See discussions, stats, and author profiles for this publication at: https://www.researchgate.net/publication/315894230 Advanced Programming in Java2 Book · January 2008 CITATIONS READS 0 6,521 1 author: Somasundaram Karuppanagounder Gandhigram Rural Institute 185 PUBLICATIONS 1,480 CITATIONS SEE PROFILE All content following this page was uploaded by Somasundaram Karuppanagounder on 11 April 2017. The user has requested enhancement of the downloaded file. PROGRAMMING IN JAVA2 Dr.K. SOMASUNDARAM Professor Dept. of Computer Science & Applications Gandhigram Rural University Gandhigram - 624 302 Tamil Nadu ACKNOWLEDGEMENT I would like to thank all my MCA and M.Sc-I.T. students (1995-2007) for whom I learned Java. I thank my wife Mrs.S.Gomathi and sons S.Praveen Kumar and S.Magesh without whose support, care, patience and encouragement I could not have written this book. I thank Mrs.T.Vasantha for typing the entire manuscript by deciphering my handwriting. Thanks to Mr.S.Domnic and Mr.K.Paulraj for beautifying the Java codes using Trita, to Mrs.T.Kalaiselvi for her help in proof reading the manuscript, to Mrs.M.Mary Shanthi Rani and Mr.V.Pechi for their help in editing the final manuscript. I thank the Educatioanl Representative of JAICO Publishing House, who initiated this project and co-ordinated to bring the book to publication. Thanks to the book reviewer for his/her constructive suggestion to include the Chapters on Swing and JDBC which added more value to the book. It is a pleasure to thank JAICO Publishing House for publishing this book in excellent look and feel. Date: April 2007 Dr.K. SOMASUNDARAM ACKNOWLEDGEMENT I would like to thank all my MCA and M.Sc-I.T. students (1995-2007) for whom I learned Java. I thank my wife Mrs.S.Gomathi and sons S.Praveen Kumar and S.Magesh without whose support, care, patience and encouragement I could not have written this book. I thank Mrs.T.Vasantha for typing the entire manuscript by deciphering my handwriting. Thanks to Mr.S.Domnic and Mr.K.Paulraj for beautifying the Java codes using Trita, to Mrs.T.Kalaiselvi for her help in proof reading the manuscript, to Mrs.M.Mary Shanthi Rani and Mr.V.Pechi for their help in editing the final manuscript. I thank the Educatioanl Representative of JAICO Publishing House, who initiated this project and co-ordinated to bring the book to publication. Thanks to the book reviewer for his/her constructive suggestion to include the Chapters on Swing and JDBC which added more value to the book. It is a pleasure to thank JAICO Publishing House for publishing this book in excellent look and feel. Date: April 2007 Dr.K. SOMASUNDARAM ACKNOWLEDGEMENT I would like to thank all my MCA and M.Sc-I.T. students (1995-2007) for whom I learned Java. I thank my wife Mrs.S.Gomathi and sons S.Praveen Kumar and S.Magesh without whose support, care, patience and encouragement I could not have written this book. I thank Mrs.T.Vasantha for typing the entire manuscript by deciphering my handwriting. Thanks to Mr.S.Domnic and Mr.K.Paulraj for beautifying the Java codes using Trita, to Mrs.T.Kalaiselvi for her help in proof reading the manuscript, to Mrs.M.Mary Shanthi Rani and Mr.V.Pechi for their help in editing the final manuscript. I thank the Educatioanl Representative of JAICO Publishing House, who initiated this project and co-ordinated to bring the book to publication. Thanks to the book reviewer for his/her constructive suggestion to include the Chapters on Swing and JDBC which added more value to the book. It is a pleasure to thank JAICO Publishing House for publishing this book in excellent look and feel. Date: April 2007 Dr.K. SOMASUNDARAM PROGRAMMING IN JAVA2 CONTENTS Acknowledgements Preface V XV Introduction 1.1 Object-Oriented Programming Concepts Encapsulation Inheritance Polymorphism 1.2 Features of Java Language 1.3 Types of Java Programs 1.4 Java Architecture Exercise – 1 1–9 1 2 Literals, Data Types and Variables 2.1 Literals 2.1.1 Integer Literals 2.1.2 Floating Point Literals 2.1.3 Character Literals 2.1.4 String Literals 2.1.5 Boolean Literals 2.2 Data Types 2.2.1 Integer Types 2.2.2 Floating Point Types 2.2.3 Character Type 2.2.4 Boolean Type 2.3 Variables Exercise – 2 11 - 18 11 11 12 12 13 13 13 14 15 15 16 16 18 3 The Structure of a Java Program 3.1 Structure of a Java Program 3.2 Comments 3.3 Expressions and Statements 3.4 Type Conversion 3.5 Block Statements and Scope Exercise – 3 19 - 27 19 21 21 22 24 27 1 i 5 5 6 9 4 Operators 4.1 Arithmetic Operators 4.2 Bitwise Operators 4.3 Relational Operators 4.4 Boolean Logical Operators 4.5 Ternary Operator 4.6 Operator Precedence Exercise – 4 29 - 42 29 32 36 37 40 40 42 5 Control Statements 5.1 The if...else Statement 5.2 The switch Statement 5.3 The while Statement 5.4 The do...while Statement 5.5 The for...Statement 5.6 The break Statement 5.7 The continue Statement 5.8 The comma Statement Worked Out Problems – 5 Exercise – 5 43 - 70 43 49 52 54 55 59 62 64 65 69 6 Arrays 6.1 6.2 71 - 86 71 74 79 86 7 Classes 7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 One-Dimensional Array Multi-Dimensional Array Worked Out Problems – 6 Exercise - 6 Defining a Class The new Operator and Objects The dot Operator Method Declaration and Calling Constructors Instance Variable Hiding this in Constructor Method Overloading Passing Objects as Parameters to Methods 87 – 111 89 90 91 92 93 94 96 101 102 Worked Out Problems – 7 Exercise – 7 104 110 i 8 Inheritance 8.1 Creating Subclasses 8.2 Method Overriding 8.3 Final Class 8.4 Final Method 8.5 Final Variables 8.6 Object Destruction and Garbage Collection 8.7 Recursion 8.8 Static Methods, Block and Variables 8.8.1 Static Method 8.8.2 Static Variables 8.8.3 Static Block 8.9 Abstract Classes Worked Out Problems – 8 Exercise – 8 113 – 136 113 115 119 120 122 122 123 124 124 125 127 128 131 135 9 Packages and Interfaces 9.1 Package 9.2 The import Statement 9.3 Access Modifer 9.4 Interfaces Defining Interfaces Implementing an Interface Worked Out Problems – 9 Exercise – 9 137 - 154 137 138 140 145 145 145 150 153 10 Wrapper Classes 10.1 The Number Class 10.1.1 Byte Class 10.1.2 Short Class 10.1.3 Integer Class 10.1.4 Long Class 10.1.5 Float Class 10.1.6 Double Class 10.2 The Character Class 10.3 The Boolean Class Worked Out Problems – 10 155 – 177 155 156 158 160 163 165 168 170 172 173 Exercise – 10 177 iii 11 Mathematical Methods Worked Out Problems – 11 Exercise – 11 179 – 198 183 197 12 Exceptions 12.1 Types of Exceptions 12.2 Catching Exceptions 12.2.1 Nested try Blocks 12.2.2 Hierarchy of Multiple Catch Blocks 12.3 Rethrowing Exceptions 12.4 Creating Your Own Exceptions 12.5 Broadcasting that a Method Throws Exception 12.6 The finally Block 12.7 Checked and Unchecked Exceptions Exercise - 12 199 – 215 200 201 204 205 207 209 210 212 213 214 13 Input and Output Classes 13.1 I/0 Streams 13.2 The File Class 13.3 Byte Stream 13.3.1 InputStream 13.3.2 OutputStream 13.4 Disk File Handling 13.4.1 FileInputStream 13.4.2 FileOutputStream 13.5 Memory Handling 13.5.1 ByteArrayInputStream 13.5.2 ByteArrayOutputStream 13.6 Filtered Byte Streams 13.6.1 BufferedInputStream 13.6.2 BufferedOutputStream 13.6.3 DataInputStream 13.6.4 DataOutputStream 13.7 SequenceInputStream 13.8 ObjectOutputStream 13.9 ObjectInputStream 13.10 Random Access File 13.11 Character Stream 13.11.1 CharArrayReader 13.11.2 CharArrayWriter 13.11.3 InputStreamReader 217 – 276 217 219 223 224 224 225 225 227 228 228 230 231 232 234 234 237 238 240 245 250 253 255 257 259 iv 13.11.4 OutputStreamWriter 13.11.5 FileWriter 13.11.6 FileReader 13.11.7 BufferedReader 13.11.8 BufferedWriter Worked Out Problems – 13 Exercise – 13 261 262 264 264 265 266 275 14 Strings 14.1 The String Class 14.1.1 Equality Operator and equals Method 14.1.2 String Concatenation With + 14.2 The StringBuffer Class Worked Out Problems – 14 Exercise – 14 277–298 277 279 281 288 291 298 15 Threads 15.1 Multitasking 15.2 Creating a Thread 15.3 States of a Thread 15.4 Multithreaded Programming 15.5 Thread Priorities 15.6 Waiting for a Thread – join Method 15.7 Controlling the Threads 15.8 Synchronizing Methods 15.9 Inter–Thread Communication Worked Out Problems – 15 Exercise – 15 299 – 341 299 301 306 307 309 311 313 318 323 330 340 16. Applets 16.1 Applet Basics 16.2 Methods of Building an Applet 16.3 Some General Methods of Applet 16.4 Displaying Text in Status Bar 16.5 Embedding Applet Information 16.6 The HTML Applet Tag 16.7 Reading Parameters into Applets 16.8 Colors in Applet 16.9 Getting Documentbase and Codebase 16.10 Interfaces in Applet 16.11 Multimedia in Applet 16.11.1 Playing Audio Clips v 343 – 368 343 347 351 351 352 353 355 356 357 358 358 359 16.11.2 Images in Applet 16.11.3 Applet Showing Other HTML Pages Worked Out Problem – 16 Exercise – 16 17 18 361 363 366 368 Graphics 17.1 Drawing Lines 17.2 Drawing Rectangles 17.3 Drawing Ovals and Circles 17.4 Drawing Arcs 17.5 Drawing Polygons 17.6 Drawing Polyline 17.7 Creating a Graphics Clip 17.8 Colors in Graphics 17.8.1 Constructors for Color Class 17.8.2 Color Methods 17.9 Setting Paint Modes 17.10 Fonts in Graphics 17.10.1 Determining Fonts Available in the System 17.10.2 Setting Fonts Worked Out Problems – 17 Exercise – 17 369 – 399 370 371 375 376 378 379 381 382 382 384 387 389 Event Handling 18.1 Delegation Event Model 18.2 Events 18.2.1 The ActionEvent Class 18.2.2 The AdjustmentEvent Class 18.2.3 The ComponentEvent Class 18.2.4 The ItemEvent Class 18.2.5 The KeyEvent Class 18.2.6 The MouseEvent Class 18.2.7 The TextEvent Class 18.2.8 The WindowEvent Class 18.3 Event Listeners 18.4 Registering Listeners with Source 18.5 Example Programs 18.5.1 Mouse Event Handling 18.5.2 Key Event Handling 18.5.3 Window Event Handling 401 – 427 401 402 404 405 407 408 408 410 412 412 413 414 415 415 417 419 vi 389 390 394 399 18.6 19 Adapter Classes Worked Out Problem – 18 Exercise – 18 Swing and GUI Components 19.1 The Origin of Swing 19.1.1 JComponent 19.2 Creating Windows in Swing 19.2.1 Creating JFrame Windows 19.3 JButton 19.3.1 Creating JButtons 19.3.2 Creating JButtons on JFrame 19.3.3 Creating JButtons on JApplet 19.3.4 Using JButton 19.4 JLabel 19.4.1 Creating JLabel 19.4.2 Creating JLabel on JFrame 19.5 JToggleButton 19.5.1 Creating JToggleButton 19.5.2 Adding JToggleButton on JApplet 19.6 JCheckBox 19.6.1 Creating JCheckBox 19.6.2 Creating JCheckBox on JFrame 19.6.3 Creating JCheckBox on JPanel 19.6.4 Using JCheckBox 19.7 JRadioButton 19.7.1 Creating JRadioButton 19.7.2 Creating JRadioButton on JFrame 19.7.3 Using JRadioButton 19.8 JList 19.8.1 Creating JList 19.8.2 Creating JList with an Array 19.8.3 DefaultListModel 19.8.4 Creation of JList Using DefaultListModel 19.8.5 Using JList 19.9 JScrollBar 19.9.1 Creating JScrollBar 19.10 19.9.2 Creating JScrollBar on JPanel JScrollPane 19.10.1 Creating JScrollPane 19.10.2 Creating JScrollPane on JPanel vii 421 424 427 429 – 581 429 430 432 433 437 437 438 444 445 447 448 449 450 450 451 452 452 453 455 456 459 459 460 461 464 464 465 468 469 471 474 475 476 478 479 480 19.11 19.12 19.13 19.14 19.15 19.16 19.17 19.18 19.19 19.20 JTextField 19.11.1 Creating JTextField 19.11.2 Creating JTextField on JPanel 19.11.3 Creating JTextField on JApplet 19.11.4 Creating JTextField on JFrame 19.11.5 Using JTextField JPasswordField 19.12.1 Creating JPasswordField 19.12.2 Creating JPasswordField on JFrame JTextArea 19.13.1 Creating JTextArea 19.13.2 Creating JTextArea on JPanel 19.13.3 Using JTextArea in Applications JComboBox 19.14.1 Creating JComboBox 19.14.2 Adding JComboBox on JPanel 19.14.3 Using JComboBox JMenuItem, JMenu and JMenuBar 19.15.1 Creating JMenuItem 19.15.2 Creating JMenu 19.15.3 Creating JMenuBar 19.15.4 Creating JMenu on JFrame 19.15.5 Creating JMenu on JApplet JDialog 19.16.1 Creating JDialog 19.16.2 Using JDialog JOptionPane 19.17.1 Creating JOptionPane 19.17.2 Using JOptionPane JFileChooser 19.18.1 Creating JFileChooser 19.18.2 Creating JFileChooser Dialog 19.18.3 Using JFileChooser JProgressBar 19.19.1 Creating JProgressBar 19.19.2 Creating JProgressBar on JFrame 19.19.3 Using JProgressBar Layout Managers 19.20.1 BorderLayout 19.20.2 FlowLayout viii 484 485 486 487 488 490 494 494 494 496 496 498 500 503 503 505 507 510 510 511 512 513 516 518 518 519 522 523 525 538 539 540 542 548 548 549 551 555 555 558 19.20.3 GridLayout 19.20.4 CardLayout 19.20.4.1 Creating CardLayout 19.20.4.2 Using CardLayout Worked Out Problems – 19 Exercise – 19 562 567 568 569 573 579 20 Networking 20.1 InetAddress 20.2 Socket Programming 20.2.1 ServerSocket(TCP/IP) 20.2.2 Client Socket(TCP/IP) 20.2.3 Server Sending Message to Client 20.2.4 Echo-Server and Client 20.3 Datagram 20.3.1 DatagramPacket 20.3.2 DatagramSocket 20.3.3 UDP Server-Client Conversation 20.4 URL 20.4.1 URL Class 20.4.2 URLConnection Exercise – 20 583 – 606 584 586 586 587 589 591 595 595 596 597 600 601 603 605 21 JDBC 21.1 607 – 654 607 608 611 611 614 615 616 626 630 634 637 653 655 – 710 655 656 657 21.2 21.3 21.4 21.5 21.6 21.7 21.8 22 JDBC and ODBC 21.1.1 Types of Drivers 21.1.2 Java SQL Package Using a JDBC DriverManager – Creating Connection Connection Interface - Creating Statements Statement Interface - Executing Statements PreparedStatement Interface CallableStatement Interface ResultSet Interface Worked Out Problem – 21 Exercise – 21 Servlets 22.1 Servlets 22.2 The HTML 22.3 Interface Servlet ix 22.4 22.5 22.6 22.7 22.8 22.8.2 HttpServlet Class Servlet Programs 22.5.1 A Simple Servlet 22.5.2 Compiling a Servlet 22.5.3 Deploying and Executing a Servlet 22.5.4 Deploying an HTML Document in a Web Server 22.5.5 Sending Data - HTML Form with GET 22.5.6 Servlet with doGet() Method 22.5.7 HTML Form with POST Method 22.5.8 Servlet with doPost() Method 22.5.9 Servlet with doGet() and doPost() Methods 22.5.10 Servlet Receiving Numbers 22.5.11 The getParameterNames() and getParameterValues() Methods Servlet with I/O File Servlet with JDBC Session Handling 22.8.1.1 Cookies 22.8.1.2 Using Cookies Session Tracking 22.8.2.1 HttpSession Interface 22.8.2.2 Using Session Worked Out Problem-22 Exercise-22 658 660 660 661 662 667 669 670 671 672 673 674 677 680 684 688 688 690 693 693 694 699 709 23 Remote Method Invocation(RMI) 23.1 Creating an RMI Application 23.2 Running the Client from a different Directory Exercise-23 711 – 720 712 717 719 24 Utility Classes 24.1 GregorianCalendar Class 24.2 Scanner Class 24.2.1 Scanning a String within the Program 24.2.2 Scanning a Console 721 – 747 722 726 729 730 24.3 24.2.3 Scanning a File Formatter Class 24.3.1 Format Syntax 24.3.2 Conversion Characters for Numeric Type x 731 732 732 733 24.4 24.3.3 24.3.4 24.3.5 24.3.6 Console 24.4.1 Conversion Characters for Date and Time 734 Formatting Numbers 737 Formatting Output to Console 738 Formatting Date and Time 739 Class 741 Using readPassword, format and printf Methods 742 24.4.2 Using reader and writer Methods 743 Worked Out problem-24 745 Exercise-24 747 Reference Books Answers to Questions Index 748 749 753 ****** xi PREFACE This book is the result of the class notes prepared for a course on Java Programming to MCA and M.Sc. students for over ten years. Though I have had excellent exposure to different computer languages like FORTRAN, BASIC, COBOL, Pascal and C since 1978 for scientific computing, developing accounting packages and of course for teaching, it was a different experience to learn Java. When I started reading the Java Hand Book by Patrick Naughton in 1995, I was puzzled at the structure and syntax of a Java program. Initially when I went through the programs with more than one class, it was difficult to comprehend which is the starting point of a program. But very soon I found the awesome capabilities of Java. Those who read an Object Oriented Programming (OOP) language like Java for the first time may experience the same. This book is intended for a course on Java programming and for beginners who want to learn Java. Advanced chapters such as JDBC, Swing, Servlet and RMI will serve as a resource material for professional programmers. Though, prior knowledge of a computer language is not essential to read this book, but that will accelerate the learning speed. The second edition is updated to J2SE6 and has three new chapters on Servlets, RMI and Utility classes. This book is organized in 24 chapters. Chater 1 introduces the readers to the Java language feature and its technology. The data types are explained in chapter 2, the syntax of a Java program is given in chapter 3, and various operators in Java in chapter 4. Control statements that affect the flow of control while executing a program are discussed in chapter 5. The arrays are introduced in chapter 6. Those who have a prior knowledge of any computer language can rush through the chapters 2 to 6. A class which forms the blueprint for creating an object is discussed in chapter 7. A reader needs to spend enough time to understand every concept given in this chapter. Chapter 8 deals with the inheritance in Java. Packages and interfaces are given in chapter 9. Wrapper classes given in chapter 10 explain the different ways to create objects for basic types. Mathematical methods used for scientific and engineering calculations are given in chapter 11. Abnormal errors, called Exceptions, occurring in a Java program are explained in chapter 12. (i) Classes that deal with Input/Output are explained in detail in chapter 13. Strings in Java are dealt in chapter 14 and multithreaded programming in 15. Applet, which is a new kind of program that can travel from a web server to a client through a network is explained in chapter 16. Graphics programming is given in chapter 17. Events that provide interactivity between an user and a program are explained in chapter 18. Swing classes that help to create Graphical User Interface(GUI) screens are discussed in chapter 19. This is the largest chapter in this book. An exposure to this chapter will propel the GUI programming capability of a reader to an expert level. Variety of buttons, lists, choices are given in this chapter. Those who have prior exposure to Java language, can directly plunge into this chapter. Introduction to Networking using TCP/IP and UDP is given in chapter 20. JDBC, that helps to handle a database is given in chapter 21. Database handling using SQL and operations such as insert, update, delete and procedure call are explained in this chapter. Chapter 22 deals with Servlet. Servlets are used in enterprise applications and belong to J2EE (presently named as JAVEE5) technology. How to create servlets and invoke them through the client side HTML documents are explained in this chapter. How to compile servlets and deploy them using Sun Java Applications Server are explained. File and database handling in multitier architecture are given. Cookies and session tracking topics are included in this chapter. Remote Method Invocation(RMI) is given in chapter 23. The basic concepts of creating a client and calling remote objects are explained in this. Chapter 24 explains some of the utility classes which are used in common applications. Handling time, date, formating outputs and reading data from console in simple way are discussed in this chapter. All the chapters contain programs to illustrate the concepts dealt in that chapter. Most chapters have programs for real life problems. Readers can redo them, add or improve them depending on their need as a project. Questions are given in each chaper to test the readers’ understanding. Any suggestions or comment on any aspect of the book can be sent to the author’s e-mail id: somasundaramk@yahoo.com. ****** (ii) This book covers l OOP l Wrapper Classes l Networking l Data Types l Exceptions l JDBC l Operators l I/O Classes l Servlets l Control Statements l Threads l RMI l Arrays l Applets l Scanner Class l Classes l Graphics l Formatter Class l Inheritance l Event Handling l Console Class l Interfaces l Swing l Covers J2SE6 Key Features of the book v Simple language v Clean and crisp description and explanation v Depth of explanation to the required level v Complete program for each concept v Hard to understand concepts are explained through appropriate conceptual diagrams v Review questions and exercises for each chapter v 234 complete programs v 37 programs for real life problems v 187 figures and 53 tables v Highlighter for all important concepts v Outcome after reading a chapter v Textbook for MCA., M.Sc., B.E., B.Sc. and B.C.A. courses v Updated to J2SE6 About the Author Dr.K. Somasundaram is a Professor & Head of Dept. of Computer Science & Applications at Gandhigram Rural University. He obtained his Ph.D. degree in Computational Physics from the Indian Institute of Science, Bangalore and M.Sc. degree in Physics with specialisation in Electronics from the University of Madras. His teaching experience spans over two decades to undergraduate and postgraduate courses. He has developed several software for scientific and commercial applications. He has contributed to various major journals and is a life member of the Indian Society for Technical Education. 1 Chapter 1 INTRODUCTION In this chapter, basic concepts of object-oriented programming (OOP), features of Java language and Java language architecture are explained. 1.1 Object-Oriented Programming Concepts The object-oriented technique is based on three basic concepts. They are: · Encapsulation · Inheritance · Polymorphism Encapsulation Many computer languages which came earlier, like FORTRAN, BASIC, Pascal, C, etc., handled data in an ‘open’ manner. Every component (like subroutines, functions) in the program written in those languages can access data defined for the whole program. This feature, though advantageous in many occasions, has some disadvantages in few cases. When a data is declared for all components of a program, any component in that program can alter the data. But, there are problems in which a data is to be protected from modification by all components of the program, barring a particular component. Not only data, but also the procedures that manipulate the data are to be guarded against misuse by other components of a program. Each procedure or method defined for a specific task is allowed to be accessed only by a particular component or by all other components of a program in varying 2 Programming in JAVA2 degrees. This mechanism of providing protection to data and methods of a program is called encapsulation. In Java language, encapsulation is realized through a description concept called class. A Java class contains variables representing data and methods that manipulate the data. The methods describe the way in which the data is manipulated. The variables and methods of a class are called members of the class. The members of a class can be declared as private or public. Private members are accessible only within the class. Public members can be accessed both internally and from external components. Fig.1.1 gives a view of a Java class. Class Private private Access to External Components Public Data Private Method Public Method Communication Channel to External Components Fig.1.1 A Conceptual View of a Java Class Public data and methods can be accessed by other components (objects) of a program. The private data and method can be accessed only by that class members. This mechanism provides protection to private members. The only way to access a private member by an external component is through the public method, which is well defined (by the user). Thus public methods encapsulate the data and method and act as an interface. The public method provides a channel for communication with external components. A class itself cannot be used as such. Realistic entities, called objects, are to be created as per the description of the class, like buildings are constructed using blueprint. Only objects constitute a Java program. Public methods provide communication among objects through which messages are exchanged between objects. Introduction 3 Message Object2 Object1 Message Object3 Object4 Fig.1.2 Objects Constitute a Java Program Inheritance A program module is developed for a particular task. There may be another task, which needs all functionalities of the previous module and a few additional capabilities. In such a case, generally, a new module is developed. Just for a few additional functionalities, one spends time on writing a new module, in which most of the functionalities of the previous module is repeated. Inheritance is used to avoid this repetition. The properties of a module prepared for a task can be inherited in another module and only the additional capabilities required are to be added in that to perform the new task. For example, if there is a module which finds the area of a rectangular surface, then this functionality can be inherited in another module to calculate the volume of a rectangular box. The new module, calculating the volume, need not repeat the procedure for calculating the area. This module needs to have only the procedure to multiply area and height to find the volume. This inheritance property helps to build reusable codes to build complex modules. In Java, a class is created for carrying out a task. Properties of such classes can be inherited into another class. The process of inheritance can be continued down to any level. Java also provides a mechanism to extract common properties of several classes into a single class, one level above the current level in the class hierarchy. Such classes may not contain exact details, but may only give the broad concept. Such classes are called abstract classes. Fig.1.3 shows the concept of inheritance. 4 Programming in JAVA2 Matter Living Human NonLiving Plant Indian Pakistani Tamilian Gujarati Male Female Children Adults Fig.1.3 The Concept of Inheritance Matter describes common properties of things present in the universe. The living class gives properties of matter and properties of living thing. The human class has properties of matter plus the properties of living things plus properties of human. In a similar way, inheritance continues down in the inheritance ladder. Polymorphism Polymorphism refers to the behavior of the same entity behaving differently in different situations. For example, you feel happy when you receive a good news, feel sad on seeing that you failed in an examination, feel angry when someone teases you and so on. In all the situations, there is only one person, you, but behaving differently. In Java, one method can be defined in a class, which can perform different tasks depending on the context. Polymorphism in Java is realized through overloading methods and overriding methods. Introduction 1.2 5 Features of Java Language Java language has some special features, using which programmers can write fast, complex, safe and robust programs. Some of such important features are: Safe Java does not provide any pointers like in C or C++. Hence, the memory locations of a system cannot be accessed through a Java program. Therefore, any program developed in Java cannot be used to hack a system. Robust Errors that occur at runtime can be handled easily in Java. Java provides exception handling feature to overcome many runtime problems, like divide by zero, memory out of range, input-output, file not found, etc. Using this feature, a user can properly exit or come out smoothly without the program hanging. Multithreaded Java language provides an environment by which several tasks can be initiated and managed easily. Such a feature is called multithreading. Architecture Neutral A program written and compiled in one platform can run on any other platform running under any type of operating system. Internet Ready Java has the capability to handle TCP/IP packets. Hence Java can be used for internet application. It has several classes for internet programming which can be used for client/server programming. Simple Many authors of Java have quoted that Java language is simple to learn. No, Java is not that much simple to learn. It is because the capabilities of Java tools are high and one needs to put an effort to understand the Java programming concepts and use them. 1.3 Types of Java Programs Using Java language, two types of programs can be written. They are: 6 Programming in JAVA2 Application Program Java can be used for writing programs that run in a PC under the control of the operating system in that machine. Such programs are termed as application programs. Applet Programs can be written and compiled to give what is called bytecodes. These bytecodes can be downloaded mostly from a remote server and executed without any control from the local operating system. Such programs are called applets. 1.4 Java Architecture Java programming technologies: · · · · Java Java Java Java environment is based on the following four programming language class files Application Programming Interface (API) Virtual Machine (JVM) The Java source program is created using the features of Java language. The source program is then compiled using the Java compiler, javac, supplied in Java Development Kit (JDK). After compilation, Java class files are created. These class files are in the form of bytecode. These bytecodes can be in the same machine (in application program) or may travel across the network (in applet) and reach the local machine. The Java Virtual Machine executes Java class files and Java API class files as required for Java class files. The API class files have Java native methods that interact with the local operating system. The JVM is a virtual computer developed in software. The combination of JVM and API is called Java platform (see fig.1.4). Introduction Demo.java Java Source File Java Compiler From Network or Local Machine 7 Text Editor javac bytecode Demo.class Java Class Files Java Virtual Machine String Class java(in JDK) java(in JDK) Result Java Platform Java API Object Class… String Class… Local Operating System Fig.1.4 Java Architecture The Java platform is different for different machines. Java platform for Unix, Windows, Macintosh, etc. are different from one another. It is this architecture that makes a Java program to write once, compile once and run in any platform. For a Java program developer, it appears that the program he/she developed can run in any type of platform. The variation in the hardware environment is taken care by different JVMs for different machines, leaving the source program compatible to all types of machines. Hence, a Java program becomes platform independent (see fig.1.5). 8 Programming in JAVA2 Java Program Java Platform for Unix Fig.1.5 Java Platform for Macintosh Java Platform for Window Platform-Independent Java Program After reading this chapter, you should have learned the following concepts:. Ü Object-oriented programming is based on three concepts: encapsulation, inheritance and polymorphism. Ü Objects consitute a Java program. Ü Java language is safe, robust, internet ready and architecture neutral. Ü Java supports two types of programs: applet and application. Ü Java Virtual Machine (JVM) is an abstract computer built using software. In the next chapter, you will learn about Java literals, data types and variables. Introduction Exercise-1 Fill in the blanks 1.1 The basic principles which form the object-oriented programming are _______, _______ and _______ . 1.2 The mechanism of providing required protection to the components of a program is known as _________ . 1.3 The concept of encapsulation is described in the _________ . 1.4 Java objects are derived from the ________ . 1.5 The absence of pointers in Java helps to write _________ programs that do not hack the system. 1.6 A Java program can be run in any computer running under any operating system. (True/False) 1.7 An application program is run in a computer under control of the ________ in that computer. 1.8 _________ program runs without the control of the _________ . 1.9 Java Virtual Machine and ___________ form the Java platform. 1.10 When a Java program is compiled, it gives ________ files. 1.11 Java programs are platform 1.12 Java Virtual Machine is a virtual computer built using _______ . _________ . * * * * * * 9 10 Programming in JAVA2 BLANK 11 Chapter 2 LITERALS, DATA TYPES AND VARIABLES In this chapter, Java constants called literals, data types and variables are explained. 2.1 Literals Entities that do not change their values in a program are called constants or literals. While solving real-life problems, one comes across different types of literals. Java provides different literal representations for them. 2.1.1 Integer literals A whole number is called integer. For example, 25, 75, 399, etc. are integers. Java supports three types of integer literals: decimal, octal and hexadecimal. The above integer numbers are examples of decimal integer literal. Octal integer literals start with 0 (zero) and are followed by octal digits 0 to 7. For example, 0, 037, 02374 are octal integer literals. Hexadecimal integer literals start with 0x (or 0X) and are followed by hexadecimal digits 0 to 9, A to F (a to f). For example, 0X29, 0X3A7, 0X2AB9 are hexadecimal integer literals. Java also provides integers of large magnitude called long integers. To denote such long integers, the letter L (or l) is appended to the literals. For example 732999456789425L and 0777765237423742517432567L represent long decimal integer literal and long octal integer literal respectively. 12 Programming in JAVA2 2.1.2 Floating Point Literals Numbers with decimal point and fractional values are called floating point literals. These literals are represented in two forms, standard and scientific. In standard notation, integer part and fractional part are separated by a decimal point. For example, 75.23749 is in standard notation. In scientific notation, a floating point number is followed by the letter E (or e) and a signed integer. The representations 6.237E-35, 4.792E18 and 42e+138 are in scientific notation standing for 6.237x10 -35, 4.792 x 10 18 and 42x10 138 respectively. The accuracy of numbers used in a program depends on the storage capacity inside the computer to store that number. Two standard precisions are used in Java, float and double. ‘float’ is called single precision and ‘double’ is a double precision. By default, all floating point literals are stored in double precision. In order to specify the precision, floating point literals can be appended with f (or F) for float and d (or D) for double. For example, 2.342f denotes that the number be stored in single-precision float and 7.2345678902d or 7.234568902D denotes that the number be stored in double-precision double. 2.1.3 Character Literals Single characters in Java are called character literals. In Java, characters belong to 16-bit character set called Unicode. Java character literals are written within a pair of single quote. For example ‘a’, ‘z’ represent character literals. There are certain characters that cannot be printed. Further, in certain occasions, a character like single quote (‘) itself is to be written as character literal. To represent such characters, Java provides a set of character literals called escape sequence. Table 2.1 gives the escape sequence. Table 2.1 The Escape Sequence Characters Escape Sequence \ddd \Uxxxx \’ \” \\ \r \n \f \t \b Description Octal character represented in ddd Hexadecimal Unicode character Single quote Double quote Backslash Carriage return New line Form feed Tab Backspace Literals, Data Types and Variables 13 2.1.4 String Literals A sequence of characters written within a pair of double quote is called string literal. For example: “This is a String” “You can put anything here” “1234 * special characters” “next \n line” “\” within double quote\”” are all string literals. Notice that the escape sequence characters are written as such. String literals are to be started and ended in one line only. 2.1.5 Boolean Literals In Java, boolean literals take two values, true or false. These two values are not related to any numeric value as in C or C++. The Boolean value true is not equal to 1 and false is not equal to 0. 2.2 Data Types While solving real-life problems, one comes across a variety of data types. Therefore, any computer language should be able to handle such data types. Java supports eight basic types. The eight basic types fall under the following four groups: Integers Integers are whole valued signed numbers. They are byte, short, int and long. There are four types in this. Floating Point Numbers Real numbers, with fractional values and with decimal point, are covered under this category. They are covered under two types, float and double. Characters Single characters are represented through char type. Boolean Boolean logical values are handled under the type boolean. 14 Programming in JAVA2 2.2.1 Integer Types Integers in Java are handled in four basic types: byte, short, int and long. All types are signed and take positive and negative values. The width of each type is defined by Java language and do not depend on the machine in which the program is executed. The width of each type is prefixed and is platform independent. This is one of the important aspects of Java language in handling integer numbers. byte byte is the lowest size integer. byte is signed and is 8-bit width. It‘s value range from -128 to 127. byte variables are declared by the keyword byte. Example : byte a, buff; short short type is 16-bit width and is signed. It takes the value form -32,768 to 32,767. The short type integers are declared by the keyword short. Example : short sn, num; int The int type is a signed integer of 32-bit width. It takes up the value from -2147483648 to 2147483647. It is the most commonly used type in Java programs. The int type integers are declared by the keyword int. Example : int n, numb; long The long type is a signed integer of 64-bit width. It takes values from -9223372036854775808 to 9223372036854775807. The long type integers are declared by the key word long. Example : long factorial, star_count; G The range of integer values for each integer type is defined by Java language and does not depend on the computer on which the numbers are generated. Literals, Data Types and Variables 15 2.2.2 Floating Point Types Numbers with fractional values are called floating point numbers and are known as real numbers in older languages like FORTRAN. The floating point numbers are represented in two forms, float and double. float In float type, the numbers are specified in 32-bit width. It takes value from 3.43e-038 to 3.43e+038. This is a single precision. Single-precision numbers are processed efficiently. The float type variables are declared by the keyword float. Example: float x, area; By default, all floating point numbers are treated as double. Hence, explicit specification is required when initializing float variables. To represent a float, the number is to be appended with f. Example: float x = 85.25f; double The double type floating point numbers are represented in 64-bit width. This is a double-precision representation. It takes value from 1.7e-308 to 1.7e+308. By default, all floating point numbers assume this form. It is the most commonly used form. The double type variables are declared by the keyword double. Example: double volume, average; 2.2.3 Character Type Single characters are handled by char type. It is a 16-bit code. Therefore, it can represent 65,536 distinct characters. In Java, this 16-bit representation of characters is called Unicode. It covers a large set of language characters in the world. For example, characters of English, Gujarati, Telugu, Tamil and Hindi languages are defined in the Unicode character set in addition to several other languages. The char type variables are declared by the key word char. Example: char choice, flag; The char type is associated with ASCII value, which is a subset of unicode value. Therefore, char type can also be associated with int values. For example, character ‘A’ is represented by the value 65. G Characters defined in Java are 16-bit width and are called Unicode characters. 16 Programming in JAVA2 2.2.4 Boolean Type The logical values true and false are handled by boolean type. The boolean values true and false are not associated with any numerical value. (In C or C++, zero is treated as false and non-zero value as true). The boolean type variables are declared by the keyword boolean. Example: boolean flag, full, empty; 2.3 Variables Variables, as the name indicates, take different values during the execution of the program. A few authors term variables as an identifier. A variable is any combination of letter, number, underscore and $ sign. The variable must not begin with numbers. A letter may be any Unicode character defined for a language. There is no maximum limit on the total number of characters that form the variable. A Few Valid Java Variables Are: sum _max total_val $value area Total fact_num A Few Invalid Java Variables Are: 2nd_class avg val double min-val total/ length&breadth float float and double are Java-reserved words and hence invalid. Java variables are case-sensitive, i.e., uppercase letters are different from those of lowercase. Therefore, the variables, sum and Sum, are different. All Java variables required for the program must be declared before it is used and it can be placed anywhere in the block where they are used. Declaring A Variable A variable is declared with a type it is going to store. An initial value can also be assigned along with the declaration. The general form of declaring a variable is : type variable [=value], variable [=value]; Example : int x, y, z; int a, b = 45, c; float p, q = 7.253f; char c, choice = ‘y’; Literals, Data Types and Variables 17 Scope of Variables The scope refers to the validity of a variable across the Java program. The scope of a variable is limited to the block defined within the braces { and }. It means a variable cannot be accessed outside the scope. Default Values for Basic Types When variables are declared in a program, they need to be assigned some value before they are used in that program. When no value is assigned after declaration, the basic types assume certain default initial values. Table 2.2 shows the default values that variables take. Table 2.2 Default Initial Values for Different Types Type char byte short int long float double boolean G Initial Value null 0 0 0 0L 0.0f 0.0d false The scope of variables is restricted to the block in which it is defined. After reading this chapter, you should have learned the following concepts: Ü Constants defined in Java are called literals. Ü Characters defined in Java are called Unicode characters. Ü Java defines eight basic types: byte, short, char, int, long, float, double and boolean Ü The range of integer values for each integer type is defined by Java language and does not depend on the computer in which the numbers are generated. In the next chapter, you will learn the structure and syntax of a Java program. 18 Programming in JAVA2 Exercise-2 I. Fill in the blanks 2.1. 2.2. 2.3. 2.4. 2.5. 2.6. 2.7. 2.8. 2.9. 2.10. 2.11. 2.12. Constants are called as ______ in Java language. A hexadecimal literal starts with ________ . 035 is a/an ________ integer. In Java language the precision of a number _______ on the machine in which the program is executed. There are _____ basic types in Java. _____ type in Java is called Unicode character. The scope of a variable is restricted to _________ in which they are declared. In the following list ________ are invalid Java variables: Sum _Max $value 1class Mat-value float For engineering and scientific calculations ______ type will be more useful. Non-printable characters are represented by _______ characters. The default initial value for char type is _________ . The value 75.25 as such is to be assigned to a _______ type variable. * * * * * * The Structure of a Java Program 21 3.2 Comments Comments can be inserted into a Java program in three different forms. In the first form, comments can be written in a single line by placing // at any location of a statement. All statements made after // and till the end of the line will be treated as comment. Example: i) ii) iii) // This is a first Java program a = p * Q ; // making a multiplication int x, y ; //declaring two int types. In the second form, comments running into multiple lines can be made. In this form, comments start with /* and end with */. The beginning /* and ending */ can be in the same or different lines. Example: i) ii) /*_____________________________________________ This program is developed to find a prime number ————————————————————————*/ /* This is an example for multi line comment */ The third form of comment is meant for generating an HTML file that documents your program. This form of comments starts with /** and ends with */. 3.3 Expressions and Statements Java expressions, like in any other language, consist of variables and literals separated by operators. A Java expression will be of the form: { } variable or literal Operator { } variable or literal An example for an expression is : 40 * m + total / numb - 25 The operands in the expression may be the same or different type. If the operands are of the same type, the resulting value of the expression is also the same type. Suppose, if all variables and literals are int type, the resulting value is int type. 22 Programming in JAVA2 When a Java expression is assigned to a variable, it becomes a statement. The general form of a statement is: Variable = expression ; 3.4 Type Conversion It is important to know beforehand what type an expression will give when it is evaluated. It is necessary because an expression may contain different types. Java has mechanisms to handle different types present in an expression during evaluation or while assignment. Type conversions of primitive types occur while evaluating an expression or during assignment. Java does the conversion through two mechanisms, automatic promotion and type casting. Automatic Promotion Java automatically converts variables or literals of lower precision type to a higher precision type during the evaluation of expression or during assignment. This is known as automatic promotion or widening. When unary operators like ,+,--,++ etc. operate on an operand of type byte or short, the operand will be converted to int type, otherwise the operands are left as such. When binary operations take place, the type of the operands are checked. If one of the operands is double, the other will be converted to double. If one of the operands is float, the other will be converted to float and if one of the operands is long, the other operand will be converted to long, otherwise the two operands will be converted to int (if the operands are of type byte or short). Example: i) byte b1 = 35; byte b2 = –b1; The second statement will give promoted to int. ii) compile error because b1 is automatically byte b1 = 25; byte b2 = 14; byte b3 = b1+b2; The third statement will give compile error as both b1 and b2 will be promoted to int before the binary operator + is operated. Hence, the addition will give an int result, whereas the left hand side b3 is a byte. iii) byte b1 = 25; byte b2 = 14; int n = b1+b2; The Structure of a Java Program 23 The third statement is valid and correct. Java also does automatic conversion while assigning values to variables in a statement: destination = source; where the source may be an expression or variable or even a literal. In such assignments, if precision of the destination is larger than the source, Java automatically converts the lower precision value (say int) to higher precision value (say long). Table 3.1 shows the source type and destination type. Table 3.1 Source Type Valid Type Conversion Destination Type byte short char int long float short, int, long, float, double int, long, float, double int, long, float, double long, float, double float, double double Fig. 3.1 shows the widening type conversion. char byte short int long float double Fig.3.1 Widening Type Conversion Widening can take left to right as indicated in the arrow mark in fig.3.1 in consecutive stages or hop one or more stages in between. For example, byte can directly be converted to long type. G byte and short type are automatically converted to int in an expression. Hence, the destination type should be declared according to this conversion. 24 Programming in JAVA2 Type Casting There are situations where incompatible type conversion is needed, where a higher precision type is being assigned to or converted to a lower precision. For example, it may be needed to get an int type from a double type or a byte from a float. This process is known as narrowing or down casting. The narrowing process will result in loss of bit and the value obtained may be incorrect. Therefore, a programmer must know the consequence of narrowing before effecting it. The type conversion is to be done explicitly by using the keyword type. The general form of type casting is: type variable = (type) expression; G Whenever incompatible type conversion is needed, type casting is used. 3.5 Block Statements and Scope Statements written in single lines are simple statements. There are occasions, where a group of statements are to be treated as one unit. In such situations, several simple statements are enclosed between a pair of braces { and } and is called block statement. Blocks define the scope of variables. As we have seen earlier, the scope of variables is restricted to the blocks in which they are declared. Blocks can be nested. The following program 3.3 illustrates the use of nested block statement: Program 3.2 class BlockDemo { public static void main(String args []) { int num = 24; double y; { int i = 45, k; k = num + i; System.out.println(“k = “ + k); } y = num / 3.0; System.out.println(“y = “ + y); } } The Structure of a Java Program 25 The above program gives the following output: k = 69 y = 8.0 The variables i and k are declared inside the inner block. Hence, their scope is valid only in that block. Outside the block, i and k cannot be accessed. The variables num and y are declared in the outer block and, therefore, can be accessed in both blocks. Consider the following program 3.3: Program 3.3 // This program illustrates the scope of variables // in nested blocks. // somasundaramk@yahoo.com class Scope { public static void main(String args []) { // main block int num = 25; double y; { // second block int i = 45; int k; k = num + i; // num can be accessed here System.out.println(“ K = “ + k); } // second block ends y = k / 3.0; // k is outside its scope. hence // compile error will occur System.out.println(“ Y = “ + y); } // main block ends } The statement y=k/3.0 in program 3.3 scope and hence will produce compile error. attempts to access k outside its Though Java restricts the scope of a variable to the corresponding block, variables with identical name can not be declared in two blocks. For this reason, the following statements will give compile error: { . . . int i ; { int i ; . . . // i is defined already // will give error 26 Programming in JAVA2 } } The following program 3.4 illustrates the concepts discussed in this chapter: Program 3.4 /* This program illustrates the following concepts: Single-line comment multi-line comment statement block type casting */ class Program33 { public static void main(String args []) { int n = 2785, i = 15, ix; double x = 76.89, y, z, mix; byte bn; { int m = 25, k; k = m + i; // i can be accessed here also System.out.println(“k = “ + k); } // scope of k and m ends y = n / 26.85; // z = k/2.5; // do not try this statement bn = (byte)n; // converting int to byte ix = (int)x; // converting double to int System.out.println(“y = “ + y); System.out.println(“n = “ + n + “ byte n = “ + bn); System.out.println(“x = “ + x + “ int x = “ + ix); } } The above program gives the following output: k y n x = = = = 40 103.570100409074 2785 byte n = –31 76.89 int x = 76 The Structure of a Java Program 27 After reading this chapter, you should have learned the following concepts: Ü The structure of a Java program Ü Making comments in a Java program Ü Scope of variables Ü Automatic promotion of byte and short to int Ü Type casting In the next chapter, you will learn about the various operators defined in Java language. Exercise-3 I. Fill in the blanks 3.1. A class is defined within a pair ________ . 3.2. Each statement in a Java program is terminated with _______ . 3.3. A Java program must contain a ________ method. 3.4. Comments in Java program can be made in _______ ways. 3.5. Java automatically converts byte and short to _______ . 3.6. When incompatible type conversion is needed _______ is used. 3.7. A set of statements enclosed between { and } is called ______ statement. 3.8. The scope and life of a variable is restricted to the _____ in which they are declared. 3.9. The file name of a Java program must be the same as that of the ______ name. 3.10. Variable names defined in different blocks can _______ the same . 3.11. An expression with operands of type byte and float will give a result of ______ type. II. Write Java programs for the following: 3.12. Write a program that prints your address. 3.13. Write a program to find the average of three byte type numbers. 3.14. Write a program to find the sum of five short type numbers. * * * * * * 28 Programming in JAVA2 Blank 29 Chapter 4 OPERATORS In this chapter, various operators used in Java language are explained. Operators operate on operands and cause changes in the operand value or give a new value. Java provides operators in four categories. They are: 1. Arithmetic operators 2. Bitwise operators 3. Relational operators 4. Logical operators Operators may operate on one, two or three operands. Operators operating on single operand are called unary operators, on two operands are binary operators and on three operands are ternary operators. Unary operators are further classified as prefix operator and postfix operator. When the operator precedes the operand, it is called prefix operator and when it follows, it is called postfix operator. 4.1 Arithmetic Operators Arithmetic operators operate on arithmetic variable and arithmetic literals. The arithmetic operators and the character symbol that represent them are listed in table 4.1. 30 Programming in JAVA2 Table 4.1 Operation Arithmetic Operators Operator Symbol Add Subtract Multiply Divide Modulus + – * / % The first three operators carry the same meaning as we do in normal calculations. The division operator gives integer division if both operands are integer and floating point division, if one of the operands is a floating point. For example: 18/4 gives 4 18/4.0 gives 4.5 Modulus Operator The modulus operator % gives remainder value after a division. for both integer and floating point value. It works For example: 25 % 5 will give 0 25 % 7 will give 4 25 % –7 will give 4 –25 % 7 will give –4 25.8 % 7 will give 4.8 25.8 % 7.0 will give 4.8 25.8 % 7.5 will give 3.3 (quotient is integer) G Modulus operator percentage works for both integer type and floating point values. All the five arithmetic operators are binary operators, i.e. they need two operands. However, the subtract operator can also be used as unary prefix operator as given below: y = –x; The same is applicable for + operator and can be written as: p = + q; This form, though valid and correct, is not generally used, as the statement p = q; means the same. Operators 31 Operator Assignment All the five arithmetic operators can be used in operator assignment form. This helps to avoid repeating the operands in two places of a statement. Consider the statement: sum = sum + 1; This statement can also be written as: sum += 1; This form of assigning value to the variable is called operator assignment. In general, a statement of the form: variable = variable operator expression is replaced by operator assignment form: variable operator= expression; For arithmetic operators, the following forms +=, –=, *=, /= and %= are applicable. Increment and Decrement Operators There are two more arithmetic operators ++ and ––. Both are unary operators and operate only on integers. The ++ increment operator increases the operand’s value by 1. Both can operate in prefix form ++n or in postfix form n++, where n is a variable. In prefix form, the value of the operand n is incremented first and the operand is used. In postfix form, the value of the operand is used first and then incremented. The same is applicable to the decrement operator ––. Program 4.1 illustrates the use of increment and decrement operators. G The prefix operator (++variable or ––variable) changes (increment by one or decrement by one) the value of the variable first and uses the variable. When postfix operator (variable++ or variable––) is used, the value of the variable is used in the operation and then changes the value (increment by one or decrement by one). Program 4.1 // This program illustrates the use of increment and // decrement operators. class InrDcr { public static void main(String args []) 32 Programming in JAVA2 { int m = 25, p = 70; System.out.println(“m = System.out.println(“++m System.out.println(“p = System.out.println(“p++ System.out.println(“p++ “ + m); = “ + ++m); “ + p); = “ + p++); after use = “ + p); } } The above program gives the following output: m = 25 ++m = 26 p = 70 p++ = 70 p++ after use = 71 The ++ and –– operators do not operate on integer literal. 25++ or ––85 are not valid. N Therefore, The ++ and –– operators should not be operated on integer literals (like ++75). 4.2 Bitwise Operators Bitwise operators are used to manipulate individual bits of a data item. There are situations where individual bits of a data are to be modified. Java provides a set of bitwise operators. These operators operate only on byte, char, short, int and long types. The bitwise operators in Java are given in table 4.2. Table 4.2 Bitwise Operators Operation Bitwise NOT Bitwise AND Bitwise OR Bitwise exclusive OR Left shift Right shift Right shift zero fill Operator Symbol ~ & | ^ << >> >>> Operators 33 Bitwise NOT (~) This is a unary operator. It complements each bit of the operand. Consider a number 71. This number in byte type has a binary value of 01000111. a = 01000111 The NOT operation gives: ~a = 10111000 = –96 Bitwise AND (&) This AND operator, & , performs AND operation bit by bit of the operands. Consider two operands a = 71 and b = 25, represented in byte type as: a = 01000111 b = 00011001 The AND operation gives: a & b = 00000001 = 1 Bitwise OR (|) This OR operator, | , performs OR operation bit by bit. bytes a = 71 and b = 25. The OR operation gives: a | b = = Consider two 01011111 95 Bitwise Exclusive OR (^) This XOR operator, ^ , performs exclusive OR (XOR) bit by bit. In this operation, if the corresponding bits of the operands are identical, the resulting bit is 0, otherwise it is 1. For the numbers a = 71 and b = 25, the XOR operation gives: a ^ b = = 01011110 94 Left Shift Operator (<<) This operator, << , is a unary operator. It shifts each bit of the operand to the left by the specified number of positions. The general form of using this operator is: variable << n 34 Programming in JAVA2 where n specifies the number of positions each bit in the variable is to be shifted left. The leftmost bit is shifted out and the rightmost bit is filled with zero. Example: a = 25 = 0 0 0 1 1 0 0 1 The left shift operation, a << 2 specifies that each bit be shifted left by 2 positions. The result, after 1st shift is 0 0 1 1 0 0 1 0 after 2nd shift is 0 1 1 0 0 1 0 0 a = 100 Thus, the final value of a is 100. Each left shift is equivalent to multiplication by 2. One has to remember that Java promotes automatically the byte and short type to int type before evaluating them. Hence, care must be taken to handle such situation. When bits in signed integers are shifted left, the leftmost bit indicating the sign will be retained always, i.e. a negative value after the shift will also be a negative number. Example: a = = –25 10011001 The operation a << 2 will give a = = 11100100 –100 Right Shift Operator (>>) This operator >> shifts each bit of the operand to the right by a specified number of positions. The rightmost bit is shifted out and lost. The leftmost bit is sign extended. All other bits in between are shifted to right by one position. Each right shift is equivalent to divide by 2. The general form of using this operator is: variable >> n where n specifies the number of positions the bits in the variable are to be shifted right. Operators 35 Example a = = 25 00011001 The operation a >> 2 gives a = 00000110 = 6 For a signed number, the sign bit will be extended. 1 indicates that the number is negative. The leftmost bit with Example b = = –25 10011001 The operation b >> 2 gives b = 11100110 Notice that the leftmost sign bit is sign extended to the right each time and, hence, the two extra 1s at the left. Here also the problem of automatic promotion of byte and short type to int type is to be handled according to the requirement. G Both right shift (>>) and left shift (<<) operators retain the sign bits even after shifting. Hence, a programmer must be aware of the consequence of this when negative integers are used. Right Shift Zero Fill Operator (>>>) This operator, >>>, performs the same type of operation done by right shift operator, >>, except that sign bit extension is not done. Instead, zero will be inserted at the leftmost bit position for every shift. Therefore, in situations where the sign extension is unwanted, the right shift zero fill operator can be used. This operation is also called unsigned shift, as the other two shift operators, >> and <<, extend the sign bit. The general form of using this operator is: variable >>> n where n specifies the number of bit positions of the variable to be shifted right with zero fill. 36 Programming in JAVA2 Example b = = –25 10011001 The operation b >>> 2 gives b = = 00100110 38 You may compare this result with the earlier one with >> operator. The reader is again reminded of the problem of automatic promotion of byte and short type to int type by Java. In most cases, masking off the higher order bytes in the int type will provide a solution to face such situations. For all bitwise operators, the operator assignment form is also applicable. Examples 4.3 1. a = a>>3 can be written as a >> = 3 2. b = b & c b &= c 3. y = y>>>n can be written as y >>>= n can be written as Relational Operators For comparing the values of variables and literals, Java provides relational operators. Relational operators are used to relate a given value with several possible values of a variable. The results of the relational operators help to make branching, iterating a block and to terminate the block statement. The relational operators are given in table 4.3. Table 4.3 Relational Operators Operation Equal to Not equal to Greater than Greater than or equal to Less than Less than or equal to Operator Symbol == != > >= < <= Operators 37 All relational operators are binary operators. The result of operating a relational operator is boolean, true or false. They operate on operands of type char, byte, short, int, long, float and double. For string variables and literals, separate methods are used and are given in chapter 14. Examples int a = 25; int b = 75; double x = 35.87; double y = 67.43; char c1 = ‘b’; char c2 = ‘d’; 1. 2. 3. 4. 5. 6. 7. 8. 4.4 a == b a != b a < b x > y c1 == c2 c1 < c2 x > b 35 == 10 gives gives gives gives gives gives gives gives false true true false false false false false Boolean Logical Operators Logical operators operate only on boolean operands and not on numerical operands. Logical operators result in boolean values true or false. The boolean logical operators in Java are given in table 4.4. Table 4.4 Boolean Logical Operators Operation Logical AND Logical OR Logical XOR Short-circuit OR Short-circuit AND Logical unary NOT Equal to Not equal to Ternary if-else Operator Symbol & | ^ || && ! == != ?: These logical operators, except the unary NOT and ternary if-else, are binary operators. They are used in the same way as that for bitwise operators. The unary NOT complements true to false and false to true. 38 Programming in JAVA2 The following table 4.5 boolean variables A and B: Table 4.5 gives results of various logical operations on the Truth Table for Boolean Operators A B A|B A&B A^B !A False False True True False True False True False True True True False False False True False True True False True True False False The following examples illustrate the use of logical operators: Examples int a = 25; int b = 75; double x = 34.25; double y = 63.98; char c1 = ‘a’; char c2 = ‘d’; 1. 2. 3. 4. 5. 6. 7. 8. (a>b) & (x<y) = false & true = false (a>b) | (x<y) = false | true = true (c1 == c2) ^ (b > 100) = false ^ false = false (c1 != c2) ^ (b > 100) = true ^ false = true ! (a>b) = ! false = true (a>b) == (x<y) = false == true = false (a>b) != (x<y) = false != true = true (a<b) ? (x>y) : (c1 != c2) = true ? false : true = false Operators 9. 39 (a>b) ? (x>y) : (c1 != c2) = false ? false : true = true Short-circuit && and || operators From the examples given above, you will find that the expressions on both sides of the logical operators are evaluated and then only the final result is obtained. However, from the first four columns of the Table 4.5 you will notice that : i) if one of the operands of the OR operation is true, then the result is always true irrespective of the value of the other operand. ii) if one of the operands of the AND operation is false, the result is always false, irrespective of the value of the other operand. Therefore, in a logical OR operation, if the first operand has a value true, the result can be declared as true without checking or evaluating the value of the second operand. In a similar way, in an AND operation, if the first operand has a value false, the result can be declared as false without even evaluating the second operand. This feature is built into the short-circuit AND, &&, and shortcircuit OR, ||, operators. These are more efficient than & and | as they save time spent for evaluating the second operand. The following examples illustrate the use of && and || operators. Examples int a int b double x double y char c1 char c2 = = = = = = 25; 75; 34.25; 63.98; ‘a’; ‘d’; 1) (a>b) && (x<y) = false (no need to evaluate the expression x < y) 2) (c1! = c2) || (a<b) = true (no need to evaluate a<b) 3) (a>b) || (x<y) = false || true = true only in this kind of situations both operands are evaluated to get the final result. 40 Programming in JAVA2 G The short-circuit logical AND (&&) and short-circuit logical OR (||) are more efficient than logical AND (&) and logical OR (|). 4.5 Ternary Operator (?) The ternary operator, ?, operates on three operands. This operator can replace simple if-then-else statements. The general form of using this operator is: expression1 ? expression2 : expression3 The expression1 should always result in a boolean value true or false. If the expression1 results in true, the expression2 is evaluated and expression3 is discarded, otherwise, expression3 is evaluated and expression2 is discarded. Program 4.2 illustrates the use of a ternary operator. Program 4.2 // This program illustrates the use of a ternary operator. class TernaryProg { public static void main(String args []) { int mark = 75; String result; result = (mark > 40) ? “Pass” : “fail”; System.out.println(“Your Mark = “ + mark); System.out.println(“Result = “ + result); } } The above program gives the following output: Your Mark = 75 Result = Pass 4.6 Operator Precedence An expression contains a number of operators, variables and literals. A programmer must know how these operators are evaluated. Like in other computer languages, priorities are given for each operator. Operators are evaluated on the priorities allotted to them. This is called operator precedence. A good knowledge of these priorities is necessary to write unambiguous Java expressions. In most of the cases, an expression is evaluated from left to right of the expression. Unary and assignment operators take right to left association. The Java operator precedence from highest to lowest is given in table 4.6. Operators 41 Table 4.6 Operator Precedence Highest Lowest () [] ! ++ – – +(unary) -(unary) * / % + – << >> >>> < <= > >= == != & ^ | && || ?: = op= (cast) The operators in a row have the same precedence and are evaluated in the order in which they appear in the expression. Use of parentheses in an expression alters the precedence and it is hence listed at the highest precedence or priority. Example: int a=25, b=60, c=5; double x = 5.5, y; y = a+b / (2*c)–x = 25 + 60 / (2x5)–5.5 = 25 + 60/10 – 5.5 = 25 + 6 – 5.5 = 31 – 5.5 = 31.0 – 5.5 = 25.5 After reading this chapter, you should have learned the following: Ü Arithmetic operators Ü Bitwise operators Ü Relational operators Ü Logical operators and short circuit logical operators Ü Operator precedence In the next chapter, you will learn the control statements. 42 Programming in JAVA2 Exercise–4 I. Fill in the blanks 4.1. 4.2. 4.3. 4.4. 4.5. 4.6. 4.7. 4.8. 4.9. 4.10. II. There are _______ categories of operators in Java. The result of the division 7/2 is _______ . The result of the operation 7.5%2.0 is _______ . The value of y in the following statements is _______ . int x = 50, y; y = x++; The following statement is ________ (valid/invalid): y = ++70; The bitwise operators can operate on float type operands.(True/False) The sign independent bitwise operator is __________ . The equality operators operate only on integer variables or values. (True/False) The result of using logical & and logical && is the same. (True/False) The use of parentheses in an expression will alter the precedence. (True/False) Write a Java Program for the Following: 4.11. The register number, name and marks for three subjects are given. Write a program to find the average of the three marks and print it out along with the register number and name. 4.12. A cloth shop during festival seasons offers a discount of 12% on all purchases made in that shop. The bill amount for a customer is given as Rs.750.5. Write a program to calculate the discount, amount after discount and print it out. 4.13. A bank gives 6.5% per annum compound interest on deposits made in that bank. Write a program to calculate the total amount that a person will receive after the end of 4 years for a deposit of Rs.5000/-. 4.14. A motorcycle dealer sells two-wheelers to his customers on loan, which is to be repaid in 3 years. The dealer charges a simple interest of 14% for the whole term on the day of giving the loan itself. The total amount is then divided by 36 (months) and is collected as equated monthly installment (EMI). Write a program to calculate the EMI for a loan of Rs.39990. Print the EMI value in rupees. * * * * * * 43 Chapter 5 CONTROL STATEMENTS In this chapter, the statements that take the control from one location to another during execution are given. The control statements help to make branching, looping, skipping and exiting a block of codes. Basically, any computer-oriented problem can be solved using any combination of sequential, branching and looping structure. Therefore, a computer programming language should support these three structures. In this chapter, the statements supporting the branching and looping structures in Java are given. These statements help to branch or loop a segment of statements and are called control statements. 5.1 The if..else Statement This statement helps to select one out of two possibilities based on the given condition. Hence, this statement is also called as conditional if statement. The general form of the statement is: if (conditional expression) statement1; else statement2; The conditional expression should result in a boolean value. If the condition, on evaluation, gives true, statement1 is executed and the control skips statement2, otherwise statement1 is skipped and statement2 is executed. 44 Programming in JAVA2 The statement1 and the statement2 can be a simple or block statement. else part is optional and, if needed, can be left out and can take the form: The if (conditional expression) statement; In this form, the statement will be executed, if the conditional expression gives true, otherwise it is skipped. The flowchart for if...else and if... are given in fig.5.1 and fig.5.2 respectively. true false Condition Statement1 Fig.5.1 Statement2 Flowchart for if...else Statement true Condition Statement false Fig.5.2 Flowchart for if...Statement Control Statements The following statement: examples, 5.1 45 and 5.2, illustrate the if...else and if Example 5.1 int mark; String result; if (mark >= 40) result = “Pass”; else result = “Fail”; Example 5.2 double a, b, c, discr, term; discr = b*b-4.0*a*c; if (discr < 0) discr = -discr; term = Maths.sqrt(discr); root1 = (-b+term)/(2.0*a); root2 = (-b-term)/(2.0*a); Nested if..else Nested if..else statement is made by placing one if..else inside another if..else statement. Nested if..else statement helps to select one out of many choices. The general form of if..else statement is : if (condition1) if (condition2) if (condition3) statement 4 else statement 3 else statement 2 else statement 1 In the nested if..else statement, the outermost if is evaluated first. If the condition1 tested is false, the statement1 in the outmost else is evaluated and if..else ends. If the condition1 results in true, the control goes to execute the next inner if statement. If condition2 is false, statement2 is executed. Otherwise, condition3 is evaluated. If condition3 is false, statement3 is executed, otherwise statement4 is executed. 46 Programming in JAVA2 The flowchart for the nested if..else is given in fig.5.3: false Condition1 Statement1 true false Condition2 Statement2 true false Condition3 Statement3 true Statement4 Fig.5.3 Flowchart for nested if...else Statement The following program 5.1 illustrates the use of nested if..else statement: Program 5.1 //This program illustrates the nested if... else //somasundaramk@yahoo.com class NestedIf { public static void main(String args []) { String result_class; int avg_mark = 62; statement. Control Statements 47 if (avg_mark > 50) if (avg_mark >= 60) if (avg_mark >= 75) result_class = “Distinction”; else result_class = “First Class”; else result_class = “Second Class”; else result_class = “Third Class”; if (avg_mark < 40) System.out.println(“Failed”); else System.out.println(“Passed with “ +result_class); } } The above program gives the following output: Passed with First Class Another form of nested if..else is the ladder if..else statement. structure of the ladder if..else statement is : The if (condition1) statement1; else if (condition2) statement2; else if (condition 3) statement 3; else statement4; The flowchart for the above ladder if...else statement is given in fig. 5.4: 48 Programming in JAVA2 true Condition1 Statement1 false true Condition2 Statement2 false true Condition3 Statement3 false Statement4 Fig.5.4 Flowchart for Ladder if..else Statement The following program 5.2 illustrates the ladder if...else statement: Program 5.2 //This program illustrates the ladder if...else if statement. //somasundaramk@yahoo.com class IfElseIf { public static void main(String args []) { String result_class; int avg_mark = 62; if (avg_mark > 75) result_class = “Distiction”; else if (avg_mark >= 60) result_class = “First Class”; Control Statements 49 else if (avg_mark >= 50) result_class = “Second Class”; else result_class = “Third Class”; if (avg_mark < 40) System.out.println(“Failed”); else System.out.println(“Passed with “ +result_class); } } The above program gives the following output: Passed with First Class 5.2 The switch Statement The switch statement helps to select one out of many choices. This helps to write a clear statement when compared to nested if...else statements. The general form of switch statement is: switch (expression) { case val1 : statement1; break; case val2 : statement2; break; case val3 : statement3; break; . . . case valN : statementN; break; default : statement; } It is expected that the expression, when evaluated, should give discrete values in the range Val1 to valN. If the expression gives val1, the statement1 is executed and the control exits the switch block. If the expression gives val2, statement2 is executed and so on (fig.5.5). If the expression gives any value that is not matching between val1 and valN, the statement given in default is executed. The expression should give any of the type byte, short, int or char. In this way, multiple branching can be effected. The break statement when executed will take the control out of the switch block. Generally, switch statement is used for expressions that may give discrete and predefined values. 50 Programming in JAVA2 Expression = val1 Statement1 = val2 Statement2 = valN StatementN no match Statement Fig.5.5 Flowchart for switch Statement The following program 5.3 illustrates the use of switch statement: Program 5.3 // This program illustrates the switch statement. class SwitchDemo public static void main(String args []) { int month = 5; switch (month) { case 1: System.out.println(“January”); break; case 2: System.out.println(“February”); break; case 3: System.out.println(“March”); break; case 4: System.out.println(“April”); break; case 5: System.out.println(“May”); break; case 6: Control Statements 51 System.out.println(“June”); break; case 7: System.out.println(“July”); break; case 8: System.out.println(“August”); break; case 9: System.out.println(“September”); break; case 10: System.out.println(“October”); break; case 11: System.out.println(“November”); break; case 12: System.out.println(“December”); break; default: System.out.println(“No match”); } } } The above program gives the following output: May Sometimes, for several In such problems, several common to all of them can 5.4 shows how several cases case values, one common process may be required. case values can be clubbed so that statements be executed at one point. The following program can be combined: Program 5.4 // This program illustrates the switch statement. class GroupCase { public static void main(String args []) { int choice = 6; switch (choice) { case 1: case 2: case 3: System.out.println(“Numbers between 1 and 3”); 52 Programming in JAVA2 break; case 4: case 5: case 6: case 7: System.out.println(“Numbers between 4 and 7 “); break; case 8: case 9: case 10: System.out.println(“Numbers between 8 and 10”); break; default: System.out.println(“Numbers outside 1 and 10”); } } } The above program gives the following output: Numbers between 4 and 7 G The type of data handled in switch statement must be of the type byte, short, int or char. The values used must be discrete. 5.3 The while Statement The while statement is used for looping or iterating a block of statements while the given condition is true. The general form of the while statement is: while (condition) { statements; } The condition, when evaluated, must result false. As long as the condition gives true, executed. When the condition becomes false, statement. The flow of control in while statement in the boolean value true or the statement block will be the control leaves the block is given in fig. 5.6. Control Statements 53 true Condition Statements false Fig.5.6 Flowchart for while Statement When the condition tested is false in the first instance itself, the block statement will not be executed at all. The following program 5.5 shows the use of while structure: Program 5.5 // This program illustrates the use of while statement. class WhileDemo { public static void main(String args []) { int n = 10; int sum = 0; while (n > 0) sum += n––; System.out.println(“Sum of numbers from 1 to 10 is= “ + sum); } } The above program gives the following output: Sum of numbers from 1 to 10 is = 55 G In while statement, executing the codes. the condition is checked before 54 Programming in JAVA2 5.4 The do..while Statement This do..while control statement is used for looping a block of statements while the given condition is true. In this structure, the condition is tested at the end of the block. This is in contrast to the while .. statement, where the condition is tested at the start of the block. The general form of do..while statement is: do { statements; } while (condition); The condition tested can be any expression that will yield a boolean value. As long as the condition tested is true, the whole block will be executed. Once the condition tested becomes false, the control leaves the block. It is to be noted that the block is executed once before the condition is tested. Therefore, even if the condition tested is false at the first instance itself, the block statement is executed once. The flowchart of a do..while structure is given in fig.5.7. Statements true Condition false Fig.5.7 Flowchart for do....while Statement The following program 5.6 illustrates the do ... while statement: Control Statements 55 Program 5.6 // This program illustrates the use of do..while statement. class DoWhileDemo { public static void main(String args []) { int n = 10; int sum = 0; do sum += n––; while (n > 0); System.out.println(“Sum of numbers from 1 to 10 is = “ + sum); } } The above program gives the following output: Sum of numbers from 1 to 10 is = 55 G In do...while statement, the condition is checked after executing the codes. 5.5 The for ... Statement This is the third form of looping statement. This statement is a selfcontained one, that is the initial value, termination condition, iterator (increment/ decrement) are all given in the for structure itself. The general form of for statement is: for (initializer; condition; iterator) { statements; } Here, the condition can be any expression that yields boolean value true or false. The initializer is used to store the initial value for a loop variable. The iterator modifies the loop variable. The statements in the block are executed, as long as the condition tested gives true. When the condition becomes false, the control leaves the block statement. The flowchart for the for loop is given in fig. 5.8. 56 Programming in JAVA2 initializer false Condition true Statements iterator Fig.5.8 Flowchart for the for Loop Program 5.7 shows the use of for.. statement. Program 5.7 /* This program illustrates the use of for statement. This program finds the sum of all numbers from 1 up to 10. */ class ForDemo1 { public static void main(String args []) { int n; int sum = 0; for (n = 10; n > 0; n––) sum += n; System.out.println(“Sum of numbers from 1 up to 10 =“ + sum); } } The above program gives the following output: Sum of numbers from 1 up to 10 = 55 Control Statements 57 The above program 5.7 can be written in another form as given in program 5.8. The loop variable n can be declared inside the for structure itself. The iterator is optional. If there is no need for an iterator in a program, it can be left blank. Program 5.8 /* This program illustrates the use of for statement. Notice that n is declared inside the for loop. The iterator is left blank as it has been done in the block statement itself. */ class ForDemo2 { public static void main(String args []) { int sum = 0; for (int n = 10; n > 0; ) sum += n––; System.out.println(“Sum of numbers from 1 up to 10 = “ + sum); } } The for loop in program 5.8 can be improved further and written in a compact form as : for (int n=10; n>0; sum+=n––); G In a for structure, one, two or all the three components, initializer, condition, iterator, can be absent. The statement for ( ; ; ) is valid and will make an infinite loop. The following program 5.9 finds the factorial of numbers from 1 to 10. Program 5.9 // This program finds the factorial of a number using for // statement. class FactProg { public static void main(String args []) { int n = 10; long fact = 1; 58 Programming in JAVA2 for (int i = 1; i <= n; ++i) { fact *= i; System.out.println(“Factorial of “ + i + “ = “ + fact); } } } The above program gives the following output: Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of 1=1 2=2 3=6 4 = 24 5 = 120 6 = 720 7 = 5040 8 = 40320 9 = 362880 10 = 3628800 The for loops can be nested one within another as shown below: - - - - - - - - - - - - - - - - - - for (i=1; i<n; i++) // outer loop begins { - - - - - - - - - - - - - - for (k=1; k<m; k++) // inner loop begins { . . . } // inner loop ends . . . } // outer loops ends . . . The following program 5.10 illustrates the nested for loop. multiplication tables for 2, 3 and 4. It generates Control Statements 59 Program 5.10 // This program illustrates the nested for loop. class MulTable { public static void main(String args []) { int i, j, m = 4, n = 5; int prod; for (i = 2; i <= m; ++i) { System.out.println(“Multiplication Table for“ + i); for (j = 1; j <= n; ++j) { prod = j * i; System.out.println(j + “X” + i + “ = “ + prod); } System.out.println(“ “);//create one line space } } } The above program gives the following output: Multiplication Table for 2 1X2 = 2 2X2 = 4 3X2 = 6 4X2 = 8 5X2 = 10 Multiplication Table for 3 1X3 = 3 2X3 = 6 3X3 = 9 4X3 = 12 5X3 = 15 Multiplication Table for 4 1X4 = 4 2X4 = 8 3X4 = 12 4X4 = 16 5X4 = 20 5.6 The break Statement The break statement is to be used only in loops and switch statement. When this statement is executed, the control is taken out of the loop. The loop becomes dead. The flowchart for the break statement is given in fig. 5.9. 60 Programming in JAVA2 . ¯ . ¯ if(condition) break; . ¯ > start of loop ¬ - normal end of loop > Fig.5.9 The Flowchart for break Statement The following program 5.11 illustrates the use of break in a for loop: Program 5.11 // This program illustrates the use of break statement. class BreakDemo { public static void main(String args []) { int n = 5, m = 20; for (int i = 1; i <= m; i++) { if (n * i > 30) { System.out.println(“Exiting the loop”); break; } System.out.println(i + “X” + n + “ = “ + n * i); } } } The above program gives the following output: 1X5 = 5 2X5 = 10 3X5 = 15 4X5 = 20 5X5 = 25 6X5 = 30 Exiting the loop Blocks can be labeled and the break control can be made to exit any labeled block. This is called labeled break. The label for a block can be Control Statements 61 formed by using the rules to form a variable. The labeled break is useful when using nested loops. The following program 5.12 illustrates the labeled break statement: Program 5.12 // This program illustrates the use of labeled break. class LabelBreak { public static void main(String args []) { int n = 0, m = 0; loop1: while (true) { n++; m = 0; System.out.println(“\n loop1 “ + “n = “ + n); loop2: while (++m <= n) { if (n * m > 10) { System.out.println(“Exiting loop2 and loop1”); break loop1; } System.out.println(“loop2 “ + m + “X” + n + “ = “ + n * m); } } System.out.println(“outside loop1”); } } The above program gives the following output: loop1 n = 1 loop2 1X1 = 1 loop1 n = 2 loop2 1X2 = 2 loop2 2X2 = 4 loop1 n = 3 loop2 1X3 = 3 loop2 2X3 = 6 loop2 3X3 = 9 62 Programming in JAVA2 loop1 n = 4 loop2 1X4 = 4 loop2 2X4 = 8 Exiting loop2 and loop1 outside loop1 5.7 The continue Statement The continue statement is used inside the loop control blocks. When the continue statement is executed, the control skips the remaining portion of the loop and goes to the beginning of the loop and continue. The flowchart for the continue statement is given in fig. 5.10: start of loop ¬ - .. ¯ if(condition) continue; ® . ¯ > normal - end of loop Fig.5.10 Flowchart for continue Statement The following program 5.13 illustrates the use of continue statement: Program 5.13 // This program illustrates the use of continue statement. class ContinueProg { public static void main(String args []) { int i = 0; while (++i < 10) { if (i % 2 == 0) continue; System.out.println(i); } } } Control Statements 63 The above program gives the following outptut: 1 3 5 7 9 Like labeled break, labeled continue structure is also available. following program 5.14 illustrates the use of labeled continue: The Program 5.14 // This program illustrates the use of labeled continue // statement. // This program generates prime numbers between 1 and 15. // somasundaramk@yahoo.com class LabelContinue { public static void main(String args []) { int i = 1, n, max = 15; System.out.println(“Prime numbers between 1 and 15”); System.out.println(i); start: for (n = 2; n <= max; ++n) { test: for (i = 2; i < n; ++i) if (n % i == 0) continue start; System.out.println(n); } } } The above program gives the following output: Prime numbers between 1 and 15 1 2 3 5 7 11 13 64 Programming in JAVA2 5.8 The comma Statement Java allows multiple initialization and iteration in the for statement. With this capability, more than one variable can be initialized and more than one iteration can be done. Each of such statements are to be separated by a comma(,). But there can be only one conditional expression. The general form of the multiple initialization and iteration is: for (init1, init2, init3; condition; itr1, itr2, itr3) { Statements; } The following program 5.15 illustrates the use of comma statement. Program 5.15 // This program illustrates the use of comma statement. class CommaDemo { public static void main(String args []) { int n, i, sum; for (i = 1, n = 5; n > 0; i++, n—, sum = 0) { sum = i + n; System.out.println(i + “ + “ + n + “ = “ + sum); } } } The output for the above program is : 1+5=6 2+4=6 3+3=6 4+2=6 5+1=6 After reading this chapter, you should have learned the following: Ü Branching using if...else control Ü Branching using switch control Ü Looping with while, do...while and for...control Ü Using break and continue In the next chapter, you will learn about arrays. Control Statements 65 Worked Out Problems–5 Problem 5.1w The trigonometric functions Sin(x) and Cos(x) are computed using the following formula: Sin(x) = Cos(x) = x3 x – 3! x2 1 – 2! + + x5 5! x4 4! – – x7 7! x6 6! + + x9 9! x8 8! – x 11 11! – x 10 10! Calculate the Sin(x) and Cos(x) values for x=0, 0.5 and 1.5. The following expressions which represent the above are made use of: Sin(x) = m S x + n=1 m Cos(x) = 1 + S n=1 (–1) n x 2n+1 (2n+1)! (–1) n x 2n 2n! Program 5.1w /* ------------------------------------------------------------This program calculates the sin(x) and cos(x) functions. The values obtained are compared with those of Java functions. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Prob51 { public static void main(String args []) { double x, sinx, cosx; int n, fact = 1, factn, factnplus; int m = 5; for (int i = 0; i < 80; i++) 66 Programming in JAVA2 System.out.print("-"); System.out.println("\n"); System.out.println("x \t my sinx \t Java sinx \t my cosx \t Java cosx\n"); for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); for (x = 0; x < 1.6; ) { sinx = x; cosx = 1; for (n = 1; n <= m; n++) { factn = 1; factnplus = 1; for (int i = 2; i <= 2 * n; i++) factn = factn * i; for (int i = 2; i <= (2 * n + 1); i++) factnplus = factnplus * i; sinx = sinx + Math.pow(-1, n) * Math.pow(x, (2 * n + 1)) / factnplus; cosx = cosx + Math.pow(-1, n) * Math.pow(x, 2 * n) / factn; } // Reduce the fractional digits for display double sx = (int)(sinx * 1000); double cx = (int)(cosx * 1000); sinx = sx / 1000; cosx = cx / 1000; double jsx = (int)(Math.sin(x) * 1000); double jcx = (int)(Math.cos(x) * 1000); jsx = jsx / 1000; jcx = jcx / 1000; Control Statements 67 System.out.println(x + "\t" + sinx + "\t\t" + jsx +"\t\t" + cosx + "\t\t" + jcx); x = x + 0.5; } for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------------------------------------x my sinx Java sinx my cosx Java cosx -------------------------------------------------------------------------------0.0 0.0 0.0 1.0 0.5 0.479 0.479 0.877 1.0 0.841 0.841 0.54 1.5 0.997 0.997 0.07 -------------------------------------------------------------------------------- 1.0 0.877 0.54 0.07 Problem 5.2w An electricity board charges different rates for different categories of consumption of power. Category 1 is domestic users, category 2 is educational institutions, category 3 is commercial institutions and category 4 is industries. The tariff for energy consumption is Rs.1.00 / unit for category 1, Rs.1.75 / unit for category 2, Rs. 2.50 / unit for category 3 and Rs.3.00 / unit for category 4. Write a program to calculate electricity charges for the following data: Consumer Category Unit Consumed Raman 1 75 Balaji 1 250 Public School 2 800 ABC Hardware 3 550 R.M.K. Industry 4 12450 68 Programming in JAVA2 Program 5.2w /* ------------------------------------------------------This program calculates the electricity charges for different categories of consumers. somasundaramk@yahoo.com ------------------------------------------------------------ */ class Prob52 { public static void main(String args []) { String consumers [] = { "Raman", "Balaji", "Public School", "ABC Hardware", "R.M.K.Industry" }; int units [] = {75,250, 800, 550, 12450 }; int conscat [] = { 1, 1, 2, 3, 4 }; double rate [] = {1.0, 1.75, 2.50, 3.0 }; int noc = consumers.length; int i; double bill = 0; //Calculate the electricity charges for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); System.out.println("\t Consumer \t Category \t Units \t Charges"); for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); for (i = 0; i < noc; i++) { switch (conscat[i]) { case 1: bill = units[i] * 1.0; break; case 2: bill = units[i] * 1.75; break; case 3: bill = units[i] * 2.5; break; Control Statements 69 case 4: bill = units[i] * 3.0; break; default: System.out.println("Category mismatch"); } //reduce the number of decimal places bill = (int)(bill * 100); bill = bill / 100; System.out.println(consumers[i] + "\t\t" + conscat[i] + "\t" + units[i] + "\t" + bill); } for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------------------------------------Consumer Category Units Charges -------------------------------------------------------------------------------Raman 1 75 75.0 Balaji 1 250 250.0 Public School 2 800 1400.0 ABC Hardware 3 550 1375.0 R.M.K.Industry 4 12450 37350.0 -------------------------------------------------------------------------------- Exercise–5 I. Fill in the blanks 5.1. if..else structure helps to make a ________ from the sequential computation of statements in a program. 5.2. To select one out of many options in a computation, _______ if-else can be used. 5.3. switch statement can be used to select one out ______ options. 5.4. The case value in a switch statement must be _________ . 70 Programming in JAVA2 5.5. The _______ statement tests the condition at the end of the block. 5.6. In a for..loop the condition is tested at the ________ of the block. 5.7. In a for.. statement more than one initializer is allowed. (True/False) 5.8. In a for..statement with more than one initializer, there can be more than one condition. (True/False) 5.9. The break statement can be used only in ______ and ______ statements. 5.10. The _______ statement when encountered takes the control to the end of the loop block. II. Write programs for the following: 5.11. A cloth shop during festival season offers a discount 10% for purchases made up to Rs.1,000, 12% for purchase value of Rs.1000 or more up to Rs 1,500 and 15% for purchase made for Rs.1,500 or more. Write a program to implement the above scheme for a given sales and print out the sales value, discount and net amount payable by a customer. 5.12. The roots of a quadratic equation ax 2+bx+c=0 are given by : –b+ Ö b 2–4ac , x1 = 2a x2 = –b– Ö b 2–4ac 2a , with the condition if (b 2 –4ac) < 0, then the obsolute value |(b 2-ac)| is to be taken. Given a, b, c, write a Java program to compute the two roots x 1 and x 2 . 5.13 An electric appliance shop assigns code 1 to motor, 2 to fan, 3 to tube light and 4 for wires. All other items have code 5 or more. While selling the goods, a sales tax of 8% to motor, 12% to fan, 5% to tube light, 7.5% to wires and 3% for all other items is charged. A list containing the product code and price is given for making a bill. Write a Java program using switch statement to prepare the bill. * * * * * * 43 Chapter 5 CONTROL STATEMENTS In this chapter, the statements that take the control from one location to another during execution are given. The control statements help to make branching, looping, skipping and exiting a block of codes. Basically, any computer-oriented problem can be solved using any combination of sequential, branching and looping structure. Therefore, a computer programming language should support these three structures. In this chapter, the statements supporting the branching and looping structures in Java are given. These statements help to branch or loop a segment of statements and are called control statements. 5.1 The if..else Statement This statement helps to select one out of two possibilities based on the given condition. Hence, this statement is also called as conditional if statement. The general form of the statement is: if (conditional expression) statement1; else statement2; The conditional expression should result in a boolean value. If the condition, on evaluation, gives true, statement1 is executed and the control skips statement2, otherwise statement1 is skipped and statement2 is executed. 44 Programming in JAVA2 The statement1 and the statement2 can be a simple or block statement. else part is optional and, if needed, can be left out and can take the form: The if (conditional expression) statement; In this form, the statement will be executed, if the conditional expression gives true, otherwise it is skipped. The flowchart for if...else and if... are given in fig.5.1 and fig.5.2 respectively. true false Condition Statement1 Fig.5.1 Statement2 Flowchart for if...else Statement true Condition Statement false Fig.5.2 Flowchart for if...Statement Control Statements The following statement: examples, 5.1 45 and 5.2, illustrate the if...else and if Example 5.1 int mark; String result; if (mark >= 40) result = “Pass”; else result = “Fail”; Example 5.2 double a, b, c, discr, term; discr = b*b-4.0*a*c; if (discr < 0) discr = -discr; term = Maths.sqrt(discr); root1 = (-b+term)/(2.0*a); root2 = (-b-term)/(2.0*a); Nested if..else Nested if..else statement is made by placing one if..else inside another if..else statement. Nested if..else statement helps to select one out of many choices. The general form of if..else statement is : if (condition1) if (condition2) if (condition3) statement 4 else statement 3 else statement 2 else statement 1 In the nested if..else statement, the outermost if is evaluated first. If the condition1 tested is false, the statement1 in the outmost else is evaluated and if..else ends. If the condition1 results in true, the control goes to execute the next inner if statement. If condition2 is false, statement2 is executed. Otherwise, condition3 is evaluated. If condition3 is false, statement3 is executed, otherwise statement4 is executed. 46 Programming in JAVA2 The flowchart for the nested if..else is given in fig.5.3: false Condition1 Statement1 true false Condition2 Statement2 true false Condition3 Statement3 true Statement4 Fig.5.3 Flowchart for nested if...else Statement The following program 5.1 illustrates the use of nested if..else statement: Program 5.1 //This program illustrates the nested if... else //somasundaramk@yahoo.com class NestedIf { public static void main(String args []) { String result_class; int avg_mark = 62; statement. Control Statements 47 if (avg_mark > 50) if (avg_mark >= 60) if (avg_mark >= 75) result_class = “Distinction”; else result_class = “First Class”; else result_class = “Second Class”; else result_class = “Third Class”; if (avg_mark < 40) System.out.println(“Failed”); else System.out.println(“Passed with “ +result_class); } } The above program gives the following output: Passed with First Class Another form of nested if..else is the ladder if..else statement. structure of the ladder if..else statement is : The if (condition1) statement1; else if (condition2) statement2; else if (condition 3) statement 3; else statement4; The flowchart for the above ladder if...else statement is given in fig. 5.4: 48 Programming in JAVA2 true Condition1 Statement1 false true Condition2 Statement2 false true Condition3 Statement3 false Statement4 Fig.5.4 Flowchart for Ladder if..else Statement The following program 5.2 illustrates the ladder if...else statement: Program 5.2 //This program illustrates the ladder if...else if statement. //somasundaramk@yahoo.com class IfElseIf { public static void main(String args []) { String result_class; int avg_mark = 62; if (avg_mark > 75) result_class = “Distiction”; else if (avg_mark >= 60) result_class = “First Class”; Control Statements 49 else if (avg_mark >= 50) result_class = “Second Class”; else result_class = “Third Class”; if (avg_mark < 40) System.out.println(“Failed”); else System.out.println(“Passed with “ +result_class); } } The above program gives the following output: Passed with First Class 5.2 The switch Statement The switch statement helps to select one out of many choices. This helps to write a clear statement when compared to nested if...else statements. The general form of switch statement is: switch (expression) { case val1 : statement1; break; case val2 : statement2; break; case val3 : statement3; break; . . . case valN : statementN; break; default : statement; } It is expected that the expression, when evaluated, should give discrete values in the range Val1 to valN. If the expression gives val1, the statement1 is executed and the control exits the switch block. If the expression gives val2, statement2 is executed and so on (fig.5.5). If the expression gives any value that is not matching between val1 and valN, the statement given in default is executed. The expression should give any of the type byte, short, int or char. In this way, multiple branching can be effected. The break statement when executed will take the control out of the switch block. Generally, switch statement is used for expressions that may give discrete and predefined values. 50 Programming in JAVA2 Expression = val1 Statement1 = val2 Statement2 = valN StatementN no match Statement Fig.5.5 Flowchart for switch Statement The following program 5.3 illustrates the use of switch statement: Program 5.3 // This program illustrates the switch statement. class SwitchDemo public static void main(String args []) { int month = 5; switch (month) { case 1: System.out.println(“January”); break; case 2: System.out.println(“February”); break; case 3: System.out.println(“March”); break; case 4: System.out.println(“April”); break; case 5: System.out.println(“May”); break; case 6: Control Statements 51 System.out.println(“June”); break; case 7: System.out.println(“July”); break; case 8: System.out.println(“August”); break; case 9: System.out.println(“September”); break; case 10: System.out.println(“October”); break; case 11: System.out.println(“November”); break; case 12: System.out.println(“December”); break; default: System.out.println(“No match”); } } } The above program gives the following output: May Sometimes, for several In such problems, several common to all of them can 5.4 shows how several cases case values, one common process may be required. case values can be clubbed so that statements be executed at one point. The following program can be combined: Program 5.4 // This program illustrates the switch statement. class GroupCase { public static void main(String args []) { int choice = 6; switch (choice) { case 1: case 2: case 3: System.out.println(“Numbers between 1 and 3”); 52 Programming in JAVA2 break; case 4: case 5: case 6: case 7: System.out.println(“Numbers between 4 and 7 “); break; case 8: case 9: case 10: System.out.println(“Numbers between 8 and 10”); break; default: System.out.println(“Numbers outside 1 and 10”); } } } The above program gives the following output: Numbers between 4 and 7 G The type of data handled in switch statement must be of the type byte, short, int or char. The values used must be discrete. 5.3 The while Statement The while statement is used for looping or iterating a block of statements while the given condition is true. The general form of the while statement is: while (condition) { statements; } The condition, when evaluated, must result false. As long as the condition gives true, executed. When the condition becomes false, statement. The flow of control in while statement in the boolean value true or the statement block will be the control leaves the block is given in fig. 5.6. Control Statements 53 true Condition Statements false Fig.5.6 Flowchart for while Statement When the condition tested is false in the first instance itself, the block statement will not be executed at all. The following program 5.5 shows the use of while structure: Program 5.5 // This program illustrates the use of while statement. class WhileDemo { public static void main(String args []) { int n = 10; int sum = 0; while (n > 0) sum += n––; System.out.println(“Sum of numbers from 1 to 10 is= “ + sum); } } The above program gives the following output: Sum of numbers from 1 to 10 is = 55 G In while statement, executing the codes. the condition is checked before 54 Programming in JAVA2 5.4 The do..while Statement This do..while control statement is used for looping a block of statements while the given condition is true. In this structure, the condition is tested at the end of the block. This is in contrast to the while .. statement, where the condition is tested at the start of the block. The general form of do..while statement is: do { statements; } while (condition); The condition tested can be any expression that will yield a boolean value. As long as the condition tested is true, the whole block will be executed. Once the condition tested becomes false, the control leaves the block. It is to be noted that the block is executed once before the condition is tested. Therefore, even if the condition tested is false at the first instance itself, the block statement is executed once. The flowchart of a do..while structure is given in fig.5.7. Statements true Condition false Fig.5.7 Flowchart for do....while Statement The following program 5.6 illustrates the do ... while statement: Control Statements 55 Program 5.6 // This program illustrates the use of do..while statement. class DoWhileDemo { public static void main(String args []) { int n = 10; int sum = 0; do sum += n––; while (n > 0); System.out.println(“Sum of numbers from 1 to 10 is = “ + sum); } } The above program gives the following output: Sum of numbers from 1 to 10 is = 55 G In do...while statement, the condition is checked after executing the codes. 5.5 The for ... Statement This is the third form of looping statement. This statement is a selfcontained one, that is the initial value, termination condition, iterator (increment/ decrement) are all given in the for structure itself. The general form of for statement is: for (initializer; condition; iterator) { statements; } Here, the condition can be any expression that yields boolean value true or false. The initializer is used to store the initial value for a loop variable. The iterator modifies the loop variable. The statements in the block are executed, as long as the condition tested gives true. When the condition becomes false, the control leaves the block statement. The flowchart for the for loop is given in fig. 5.8. 56 Programming in JAVA2 initializer false Condition true Statements iterator Fig.5.8 Flowchart for the for Loop Program 5.7 shows the use of for.. statement. Program 5.7 /* This program illustrates the use of for statement. This program finds the sum of all numbers from 1 up to 10. */ class ForDemo1 { public static void main(String args []) { int n; int sum = 0; for (n = 10; n > 0; n––) sum += n; System.out.println(“Sum of numbers from 1 up to 10 =“ + sum); } } The above program gives the following output: Sum of numbers from 1 up to 10 = 55 Control Statements 57 The above program 5.7 can be written in another form as given in program 5.8. The loop variable n can be declared inside the for structure itself. The iterator is optional. If there is no need for an iterator in a program, it can be left blank. Program 5.8 /* This program illustrates the use of for statement. Notice that n is declared inside the for loop. The iterator is left blank as it has been done in the block statement itself. */ class ForDemo2 { public static void main(String args []) { int sum = 0; for (int n = 10; n > 0; ) sum += n––; System.out.println(“Sum of numbers from 1 up to 10 = “ + sum); } } The for loop in program 5.8 can be improved further and written in a compact form as : for (int n=10; n>0; sum+=n––); G In a for structure, one, two or all the three components, initializer, condition, iterator, can be absent. The statement for ( ; ; ) is valid and will make an infinite loop. The following program 5.9 finds the factorial of numbers from 1 to 10. Program 5.9 // This program finds the factorial of a number using for // statement. class FactProg { public static void main(String args []) { int n = 10; long fact = 1; 58 Programming in JAVA2 for (int i = 1; i <= n; ++i) { fact *= i; System.out.println(“Factorial of “ + i + “ = “ + fact); } } } The above program gives the following output: Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of 1=1 2=2 3=6 4 = 24 5 = 120 6 = 720 7 = 5040 8 = 40320 9 = 362880 10 = 3628800 The for loops can be nested one within another as shown below: - - - - - - - - - - - - - - - - - - for (i=1; i<n; i++) // outer loop begins { - - - - - - - - - - - - - - for (k=1; k<m; k++) // inner loop begins { . . . } // inner loop ends . . . } // outer loops ends . . . The following program 5.10 illustrates the nested for loop. multiplication tables for 2, 3 and 4. It generates Control Statements 59 Program 5.10 // This program illustrates the nested for loop. class MulTable { public static void main(String args []) { int i, j, m = 4, n = 5; int prod; for (i = 2; i <= m; ++i) { System.out.println(“Multiplication Table for“ + i); for (j = 1; j <= n; ++j) { prod = j * i; System.out.println(j + “X” + i + “ = “ + prod); } System.out.println(“ “);//create one line space } } } The above program gives the following output: Multiplication Table for 2 1X2 = 2 2X2 = 4 3X2 = 6 4X2 = 8 5X2 = 10 Multiplication Table for 3 1X3 = 3 2X3 = 6 3X3 = 9 4X3 = 12 5X3 = 15 Multiplication Table for 4 1X4 = 4 2X4 = 8 3X4 = 12 4X4 = 16 5X4 = 20 5.6 The break Statement The break statement is to be used only in loops and switch statement. When this statement is executed, the control is taken out of the loop. The loop becomes dead. The flowchart for the break statement is given in fig. 5.9. 60 Programming in JAVA2 . ¯ . ¯ if(condition) break; . ¯ > start of loop ¬ - normal end of loop > Fig.5.9 The Flowchart for break Statement The following program 5.11 illustrates the use of break in a for loop: Program 5.11 // This program illustrates the use of break statement. class BreakDemo { public static void main(String args []) { int n = 5, m = 20; for (int i = 1; i <= m; i++) { if (n * i > 30) { System.out.println(“Exiting the loop”); break; } System.out.println(i + “X” + n + “ = “ + n * i); } } } The above program gives the following output: 1X5 = 5 2X5 = 10 3X5 = 15 4X5 = 20 5X5 = 25 6X5 = 30 Exiting the loop Blocks can be labeled and the break control can be made to exit any labeled block. This is called labeled break. The label for a block can be Control Statements 61 formed by using the rules to form a variable. The labeled break is useful when using nested loops. The following program 5.12 illustrates the labeled break statement: Program 5.12 // This program illustrates the use of labeled break. class LabelBreak { public static void main(String args []) { int n = 0, m = 0; loop1: while (true) { n++; m = 0; System.out.println(“\n loop1 “ + “n = “ + n); loop2: while (++m <= n) { if (n * m > 10) { System.out.println(“Exiting loop2 and loop1”); break loop1; } System.out.println(“loop2 “ + m + “X” + n + “ = “ + n * m); } } System.out.println(“outside loop1”); } } The above program gives the following output: loop1 n = 1 loop2 1X1 = 1 loop1 n = 2 loop2 1X2 = 2 loop2 2X2 = 4 loop1 n = 3 loop2 1X3 = 3 loop2 2X3 = 6 loop2 3X3 = 9 62 Programming in JAVA2 loop1 n = 4 loop2 1X4 = 4 loop2 2X4 = 8 Exiting loop2 and loop1 outside loop1 5.7 The continue Statement The continue statement is used inside the loop control blocks. When the continue statement is executed, the control skips the remaining portion of the loop and goes to the beginning of the loop and continue. The flowchart for the continue statement is given in fig. 5.10: start of loop ¬ - .. ¯ if(condition) continue; ® . ¯ > normal - end of loop Fig.5.10 Flowchart for continue Statement The following program 5.13 illustrates the use of continue statement: Program 5.13 // This program illustrates the use of continue statement. class ContinueProg { public static void main(String args []) { int i = 0; while (++i < 10) { if (i % 2 == 0) continue; System.out.println(i); } } } Control Statements 63 The above program gives the following outptut: 1 3 5 7 9 Like labeled break, labeled continue structure is also available. following program 5.14 illustrates the use of labeled continue: The Program 5.14 // This program illustrates the use of labeled continue // statement. // This program generates prime numbers between 1 and 15. // somasundaramk@yahoo.com class LabelContinue { public static void main(String args []) { int i = 1, n, max = 15; System.out.println(“Prime numbers between 1 and 15”); System.out.println(i); start: for (n = 2; n <= max; ++n) { test: for (i = 2; i < n; ++i) if (n % i == 0) continue start; System.out.println(n); } } } The above program gives the following output: Prime numbers between 1 and 15 1 2 3 5 7 11 13 64 Programming in JAVA2 5.8 The comma Statement Java allows multiple initialization and iteration in the for statement. With this capability, more than one variable can be initialized and more than one iteration can be done. Each of such statements are to be separated by a comma(,). But there can be only one conditional expression. The general form of the multiple initialization and iteration is: for (init1, init2, init3; condition; itr1, itr2, itr3) { Statements; } The following program 5.15 illustrates the use of comma statement. Program 5.15 // This program illustrates the use of comma statement. class CommaDemo { public static void main(String args []) { int n, i, sum; for (i = 1, n = 5; n > 0; i++, n—, sum = 0) { sum = i + n; System.out.println(i + “ + “ + n + “ = “ + sum); } } } The output for the above program is : 1+5=6 2+4=6 3+3=6 4+2=6 5+1=6 After reading this chapter, you should have learned the following: Ü Branching using if...else control Ü Branching using switch control Ü Looping with while, do...while and for...control Ü Using break and continue In the next chapter, you will learn about arrays. Control Statements 65 Worked Out Problems–5 Problem 5.1w The trigonometric functions Sin(x) and Cos(x) are computed using the following formula: Sin(x) = Cos(x) = x3 x – 3! x2 1 – 2! + + x5 5! x4 4! – – x7 7! x6 6! + + x9 9! x8 8! – x 11 11! – x 10 10! Calculate the Sin(x) and Cos(x) values for x=0, 0.5 and 1.5. The following expressions which represent the above are made use of: Sin(x) = m S x + n=1 m Cos(x) = 1 + S n=1 (–1) n x 2n+1 (2n+1)! (–1) n x 2n 2n! Program 5.1w /* ------------------------------------------------------------This program calculates the sin(x) and cos(x) functions. The values obtained are compared with those of Java functions. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Prob51 { public static void main(String args []) { double x, sinx, cosx; int n, fact = 1, factn, factnplus; int m = 5; for (int i = 0; i < 80; i++) 66 Programming in JAVA2 System.out.print("-"); System.out.println("\n"); System.out.println("x \t my sinx \t Java sinx \t my cosx \t Java cosx\n"); for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); for (x = 0; x < 1.6; ) { sinx = x; cosx = 1; for (n = 1; n <= m; n++) { factn = 1; factnplus = 1; for (int i = 2; i <= 2 * n; i++) factn = factn * i; for (int i = 2; i <= (2 * n + 1); i++) factnplus = factnplus * i; sinx = sinx + Math.pow(-1, n) * Math.pow(x, (2 * n + 1)) / factnplus; cosx = cosx + Math.pow(-1, n) * Math.pow(x, 2 * n) / factn; } // Reduce the fractional digits for display double sx = (int)(sinx * 1000); double cx = (int)(cosx * 1000); sinx = sx / 1000; cosx = cx / 1000; double jsx = (int)(Math.sin(x) * 1000); double jcx = (int)(Math.cos(x) * 1000); jsx = jsx / 1000; jcx = jcx / 1000; Control Statements 67 System.out.println(x + "\t" + sinx + "\t\t" + jsx +"\t\t" + cosx + "\t\t" + jcx); x = x + 0.5; } for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------------------------------------x my sinx Java sinx my cosx Java cosx -------------------------------------------------------------------------------0.0 0.0 0.0 1.0 0.5 0.479 0.479 0.877 1.0 0.841 0.841 0.54 1.5 0.997 0.997 0.07 -------------------------------------------------------------------------------- 1.0 0.877 0.54 0.07 Problem 5.2w An electricity board charges different rates for different categories of consumption of power. Category 1 is domestic users, category 2 is educational institutions, category 3 is commercial institutions and category 4 is industries. The tariff for energy consumption is Rs.1.00 / unit for category 1, Rs.1.75 / unit for category 2, Rs. 2.50 / unit for category 3 and Rs.3.00 / unit for category 4. Write a program to calculate electricity charges for the following data: Consumer Category Unit Consumed Raman 1 75 Balaji 1 250 Public School 2 800 ABC Hardware 3 550 R.M.K. Industry 4 12450 68 Programming in JAVA2 Program 5.2w /* ------------------------------------------------------This program calculates the electricity charges for different categories of consumers. somasundaramk@yahoo.com ------------------------------------------------------------ */ class Prob52 { public static void main(String args []) { String consumers [] = { "Raman", "Balaji", "Public School", "ABC Hardware", "R.M.K.Industry" }; int units [] = {75,250, 800, 550, 12450 }; int conscat [] = { 1, 1, 2, 3, 4 }; double rate [] = {1.0, 1.75, 2.50, 3.0 }; int noc = consumers.length; int i; double bill = 0; //Calculate the electricity charges for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); System.out.println("\t Consumer \t Category \t Units \t Charges"); for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); for (i = 0; i < noc; i++) { switch (conscat[i]) { case 1: bill = units[i] * 1.0; break; case 2: bill = units[i] * 1.75; break; case 3: bill = units[i] * 2.5; break; Control Statements 69 case 4: bill = units[i] * 3.0; break; default: System.out.println("Category mismatch"); } //reduce the number of decimal places bill = (int)(bill * 100); bill = bill / 100; System.out.println(consumers[i] + "\t\t" + conscat[i] + "\t" + units[i] + "\t" + bill); } for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------------------------------------Consumer Category Units Charges -------------------------------------------------------------------------------Raman 1 75 75.0 Balaji 1 250 250.0 Public School 2 800 1400.0 ABC Hardware 3 550 1375.0 R.M.K.Industry 4 12450 37350.0 -------------------------------------------------------------------------------- Exercise–5 I. Fill in the blanks 5.1. if..else structure helps to make a ________ from the sequential computation of statements in a program. 5.2. To select one out of many options in a computation, _______ if-else can be used. 5.3. switch statement can be used to select one out ______ options. 5.4. The case value in a switch statement must be _________ . 70 Programming in JAVA2 5.5. The _______ statement tests the condition at the end of the block. 5.6. In a for..loop the condition is tested at the ________ of the block. 5.7. In a for.. statement more than one initializer is allowed. (True/False) 5.8. In a for..statement with more than one initializer, there can be more than one condition. (True/False) 5.9. The break statement can be used only in ______ and ______ statements. 5.10. The _______ statement when encountered takes the control to the end of the loop block. II. Write programs for the following: 5.11. A cloth shop during festival season offers a discount 10% for purchases made up to Rs.1,000, 12% for purchase value of Rs.1000 or more up to Rs 1,500 and 15% for purchase made for Rs.1,500 or more. Write a program to implement the above scheme for a given sales and print out the sales value, discount and net amount payable by a customer. 5.12. The roots of a quadratic equation ax 2+bx+c=0 are given by : –b+ Ö b 2–4ac , x1 = 2a x2 = –b– Ö b 2–4ac 2a , with the condition if (b 2 –4ac) < 0, then the obsolute value |(b 2-ac)| is to be taken. Given a, b, c, write a Java program to compute the two roots x 1 and x 2 . 5.13 An electric appliance shop assigns code 1 to motor, 2 to fan, 3 to tube light and 4 for wires. All other items have code 5 or more. While selling the goods, a sales tax of 8% to motor, 12% to fan, 5% to tube light, 7.5% to wires and 3% for all other items is charged. A list containing the product code and price is given for making a bill. Write a Java program using switch statement to prepare the bill. * * * * * * 43 Chapter 5 CONTROL STATEMENTS In this chapter, the statements that take the control from one location to another during execution are given. The control statements help to make branching, looping, skipping and exiting a block of codes. Basically, any computer-oriented problem can be solved using any combination of sequential, branching and looping structure. Therefore, a computer programming language should support these three structures. In this chapter, the statements supporting the branching and looping structures in Java are given. These statements help to branch or loop a segment of statements and are called control statements. 5.1 The if..else Statement This statement helps to select one out of two possibilities based on the given condition. Hence, this statement is also called as conditional if statement. The general form of the statement is: if (conditional expression) statement1; else statement2; The conditional expression should result in a boolean value. If the condition, on evaluation, gives true, statement1 is executed and the control skips statement2, otherwise statement1 is skipped and statement2 is executed. 44 Programming in JAVA2 The statement1 and the statement2 can be a simple or block statement. else part is optional and, if needed, can be left out and can take the form: The if (conditional expression) statement; In this form, the statement will be executed, if the conditional expression gives true, otherwise it is skipped. The flowchart for if...else and if... are given in fig.5.1 and fig.5.2 respectively. true false Condition Statement1 Fig.5.1 Statement2 Flowchart for if...else Statement true Condition Statement false Fig.5.2 Flowchart for if...Statement Control Statements The following statement: examples, 5.1 45 and 5.2, illustrate the if...else and if Example 5.1 int mark; String result; if (mark >= 40) result = “Pass”; else result = “Fail”; Example 5.2 double a, b, c, discr, term; discr = b*b-4.0*a*c; if (discr < 0) discr = -discr; term = Maths.sqrt(discr); root1 = (-b+term)/(2.0*a); root2 = (-b-term)/(2.0*a); Nested if..else Nested if..else statement is made by placing one if..else inside another if..else statement. Nested if..else statement helps to select one out of many choices. The general form of if..else statement is : if (condition1) if (condition2) if (condition3) statement 4 else statement 3 else statement 2 else statement 1 In the nested if..else statement, the outermost if is evaluated first. If the condition1 tested is false, the statement1 in the outmost else is evaluated and if..else ends. If the condition1 results in true, the control goes to execute the next inner if statement. If condition2 is false, statement2 is executed. Otherwise, condition3 is evaluated. If condition3 is false, statement3 is executed, otherwise statement4 is executed. 46 Programming in JAVA2 The flowchart for the nested if..else is given in fig.5.3: false Condition1 Statement1 true false Condition2 Statement2 true false Condition3 Statement3 true Statement4 Fig.5.3 Flowchart for nested if...else Statement The following program 5.1 illustrates the use of nested if..else statement: Program 5.1 //This program illustrates the nested if... else //somasundaramk@yahoo.com class NestedIf { public static void main(String args []) { String result_class; int avg_mark = 62; statement. Control Statements 47 if (avg_mark > 50) if (avg_mark >= 60) if (avg_mark >= 75) result_class = “Distinction”; else result_class = “First Class”; else result_class = “Second Class”; else result_class = “Third Class”; if (avg_mark < 40) System.out.println(“Failed”); else System.out.println(“Passed with “ +result_class); } } The above program gives the following output: Passed with First Class Another form of nested if..else is the ladder if..else statement. structure of the ladder if..else statement is : The if (condition1) statement1; else if (condition2) statement2; else if (condition 3) statement 3; else statement4; The flowchart for the above ladder if...else statement is given in fig. 5.4: 48 Programming in JAVA2 true Condition1 Statement1 false true Condition2 Statement2 false true Condition3 Statement3 false Statement4 Fig.5.4 Flowchart for Ladder if..else Statement The following program 5.2 illustrates the ladder if...else statement: Program 5.2 //This program illustrates the ladder if...else if statement. //somasundaramk@yahoo.com class IfElseIf { public static void main(String args []) { String result_class; int avg_mark = 62; if (avg_mark > 75) result_class = “Distiction”; else if (avg_mark >= 60) result_class = “First Class”; Control Statements 49 else if (avg_mark >= 50) result_class = “Second Class”; else result_class = “Third Class”; if (avg_mark < 40) System.out.println(“Failed”); else System.out.println(“Passed with “ +result_class); } } The above program gives the following output: Passed with First Class 5.2 The switch Statement The switch statement helps to select one out of many choices. This helps to write a clear statement when compared to nested if...else statements. The general form of switch statement is: switch (expression) { case val1 : statement1; break; case val2 : statement2; break; case val3 : statement3; break; . . . case valN : statementN; break; default : statement; } It is expected that the expression, when evaluated, should give discrete values in the range Val1 to valN. If the expression gives val1, the statement1 is executed and the control exits the switch block. If the expression gives val2, statement2 is executed and so on (fig.5.5). If the expression gives any value that is not matching between val1 and valN, the statement given in default is executed. The expression should give any of the type byte, short, int or char. In this way, multiple branching can be effected. The break statement when executed will take the control out of the switch block. Generally, switch statement is used for expressions that may give discrete and predefined values. 50 Programming in JAVA2 Expression = val1 Statement1 = val2 Statement2 = valN StatementN no match Statement Fig.5.5 Flowchart for switch Statement The following program 5.3 illustrates the use of switch statement: Program 5.3 // This program illustrates the switch statement. class SwitchDemo public static void main(String args []) { int month = 5; switch (month) { case 1: System.out.println(“January”); break; case 2: System.out.println(“February”); break; case 3: System.out.println(“March”); break; case 4: System.out.println(“April”); break; case 5: System.out.println(“May”); break; case 6: Control Statements 51 System.out.println(“June”); break; case 7: System.out.println(“July”); break; case 8: System.out.println(“August”); break; case 9: System.out.println(“September”); break; case 10: System.out.println(“October”); break; case 11: System.out.println(“November”); break; case 12: System.out.println(“December”); break; default: System.out.println(“No match”); } } } The above program gives the following output: May Sometimes, for several In such problems, several common to all of them can 5.4 shows how several cases case values, one common process may be required. case values can be clubbed so that statements be executed at one point. The following program can be combined: Program 5.4 // This program illustrates the switch statement. class GroupCase { public static void main(String args []) { int choice = 6; switch (choice) { case 1: case 2: case 3: System.out.println(“Numbers between 1 and 3”); 52 Programming in JAVA2 break; case 4: case 5: case 6: case 7: System.out.println(“Numbers between 4 and 7 “); break; case 8: case 9: case 10: System.out.println(“Numbers between 8 and 10”); break; default: System.out.println(“Numbers outside 1 and 10”); } } } The above program gives the following output: Numbers between 4 and 7 G The type of data handled in switch statement must be of the type byte, short, int or char. The values used must be discrete. 5.3 The while Statement The while statement is used for looping or iterating a block of statements while the given condition is true. The general form of the while statement is: while (condition) { statements; } The condition, when evaluated, must result false. As long as the condition gives true, executed. When the condition becomes false, statement. The flow of control in while statement in the boolean value true or the statement block will be the control leaves the block is given in fig. 5.6. Control Statements 53 true Condition Statements false Fig.5.6 Flowchart for while Statement When the condition tested is false in the first instance itself, the block statement will not be executed at all. The following program 5.5 shows the use of while structure: Program 5.5 // This program illustrates the use of while statement. class WhileDemo { public static void main(String args []) { int n = 10; int sum = 0; while (n > 0) sum += n––; System.out.println(“Sum of numbers from 1 to 10 is= “ + sum); } } The above program gives the following output: Sum of numbers from 1 to 10 is = 55 G In while statement, executing the codes. the condition is checked before 54 Programming in JAVA2 5.4 The do..while Statement This do..while control statement is used for looping a block of statements while the given condition is true. In this structure, the condition is tested at the end of the block. This is in contrast to the while .. statement, where the condition is tested at the start of the block. The general form of do..while statement is: do { statements; } while (condition); The condition tested can be any expression that will yield a boolean value. As long as the condition tested is true, the whole block will be executed. Once the condition tested becomes false, the control leaves the block. It is to be noted that the block is executed once before the condition is tested. Therefore, even if the condition tested is false at the first instance itself, the block statement is executed once. The flowchart of a do..while structure is given in fig.5.7. Statements true Condition false Fig.5.7 Flowchart for do....while Statement The following program 5.6 illustrates the do ... while statement: Control Statements 55 Program 5.6 // This program illustrates the use of do..while statement. class DoWhileDemo { public static void main(String args []) { int n = 10; int sum = 0; do sum += n––; while (n > 0); System.out.println(“Sum of numbers from 1 to 10 is = “ + sum); } } The above program gives the following output: Sum of numbers from 1 to 10 is = 55 G In do...while statement, the condition is checked after executing the codes. 5.5 The for ... Statement This is the third form of looping statement. This statement is a selfcontained one, that is the initial value, termination condition, iterator (increment/ decrement) are all given in the for structure itself. The general form of for statement is: for (initializer; condition; iterator) { statements; } Here, the condition can be any expression that yields boolean value true or false. The initializer is used to store the initial value for a loop variable. The iterator modifies the loop variable. The statements in the block are executed, as long as the condition tested gives true. When the condition becomes false, the control leaves the block statement. The flowchart for the for loop is given in fig. 5.8. 56 Programming in JAVA2 initializer false Condition true Statements iterator Fig.5.8 Flowchart for the for Loop Program 5.7 shows the use of for.. statement. Program 5.7 /* This program illustrates the use of for statement. This program finds the sum of all numbers from 1 up to 10. */ class ForDemo1 { public static void main(String args []) { int n; int sum = 0; for (n = 10; n > 0; n––) sum += n; System.out.println(“Sum of numbers from 1 up to 10 =“ + sum); } } The above program gives the following output: Sum of numbers from 1 up to 10 = 55 Control Statements 57 The above program 5.7 can be written in another form as given in program 5.8. The loop variable n can be declared inside the for structure itself. The iterator is optional. If there is no need for an iterator in a program, it can be left blank. Program 5.8 /* This program illustrates the use of for statement. Notice that n is declared inside the for loop. The iterator is left blank as it has been done in the block statement itself. */ class ForDemo2 { public static void main(String args []) { int sum = 0; for (int n = 10; n > 0; ) sum += n––; System.out.println(“Sum of numbers from 1 up to 10 = “ + sum); } } The for loop in program 5.8 can be improved further and written in a compact form as : for (int n=10; n>0; sum+=n––); G In a for structure, one, two or all the three components, initializer, condition, iterator, can be absent. The statement for ( ; ; ) is valid and will make an infinite loop. The following program 5.9 finds the factorial of numbers from 1 to 10. Program 5.9 // This program finds the factorial of a number using for // statement. class FactProg { public static void main(String args []) { int n = 10; long fact = 1; 58 Programming in JAVA2 for (int i = 1; i <= n; ++i) { fact *= i; System.out.println(“Factorial of “ + i + “ = “ + fact); } } } The above program gives the following output: Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of 1=1 2=2 3=6 4 = 24 5 = 120 6 = 720 7 = 5040 8 = 40320 9 = 362880 10 = 3628800 The for loops can be nested one within another as shown below: - - - - - - - - - - - - - - - - - - for (i=1; i<n; i++) // outer loop begins { - - - - - - - - - - - - - - for (k=1; k<m; k++) // inner loop begins { . . . } // inner loop ends . . . } // outer loops ends . . . The following program 5.10 illustrates the nested for loop. multiplication tables for 2, 3 and 4. It generates Control Statements 59 Program 5.10 // This program illustrates the nested for loop. class MulTable { public static void main(String args []) { int i, j, m = 4, n = 5; int prod; for (i = 2; i <= m; ++i) { System.out.println(“Multiplication Table for“ + i); for (j = 1; j <= n; ++j) { prod = j * i; System.out.println(j + “X” + i + “ = “ + prod); } System.out.println(“ “);//create one line space } } } The above program gives the following output: Multiplication Table for 2 1X2 = 2 2X2 = 4 3X2 = 6 4X2 = 8 5X2 = 10 Multiplication Table for 3 1X3 = 3 2X3 = 6 3X3 = 9 4X3 = 12 5X3 = 15 Multiplication Table for 4 1X4 = 4 2X4 = 8 3X4 = 12 4X4 = 16 5X4 = 20 5.6 The break Statement The break statement is to be used only in loops and switch statement. When this statement is executed, the control is taken out of the loop. The loop becomes dead. The flowchart for the break statement is given in fig. 5.9. 60 Programming in JAVA2 . ¯ . ¯ if(condition) break; . ¯ > start of loop ¬ - normal end of loop > Fig.5.9 The Flowchart for break Statement The following program 5.11 illustrates the use of break in a for loop: Program 5.11 // This program illustrates the use of break statement. class BreakDemo { public static void main(String args []) { int n = 5, m = 20; for (int i = 1; i <= m; i++) { if (n * i > 30) { System.out.println(“Exiting the loop”); break; } System.out.println(i + “X” + n + “ = “ + n * i); } } } The above program gives the following output: 1X5 = 5 2X5 = 10 3X5 = 15 4X5 = 20 5X5 = 25 6X5 = 30 Exiting the loop Blocks can be labeled and the break control can be made to exit any labeled block. This is called labeled break. The label for a block can be Control Statements 61 formed by using the rules to form a variable. The labeled break is useful when using nested loops. The following program 5.12 illustrates the labeled break statement: Program 5.12 // This program illustrates the use of labeled break. class LabelBreak { public static void main(String args []) { int n = 0, m = 0; loop1: while (true) { n++; m = 0; System.out.println(“\n loop1 “ + “n = “ + n); loop2: while (++m <= n) { if (n * m > 10) { System.out.println(“Exiting loop2 and loop1”); break loop1; } System.out.println(“loop2 “ + m + “X” + n + “ = “ + n * m); } } System.out.println(“outside loop1”); } } The above program gives the following output: loop1 n = 1 loop2 1X1 = 1 loop1 n = 2 loop2 1X2 = 2 loop2 2X2 = 4 loop1 n = 3 loop2 1X3 = 3 loop2 2X3 = 6 loop2 3X3 = 9 62 Programming in JAVA2 loop1 n = 4 loop2 1X4 = 4 loop2 2X4 = 8 Exiting loop2 and loop1 outside loop1 5.7 The continue Statement The continue statement is used inside the loop control blocks. When the continue statement is executed, the control skips the remaining portion of the loop and goes to the beginning of the loop and continue. The flowchart for the continue statement is given in fig. 5.10: start of loop ¬ - .. ¯ if(condition) continue; ® . ¯ > normal - end of loop Fig.5.10 Flowchart for continue Statement The following program 5.13 illustrates the use of continue statement: Program 5.13 // This program illustrates the use of continue statement. class ContinueProg { public static void main(String args []) { int i = 0; while (++i < 10) { if (i % 2 == 0) continue; System.out.println(i); } } } Control Statements 63 The above program gives the following outptut: 1 3 5 7 9 Like labeled break, labeled continue structure is also available. following program 5.14 illustrates the use of labeled continue: The Program 5.14 // This program illustrates the use of labeled continue // statement. // This program generates prime numbers between 1 and 15. // somasundaramk@yahoo.com class LabelContinue { public static void main(String args []) { int i = 1, n, max = 15; System.out.println(“Prime numbers between 1 and 15”); System.out.println(i); start: for (n = 2; n <= max; ++n) { test: for (i = 2; i < n; ++i) if (n % i == 0) continue start; System.out.println(n); } } } The above program gives the following output: Prime numbers between 1 and 15 1 2 3 5 7 11 13 64 Programming in JAVA2 5.8 The comma Statement Java allows multiple initialization and iteration in the for statement. With this capability, more than one variable can be initialized and more than one iteration can be done. Each of such statements are to be separated by a comma(,). But there can be only one conditional expression. The general form of the multiple initialization and iteration is: for (init1, init2, init3; condition; itr1, itr2, itr3) { Statements; } The following program 5.15 illustrates the use of comma statement. Program 5.15 // This program illustrates the use of comma statement. class CommaDemo { public static void main(String args []) { int n, i, sum; for (i = 1, n = 5; n > 0; i++, n—, sum = 0) { sum = i + n; System.out.println(i + “ + “ + n + “ = “ + sum); } } } The output for the above program is : 1+5=6 2+4=6 3+3=6 4+2=6 5+1=6 After reading this chapter, you should have learned the following: Ü Branching using if...else control Ü Branching using switch control Ü Looping with while, do...while and for...control Ü Using break and continue In the next chapter, you will learn about arrays. Control Statements 65 Worked Out Problems–5 Problem 5.1w The trigonometric functions Sin(x) and Cos(x) are computed using the following formula: Sin(x) = Cos(x) = x3 x – 3! x2 1 – 2! + + x5 5! x4 4! – – x7 7! x6 6! + + x9 9! x8 8! – x 11 11! – x 10 10! Calculate the Sin(x) and Cos(x) values for x=0, 0.5 and 1.5. The following expressions which represent the above are made use of: Sin(x) = m S x + n=1 m Cos(x) = 1 + S n=1 (–1) n x 2n+1 (2n+1)! (–1) n x 2n 2n! Program 5.1w /* ------------------------------------------------------------This program calculates the sin(x) and cos(x) functions. The values obtained are compared with those of Java functions. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Prob51 { public static void main(String args []) { double x, sinx, cosx; int n, fact = 1, factn, factnplus; int m = 5; for (int i = 0; i < 80; i++) 66 Programming in JAVA2 System.out.print("-"); System.out.println("\n"); System.out.println("x \t my sinx \t Java sinx \t my cosx \t Java cosx\n"); for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); for (x = 0; x < 1.6; ) { sinx = x; cosx = 1; for (n = 1; n <= m; n++) { factn = 1; factnplus = 1; for (int i = 2; i <= 2 * n; i++) factn = factn * i; for (int i = 2; i <= (2 * n + 1); i++) factnplus = factnplus * i; sinx = sinx + Math.pow(-1, n) * Math.pow(x, (2 * n + 1)) / factnplus; cosx = cosx + Math.pow(-1, n) * Math.pow(x, 2 * n) / factn; } // Reduce the fractional digits for display double sx = (int)(sinx * 1000); double cx = (int)(cosx * 1000); sinx = sx / 1000; cosx = cx / 1000; double jsx = (int)(Math.sin(x) * 1000); double jcx = (int)(Math.cos(x) * 1000); jsx = jsx / 1000; jcx = jcx / 1000; Control Statements 67 System.out.println(x + "\t" + sinx + "\t\t" + jsx +"\t\t" + cosx + "\t\t" + jcx); x = x + 0.5; } for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------------------------------------x my sinx Java sinx my cosx Java cosx -------------------------------------------------------------------------------0.0 0.0 0.0 1.0 0.5 0.479 0.479 0.877 1.0 0.841 0.841 0.54 1.5 0.997 0.997 0.07 -------------------------------------------------------------------------------- 1.0 0.877 0.54 0.07 Problem 5.2w An electricity board charges different rates for different categories of consumption of power. Category 1 is domestic users, category 2 is educational institutions, category 3 is commercial institutions and category 4 is industries. The tariff for energy consumption is Rs.1.00 / unit for category 1, Rs.1.75 / unit for category 2, Rs. 2.50 / unit for category 3 and Rs.3.00 / unit for category 4. Write a program to calculate electricity charges for the following data: Consumer Category Unit Consumed Raman 1 75 Balaji 1 250 Public School 2 800 ABC Hardware 3 550 R.M.K. Industry 4 12450 68 Programming in JAVA2 Program 5.2w /* ------------------------------------------------------This program calculates the electricity charges for different categories of consumers. somasundaramk@yahoo.com ------------------------------------------------------------ */ class Prob52 { public static void main(String args []) { String consumers [] = { "Raman", "Balaji", "Public School", "ABC Hardware", "R.M.K.Industry" }; int units [] = {75,250, 800, 550, 12450 }; int conscat [] = { 1, 1, 2, 3, 4 }; double rate [] = {1.0, 1.75, 2.50, 3.0 }; int noc = consumers.length; int i; double bill = 0; //Calculate the electricity charges for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); System.out.println("\t Consumer \t Category \t Units \t Charges"); for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); for (i = 0; i < noc; i++) { switch (conscat[i]) { case 1: bill = units[i] * 1.0; break; case 2: bill = units[i] * 1.75; break; case 3: bill = units[i] * 2.5; break; Control Statements 69 case 4: bill = units[i] * 3.0; break; default: System.out.println("Category mismatch"); } //reduce the number of decimal places bill = (int)(bill * 100); bill = bill / 100; System.out.println(consumers[i] + "\t\t" + conscat[i] + "\t" + units[i] + "\t" + bill); } for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------------------------------------Consumer Category Units Charges -------------------------------------------------------------------------------Raman 1 75 75.0 Balaji 1 250 250.0 Public School 2 800 1400.0 ABC Hardware 3 550 1375.0 R.M.K.Industry 4 12450 37350.0 -------------------------------------------------------------------------------- Exercise–5 I. Fill in the blanks 5.1. if..else structure helps to make a ________ from the sequential computation of statements in a program. 5.2. To select one out of many options in a computation, _______ if-else can be used. 5.3. switch statement can be used to select one out ______ options. 5.4. The case value in a switch statement must be _________ . 70 Programming in JAVA2 5.5. The _______ statement tests the condition at the end of the block. 5.6. In a for..loop the condition is tested at the ________ of the block. 5.7. In a for.. statement more than one initializer is allowed. (True/False) 5.8. In a for..statement with more than one initializer, there can be more than one condition. (True/False) 5.9. The break statement can be used only in ______ and ______ statements. 5.10. The _______ statement when encountered takes the control to the end of the loop block. II. Write programs for the following: 5.11. A cloth shop during festival season offers a discount 10% for purchases made up to Rs.1,000, 12% for purchase value of Rs.1000 or more up to Rs 1,500 and 15% for purchase made for Rs.1,500 or more. Write a program to implement the above scheme for a given sales and print out the sales value, discount and net amount payable by a customer. 5.12. The roots of a quadratic equation ax 2+bx+c=0 are given by : –b+ Ö b 2–4ac , x1 = 2a x2 = –b– Ö b 2–4ac 2a , with the condition if (b 2 –4ac) < 0, then the obsolute value |(b 2-ac)| is to be taken. Given a, b, c, write a Java program to compute the two roots x 1 and x 2 . 5.13 An electric appliance shop assigns code 1 to motor, 2 to fan, 3 to tube light and 4 for wires. All other items have code 5 or more. While selling the goods, a sales tax of 8% to motor, 12% to fan, 5% to tube light, 7.5% to wires and 3% for all other items is charged. A list containing the product code and price is given for making a bill. Write a Java program using switch statement to prepare the bill. * * * * * * 43 Chapter 5 CONTROL STATEMENTS In this chapter, the statements that take the control from one location to another during execution are given. The control statements help to make branching, looping, skipping and exiting a block of codes. Basically, any computer-oriented problem can be solved using any combination of sequential, branching and looping structure. Therefore, a computer programming language should support these three structures. In this chapter, the statements supporting the branching and looping structures in Java are given. These statements help to branch or loop a segment of statements and are called control statements. 5.1 The if..else Statement This statement helps to select one out of two possibilities based on the given condition. Hence, this statement is also called as conditional if statement. The general form of the statement is: if (conditional expression) statement1; else statement2; The conditional expression should result in a boolean value. If the condition, on evaluation, gives true, statement1 is executed and the control skips statement2, otherwise statement1 is skipped and statement2 is executed. 44 Programming in JAVA2 The statement1 and the statement2 can be a simple or block statement. else part is optional and, if needed, can be left out and can take the form: The if (conditional expression) statement; In this form, the statement will be executed, if the conditional expression gives true, otherwise it is skipped. The flowchart for if...else and if... are given in fig.5.1 and fig.5.2 respectively. true false Condition Statement1 Fig.5.1 Statement2 Flowchart for if...else Statement true Condition Statement false Fig.5.2 Flowchart for if...Statement Control Statements The following statement: examples, 5.1 45 and 5.2, illustrate the if...else and if Example 5.1 int mark; String result; if (mark >= 40) result = “Pass”; else result = “Fail”; Example 5.2 double a, b, c, discr, term; discr = b*b-4.0*a*c; if (discr < 0) discr = -discr; term = Maths.sqrt(discr); root1 = (-b+term)/(2.0*a); root2 = (-b-term)/(2.0*a); Nested if..else Nested if..else statement is made by placing one if..else inside another if..else statement. Nested if..else statement helps to select one out of many choices. The general form of if..else statement is : if (condition1) if (condition2) if (condition3) statement 4 else statement 3 else statement 2 else statement 1 In the nested if..else statement, the outermost if is evaluated first. If the condition1 tested is false, the statement1 in the outmost else is evaluated and if..else ends. If the condition1 results in true, the control goes to execute the next inner if statement. If condition2 is false, statement2 is executed. Otherwise, condition3 is evaluated. If condition3 is false, statement3 is executed, otherwise statement4 is executed. 46 Programming in JAVA2 The flowchart for the nested if..else is given in fig.5.3: false Condition1 Statement1 true false Condition2 Statement2 true false Condition3 Statement3 true Statement4 Fig.5.3 Flowchart for nested if...else Statement The following program 5.1 illustrates the use of nested if..else statement: Program 5.1 //This program illustrates the nested if... else //somasundaramk@yahoo.com class NestedIf { public static void main(String args []) { String result_class; int avg_mark = 62; statement. Control Statements 47 if (avg_mark > 50) if (avg_mark >= 60) if (avg_mark >= 75) result_class = “Distinction”; else result_class = “First Class”; else result_class = “Second Class”; else result_class = “Third Class”; if (avg_mark < 40) System.out.println(“Failed”); else System.out.println(“Passed with “ +result_class); } } The above program gives the following output: Passed with First Class Another form of nested if..else is the ladder if..else statement. structure of the ladder if..else statement is : The if (condition1) statement1; else if (condition2) statement2; else if (condition 3) statement 3; else statement4; The flowchart for the above ladder if...else statement is given in fig. 5.4: 48 Programming in JAVA2 true Condition1 Statement1 false true Condition2 Statement2 false true Condition3 Statement3 false Statement4 Fig.5.4 Flowchart for Ladder if..else Statement The following program 5.2 illustrates the ladder if...else statement: Program 5.2 //This program illustrates the ladder if...else if statement. //somasundaramk@yahoo.com class IfElseIf { public static void main(String args []) { String result_class; int avg_mark = 62; if (avg_mark > 75) result_class = “Distiction”; else if (avg_mark >= 60) result_class = “First Class”; Control Statements 49 else if (avg_mark >= 50) result_class = “Second Class”; else result_class = “Third Class”; if (avg_mark < 40) System.out.println(“Failed”); else System.out.println(“Passed with “ +result_class); } } The above program gives the following output: Passed with First Class 5.2 The switch Statement The switch statement helps to select one out of many choices. This helps to write a clear statement when compared to nested if...else statements. The general form of switch statement is: switch (expression) { case val1 : statement1; break; case val2 : statement2; break; case val3 : statement3; break; . . . case valN : statementN; break; default : statement; } It is expected that the expression, when evaluated, should give discrete values in the range Val1 to valN. If the expression gives val1, the statement1 is executed and the control exits the switch block. If the expression gives val2, statement2 is executed and so on (fig.5.5). If the expression gives any value that is not matching between val1 and valN, the statement given in default is executed. The expression should give any of the type byte, short, int or char. In this way, multiple branching can be effected. The break statement when executed will take the control out of the switch block. Generally, switch statement is used for expressions that may give discrete and predefined values. 50 Programming in JAVA2 Expression = val1 Statement1 = val2 Statement2 = valN StatementN no match Statement Fig.5.5 Flowchart for switch Statement The following program 5.3 illustrates the use of switch statement: Program 5.3 // This program illustrates the switch statement. class SwitchDemo public static void main(String args []) { int month = 5; switch (month) { case 1: System.out.println(“January”); break; case 2: System.out.println(“February”); break; case 3: System.out.println(“March”); break; case 4: System.out.println(“April”); break; case 5: System.out.println(“May”); break; case 6: Control Statements 51 System.out.println(“June”); break; case 7: System.out.println(“July”); break; case 8: System.out.println(“August”); break; case 9: System.out.println(“September”); break; case 10: System.out.println(“October”); break; case 11: System.out.println(“November”); break; case 12: System.out.println(“December”); break; default: System.out.println(“No match”); } } } The above program gives the following output: May Sometimes, for several In such problems, several common to all of them can 5.4 shows how several cases case values, one common process may be required. case values can be clubbed so that statements be executed at one point. The following program can be combined: Program 5.4 // This program illustrates the switch statement. class GroupCase { public static void main(String args []) { int choice = 6; switch (choice) { case 1: case 2: case 3: System.out.println(“Numbers between 1 and 3”); 52 Programming in JAVA2 break; case 4: case 5: case 6: case 7: System.out.println(“Numbers between 4 and 7 “); break; case 8: case 9: case 10: System.out.println(“Numbers between 8 and 10”); break; default: System.out.println(“Numbers outside 1 and 10”); } } } The above program gives the following output: Numbers between 4 and 7 G The type of data handled in switch statement must be of the type byte, short, int or char. The values used must be discrete. 5.3 The while Statement The while statement is used for looping or iterating a block of statements while the given condition is true. The general form of the while statement is: while (condition) { statements; } The condition, when evaluated, must result false. As long as the condition gives true, executed. When the condition becomes false, statement. The flow of control in while statement in the boolean value true or the statement block will be the control leaves the block is given in fig. 5.6. Control Statements 53 true Condition Statements false Fig.5.6 Flowchart for while Statement When the condition tested is false in the first instance itself, the block statement will not be executed at all. The following program 5.5 shows the use of while structure: Program 5.5 // This program illustrates the use of while statement. class WhileDemo { public static void main(String args []) { int n = 10; int sum = 0; while (n > 0) sum += n––; System.out.println(“Sum of numbers from 1 to 10 is= “ + sum); } } The above program gives the following output: Sum of numbers from 1 to 10 is = 55 G In while statement, executing the codes. the condition is checked before 54 Programming in JAVA2 5.4 The do..while Statement This do..while control statement is used for looping a block of statements while the given condition is true. In this structure, the condition is tested at the end of the block. This is in contrast to the while .. statement, where the condition is tested at the start of the block. The general form of do..while statement is: do { statements; } while (condition); The condition tested can be any expression that will yield a boolean value. As long as the condition tested is true, the whole block will be executed. Once the condition tested becomes false, the control leaves the block. It is to be noted that the block is executed once before the condition is tested. Therefore, even if the condition tested is false at the first instance itself, the block statement is executed once. The flowchart of a do..while structure is given in fig.5.7. Statements true Condition false Fig.5.7 Flowchart for do....while Statement The following program 5.6 illustrates the do ... while statement: Control Statements 55 Program 5.6 // This program illustrates the use of do..while statement. class DoWhileDemo { public static void main(String args []) { int n = 10; int sum = 0; do sum += n––; while (n > 0); System.out.println(“Sum of numbers from 1 to 10 is = “ + sum); } } The above program gives the following output: Sum of numbers from 1 to 10 is = 55 G In do...while statement, the condition is checked after executing the codes. 5.5 The for ... Statement This is the third form of looping statement. This statement is a selfcontained one, that is the initial value, termination condition, iterator (increment/ decrement) are all given in the for structure itself. The general form of for statement is: for (initializer; condition; iterator) { statements; } Here, the condition can be any expression that yields boolean value true or false. The initializer is used to store the initial value for a loop variable. The iterator modifies the loop variable. The statements in the block are executed, as long as the condition tested gives true. When the condition becomes false, the control leaves the block statement. The flowchart for the for loop is given in fig. 5.8. 56 Programming in JAVA2 initializer false Condition true Statements iterator Fig.5.8 Flowchart for the for Loop Program 5.7 shows the use of for.. statement. Program 5.7 /* This program illustrates the use of for statement. This program finds the sum of all numbers from 1 up to 10. */ class ForDemo1 { public static void main(String args []) { int n; int sum = 0; for (n = 10; n > 0; n––) sum += n; System.out.println(“Sum of numbers from 1 up to 10 =“ + sum); } } The above program gives the following output: Sum of numbers from 1 up to 10 = 55 Control Statements 57 The above program 5.7 can be written in another form as given in program 5.8. The loop variable n can be declared inside the for structure itself. The iterator is optional. If there is no need for an iterator in a program, it can be left blank. Program 5.8 /* This program illustrates the use of for statement. Notice that n is declared inside the for loop. The iterator is left blank as it has been done in the block statement itself. */ class ForDemo2 { public static void main(String args []) { int sum = 0; for (int n = 10; n > 0; ) sum += n––; System.out.println(“Sum of numbers from 1 up to 10 = “ + sum); } } The for loop in program 5.8 can be improved further and written in a compact form as : for (int n=10; n>0; sum+=n––); G In a for structure, one, two or all the three components, initializer, condition, iterator, can be absent. The statement for ( ; ; ) is valid and will make an infinite loop. The following program 5.9 finds the factorial of numbers from 1 to 10. Program 5.9 // This program finds the factorial of a number using for // statement. class FactProg { public static void main(String args []) { int n = 10; long fact = 1; 58 Programming in JAVA2 for (int i = 1; i <= n; ++i) { fact *= i; System.out.println(“Factorial of “ + i + “ = “ + fact); } } } The above program gives the following output: Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of 1=1 2=2 3=6 4 = 24 5 = 120 6 = 720 7 = 5040 8 = 40320 9 = 362880 10 = 3628800 The for loops can be nested one within another as shown below: - - - - - - - - - - - - - - - - - - for (i=1; i<n; i++) // outer loop begins { - - - - - - - - - - - - - - for (k=1; k<m; k++) // inner loop begins { . . . } // inner loop ends . . . } // outer loops ends . . . The following program 5.10 illustrates the nested for loop. multiplication tables for 2, 3 and 4. It generates Control Statements 59 Program 5.10 // This program illustrates the nested for loop. class MulTable { public static void main(String args []) { int i, j, m = 4, n = 5; int prod; for (i = 2; i <= m; ++i) { System.out.println(“Multiplication Table for“ + i); for (j = 1; j <= n; ++j) { prod = j * i; System.out.println(j + “X” + i + “ = “ + prod); } System.out.println(“ “);//create one line space } } } The above program gives the following output: Multiplication Table for 2 1X2 = 2 2X2 = 4 3X2 = 6 4X2 = 8 5X2 = 10 Multiplication Table for 3 1X3 = 3 2X3 = 6 3X3 = 9 4X3 = 12 5X3 = 15 Multiplication Table for 4 1X4 = 4 2X4 = 8 3X4 = 12 4X4 = 16 5X4 = 20 5.6 The break Statement The break statement is to be used only in loops and switch statement. When this statement is executed, the control is taken out of the loop. The loop becomes dead. The flowchart for the break statement is given in fig. 5.9. 60 Programming in JAVA2 . ¯ . ¯ if(condition) break; . ¯ > start of loop ¬ - normal end of loop > Fig.5.9 The Flowchart for break Statement The following program 5.11 illustrates the use of break in a for loop: Program 5.11 // This program illustrates the use of break statement. class BreakDemo { public static void main(String args []) { int n = 5, m = 20; for (int i = 1; i <= m; i++) { if (n * i > 30) { System.out.println(“Exiting the loop”); break; } System.out.println(i + “X” + n + “ = “ + n * i); } } } The above program gives the following output: 1X5 = 5 2X5 = 10 3X5 = 15 4X5 = 20 5X5 = 25 6X5 = 30 Exiting the loop Blocks can be labeled and the break control can be made to exit any labeled block. This is called labeled break. The label for a block can be Control Statements 61 formed by using the rules to form a variable. The labeled break is useful when using nested loops. The following program 5.12 illustrates the labeled break statement: Program 5.12 // This program illustrates the use of labeled break. class LabelBreak { public static void main(String args []) { int n = 0, m = 0; loop1: while (true) { n++; m = 0; System.out.println(“\n loop1 “ + “n = “ + n); loop2: while (++m <= n) { if (n * m > 10) { System.out.println(“Exiting loop2 and loop1”); break loop1; } System.out.println(“loop2 “ + m + “X” + n + “ = “ + n * m); } } System.out.println(“outside loop1”); } } The above program gives the following output: loop1 n = 1 loop2 1X1 = 1 loop1 n = 2 loop2 1X2 = 2 loop2 2X2 = 4 loop1 n = 3 loop2 1X3 = 3 loop2 2X3 = 6 loop2 3X3 = 9 62 Programming in JAVA2 loop1 n = 4 loop2 1X4 = 4 loop2 2X4 = 8 Exiting loop2 and loop1 outside loop1 5.7 The continue Statement The continue statement is used inside the loop control blocks. When the continue statement is executed, the control skips the remaining portion of the loop and goes to the beginning of the loop and continue. The flowchart for the continue statement is given in fig. 5.10: start of loop ¬ - .. ¯ if(condition) continue; ® . ¯ > normal - end of loop Fig.5.10 Flowchart for continue Statement The following program 5.13 illustrates the use of continue statement: Program 5.13 // This program illustrates the use of continue statement. class ContinueProg { public static void main(String args []) { int i = 0; while (++i < 10) { if (i % 2 == 0) continue; System.out.println(i); } } } Control Statements 63 The above program gives the following outptut: 1 3 5 7 9 Like labeled break, labeled continue structure is also available. following program 5.14 illustrates the use of labeled continue: The Program 5.14 // This program illustrates the use of labeled continue // statement. // This program generates prime numbers between 1 and 15. // somasundaramk@yahoo.com class LabelContinue { public static void main(String args []) { int i = 1, n, max = 15; System.out.println(“Prime numbers between 1 and 15”); System.out.println(i); start: for (n = 2; n <= max; ++n) { test: for (i = 2; i < n; ++i) if (n % i == 0) continue start; System.out.println(n); } } } The above program gives the following output: Prime numbers between 1 and 15 1 2 3 5 7 11 13 64 Programming in JAVA2 5.8 The comma Statement Java allows multiple initialization and iteration in the for statement. With this capability, more than one variable can be initialized and more than one iteration can be done. Each of such statements are to be separated by a comma(,). But there can be only one conditional expression. The general form of the multiple initialization and iteration is: for (init1, init2, init3; condition; itr1, itr2, itr3) { Statements; } The following program 5.15 illustrates the use of comma statement. Program 5.15 // This program illustrates the use of comma statement. class CommaDemo { public static void main(String args []) { int n, i, sum; for (i = 1, n = 5; n > 0; i++, n—, sum = 0) { sum = i + n; System.out.println(i + “ + “ + n + “ = “ + sum); } } } The output for the above program is : 1+5=6 2+4=6 3+3=6 4+2=6 5+1=6 After reading this chapter, you should have learned the following: Ü Branching using if...else control Ü Branching using switch control Ü Looping with while, do...while and for...control Ü Using break and continue In the next chapter, you will learn about arrays. Control Statements 65 Worked Out Problems–5 Problem 5.1w The trigonometric functions Sin(x) and Cos(x) are computed using the following formula: Sin(x) = Cos(x) = x3 x – 3! x2 1 – 2! + + x5 5! x4 4! – – x7 7! x6 6! + + x9 9! x8 8! – x 11 11! – x 10 10! Calculate the Sin(x) and Cos(x) values for x=0, 0.5 and 1.5. The following expressions which represent the above are made use of: Sin(x) = m S x + n=1 m Cos(x) = 1 + S n=1 (–1) n x 2n+1 (2n+1)! (–1) n x 2n 2n! Program 5.1w /* ------------------------------------------------------------This program calculates the sin(x) and cos(x) functions. The values obtained are compared with those of Java functions. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Prob51 { public static void main(String args []) { double x, sinx, cosx; int n, fact = 1, factn, factnplus; int m = 5; for (int i = 0; i < 80; i++) 66 Programming in JAVA2 System.out.print("-"); System.out.println("\n"); System.out.println("x \t my sinx \t Java sinx \t my cosx \t Java cosx\n"); for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); for (x = 0; x < 1.6; ) { sinx = x; cosx = 1; for (n = 1; n <= m; n++) { factn = 1; factnplus = 1; for (int i = 2; i <= 2 * n; i++) factn = factn * i; for (int i = 2; i <= (2 * n + 1); i++) factnplus = factnplus * i; sinx = sinx + Math.pow(-1, n) * Math.pow(x, (2 * n + 1)) / factnplus; cosx = cosx + Math.pow(-1, n) * Math.pow(x, 2 * n) / factn; } // Reduce the fractional digits for display double sx = (int)(sinx * 1000); double cx = (int)(cosx * 1000); sinx = sx / 1000; cosx = cx / 1000; double jsx = (int)(Math.sin(x) * 1000); double jcx = (int)(Math.cos(x) * 1000); jsx = jsx / 1000; jcx = jcx / 1000; Control Statements 67 System.out.println(x + "\t" + sinx + "\t\t" + jsx +"\t\t" + cosx + "\t\t" + jcx); x = x + 0.5; } for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------------------------------------x my sinx Java sinx my cosx Java cosx -------------------------------------------------------------------------------0.0 0.0 0.0 1.0 0.5 0.479 0.479 0.877 1.0 0.841 0.841 0.54 1.5 0.997 0.997 0.07 -------------------------------------------------------------------------------- 1.0 0.877 0.54 0.07 Problem 5.2w An electricity board charges different rates for different categories of consumption of power. Category 1 is domestic users, category 2 is educational institutions, category 3 is commercial institutions and category 4 is industries. The tariff for energy consumption is Rs.1.00 / unit for category 1, Rs.1.75 / unit for category 2, Rs. 2.50 / unit for category 3 and Rs.3.00 / unit for category 4. Write a program to calculate electricity charges for the following data: Consumer Category Unit Consumed Raman 1 75 Balaji 1 250 Public School 2 800 ABC Hardware 3 550 R.M.K. Industry 4 12450 68 Programming in JAVA2 Program 5.2w /* ------------------------------------------------------This program calculates the electricity charges for different categories of consumers. somasundaramk@yahoo.com ------------------------------------------------------------ */ class Prob52 { public static void main(String args []) { String consumers [] = { "Raman", "Balaji", "Public School", "ABC Hardware", "R.M.K.Industry" }; int units [] = {75,250, 800, 550, 12450 }; int conscat [] = { 1, 1, 2, 3, 4 }; double rate [] = {1.0, 1.75, 2.50, 3.0 }; int noc = consumers.length; int i; double bill = 0; //Calculate the electricity charges for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); System.out.println("\t Consumer \t Category \t Units \t Charges"); for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); for (i = 0; i < noc; i++) { switch (conscat[i]) { case 1: bill = units[i] * 1.0; break; case 2: bill = units[i] * 1.75; break; case 3: bill = units[i] * 2.5; break; Control Statements 69 case 4: bill = units[i] * 3.0; break; default: System.out.println("Category mismatch"); } //reduce the number of decimal places bill = (int)(bill * 100); bill = bill / 100; System.out.println(consumers[i] + "\t\t" + conscat[i] + "\t" + units[i] + "\t" + bill); } for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------------------------------------Consumer Category Units Charges -------------------------------------------------------------------------------Raman 1 75 75.0 Balaji 1 250 250.0 Public School 2 800 1400.0 ABC Hardware 3 550 1375.0 R.M.K.Industry 4 12450 37350.0 -------------------------------------------------------------------------------- Exercise–5 I. Fill in the blanks 5.1. if..else structure helps to make a ________ from the sequential computation of statements in a program. 5.2. To select one out of many options in a computation, _______ if-else can be used. 5.3. switch statement can be used to select one out ______ options. 5.4. The case value in a switch statement must be _________ . 70 Programming in JAVA2 5.5. The _______ statement tests the condition at the end of the block. 5.6. In a for..loop the condition is tested at the ________ of the block. 5.7. In a for.. statement more than one initializer is allowed. (True/False) 5.8. In a for..statement with more than one initializer, there can be more than one condition. (True/False) 5.9. The break statement can be used only in ______ and ______ statements. 5.10. The _______ statement when encountered takes the control to the end of the loop block. II. Write programs for the following: 5.11. A cloth shop during festival season offers a discount 10% for purchases made up to Rs.1,000, 12% for purchase value of Rs.1000 or more up to Rs 1,500 and 15% for purchase made for Rs.1,500 or more. Write a program to implement the above scheme for a given sales and print out the sales value, discount and net amount payable by a customer. 5.12. The roots of a quadratic equation ax 2+bx+c=0 are given by : –b+ Ö b 2–4ac , x1 = 2a x2 = –b– Ö b 2–4ac 2a , with the condition if (b 2 –4ac) < 0, then the obsolute value |(b 2-ac)| is to be taken. Given a, b, c, write a Java program to compute the two roots x 1 and x 2 . 5.13 An electric appliance shop assigns code 1 to motor, 2 to fan, 3 to tube light and 4 for wires. All other items have code 5 or more. While selling the goods, a sales tax of 8% to motor, 12% to fan, 5% to tube light, 7.5% to wires and 3% for all other items is charged. A list containing the product code and price is given for making a bill. Write a Java program using switch statement to prepare the bill. * * * * * * 43 Chapter 5 CONTROL STATEMENTS In this chapter, the statements that take the control from one location to another during execution are given. The control statements help to make branching, looping, skipping and exiting a block of codes. Basically, any computer-oriented problem can be solved using any combination of sequential, branching and looping structure. Therefore, a computer programming language should support these three structures. In this chapter, the statements supporting the branching and looping structures in Java are given. These statements help to branch or loop a segment of statements and are called control statements. 5.1 The if..else Statement This statement helps to select one out of two possibilities based on the given condition. Hence, this statement is also called as conditional if statement. The general form of the statement is: if (conditional expression) statement1; else statement2; The conditional expression should result in a boolean value. If the condition, on evaluation, gives true, statement1 is executed and the control skips statement2, otherwise statement1 is skipped and statement2 is executed. 44 Programming in JAVA2 The statement1 and the statement2 can be a simple or block statement. else part is optional and, if needed, can be left out and can take the form: The if (conditional expression) statement; In this form, the statement will be executed, if the conditional expression gives true, otherwise it is skipped. The flowchart for if...else and if... are given in fig.5.1 and fig.5.2 respectively. true false Condition Statement1 Fig.5.1 Statement2 Flowchart for if...else Statement true Condition Statement false Fig.5.2 Flowchart for if...Statement Control Statements The following statement: examples, 5.1 45 and 5.2, illustrate the if...else and if Example 5.1 int mark; String result; if (mark >= 40) result = “Pass”; else result = “Fail”; Example 5.2 double a, b, c, discr, term; discr = b*b-4.0*a*c; if (discr < 0) discr = -discr; term = Maths.sqrt(discr); root1 = (-b+term)/(2.0*a); root2 = (-b-term)/(2.0*a); Nested if..else Nested if..else statement is made by placing one if..else inside another if..else statement. Nested if..else statement helps to select one out of many choices. The general form of if..else statement is : if (condition1) if (condition2) if (condition3) statement 4 else statement 3 else statement 2 else statement 1 In the nested if..else statement, the outermost if is evaluated first. If the condition1 tested is false, the statement1 in the outmost else is evaluated and if..else ends. If the condition1 results in true, the control goes to execute the next inner if statement. If condition2 is false, statement2 is executed. Otherwise, condition3 is evaluated. If condition3 is false, statement3 is executed, otherwise statement4 is executed. 46 Programming in JAVA2 The flowchart for the nested if..else is given in fig.5.3: false Condition1 Statement1 true false Condition2 Statement2 true false Condition3 Statement3 true Statement4 Fig.5.3 Flowchart for nested if...else Statement The following program 5.1 illustrates the use of nested if..else statement: Program 5.1 //This program illustrates the nested if... else //somasundaramk@yahoo.com class NestedIf { public static void main(String args []) { String result_class; int avg_mark = 62; statement. Control Statements 47 if (avg_mark > 50) if (avg_mark >= 60) if (avg_mark >= 75) result_class = “Distinction”; else result_class = “First Class”; else result_class = “Second Class”; else result_class = “Third Class”; if (avg_mark < 40) System.out.println(“Failed”); else System.out.println(“Passed with “ +result_class); } } The above program gives the following output: Passed with First Class Another form of nested if..else is the ladder if..else statement. structure of the ladder if..else statement is : The if (condition1) statement1; else if (condition2) statement2; else if (condition 3) statement 3; else statement4; The flowchart for the above ladder if...else statement is given in fig. 5.4: 48 Programming in JAVA2 true Condition1 Statement1 false true Condition2 Statement2 false true Condition3 Statement3 false Statement4 Fig.5.4 Flowchart for Ladder if..else Statement The following program 5.2 illustrates the ladder if...else statement: Program 5.2 //This program illustrates the ladder if...else if statement. //somasundaramk@yahoo.com class IfElseIf { public static void main(String args []) { String result_class; int avg_mark = 62; if (avg_mark > 75) result_class = “Distiction”; else if (avg_mark >= 60) result_class = “First Class”; Control Statements 49 else if (avg_mark >= 50) result_class = “Second Class”; else result_class = “Third Class”; if (avg_mark < 40) System.out.println(“Failed”); else System.out.println(“Passed with “ +result_class); } } The above program gives the following output: Passed with First Class 5.2 The switch Statement The switch statement helps to select one out of many choices. This helps to write a clear statement when compared to nested if...else statements. The general form of switch statement is: switch (expression) { case val1 : statement1; break; case val2 : statement2; break; case val3 : statement3; break; . . . case valN : statementN; break; default : statement; } It is expected that the expression, when evaluated, should give discrete values in the range Val1 to valN. If the expression gives val1, the statement1 is executed and the control exits the switch block. If the expression gives val2, statement2 is executed and so on (fig.5.5). If the expression gives any value that is not matching between val1 and valN, the statement given in default is executed. The expression should give any of the type byte, short, int or char. In this way, multiple branching can be effected. The break statement when executed will take the control out of the switch block. Generally, switch statement is used for expressions that may give discrete and predefined values. 50 Programming in JAVA2 Expression = val1 Statement1 = val2 Statement2 = valN StatementN no match Statement Fig.5.5 Flowchart for switch Statement The following program 5.3 illustrates the use of switch statement: Program 5.3 // This program illustrates the switch statement. class SwitchDemo public static void main(String args []) { int month = 5; switch (month) { case 1: System.out.println(“January”); break; case 2: System.out.println(“February”); break; case 3: System.out.println(“March”); break; case 4: System.out.println(“April”); break; case 5: System.out.println(“May”); break; case 6: Control Statements 51 System.out.println(“June”); break; case 7: System.out.println(“July”); break; case 8: System.out.println(“August”); break; case 9: System.out.println(“September”); break; case 10: System.out.println(“October”); break; case 11: System.out.println(“November”); break; case 12: System.out.println(“December”); break; default: System.out.println(“No match”); } } } The above program gives the following output: May Sometimes, for several In such problems, several common to all of them can 5.4 shows how several cases case values, one common process may be required. case values can be clubbed so that statements be executed at one point. The following program can be combined: Program 5.4 // This program illustrates the switch statement. class GroupCase { public static void main(String args []) { int choice = 6; switch (choice) { case 1: case 2: case 3: System.out.println(“Numbers between 1 and 3”); 52 Programming in JAVA2 break; case 4: case 5: case 6: case 7: System.out.println(“Numbers between 4 and 7 “); break; case 8: case 9: case 10: System.out.println(“Numbers between 8 and 10”); break; default: System.out.println(“Numbers outside 1 and 10”); } } } The above program gives the following output: Numbers between 4 and 7 G The type of data handled in switch statement must be of the type byte, short, int or char. The values used must be discrete. 5.3 The while Statement The while statement is used for looping or iterating a block of statements while the given condition is true. The general form of the while statement is: while (condition) { statements; } The condition, when evaluated, must result false. As long as the condition gives true, executed. When the condition becomes false, statement. The flow of control in while statement in the boolean value true or the statement block will be the control leaves the block is given in fig. 5.6. Control Statements 53 true Condition Statements false Fig.5.6 Flowchart for while Statement When the condition tested is false in the first instance itself, the block statement will not be executed at all. The following program 5.5 shows the use of while structure: Program 5.5 // This program illustrates the use of while statement. class WhileDemo { public static void main(String args []) { int n = 10; int sum = 0; while (n > 0) sum += n––; System.out.println(“Sum of numbers from 1 to 10 is= “ + sum); } } The above program gives the following output: Sum of numbers from 1 to 10 is = 55 G In while statement, executing the codes. the condition is checked before 54 Programming in JAVA2 5.4 The do..while Statement This do..while control statement is used for looping a block of statements while the given condition is true. In this structure, the condition is tested at the end of the block. This is in contrast to the while .. statement, where the condition is tested at the start of the block. The general form of do..while statement is: do { statements; } while (condition); The condition tested can be any expression that will yield a boolean value. As long as the condition tested is true, the whole block will be executed. Once the condition tested becomes false, the control leaves the block. It is to be noted that the block is executed once before the condition is tested. Therefore, even if the condition tested is false at the first instance itself, the block statement is executed once. The flowchart of a do..while structure is given in fig.5.7. Statements true Condition false Fig.5.7 Flowchart for do....while Statement The following program 5.6 illustrates the do ... while statement: Control Statements 55 Program 5.6 // This program illustrates the use of do..while statement. class DoWhileDemo { public static void main(String args []) { int n = 10; int sum = 0; do sum += n––; while (n > 0); System.out.println(“Sum of numbers from 1 to 10 is = “ + sum); } } The above program gives the following output: Sum of numbers from 1 to 10 is = 55 G In do...while statement, the condition is checked after executing the codes. 5.5 The for ... Statement This is the third form of looping statement. This statement is a selfcontained one, that is the initial value, termination condition, iterator (increment/ decrement) are all given in the for structure itself. The general form of for statement is: for (initializer; condition; iterator) { statements; } Here, the condition can be any expression that yields boolean value true or false. The initializer is used to store the initial value for a loop variable. The iterator modifies the loop variable. The statements in the block are executed, as long as the condition tested gives true. When the condition becomes false, the control leaves the block statement. The flowchart for the for loop is given in fig. 5.8. 56 Programming in JAVA2 initializer false Condition true Statements iterator Fig.5.8 Flowchart for the for Loop Program 5.7 shows the use of for.. statement. Program 5.7 /* This program illustrates the use of for statement. This program finds the sum of all numbers from 1 up to 10. */ class ForDemo1 { public static void main(String args []) { int n; int sum = 0; for (n = 10; n > 0; n––) sum += n; System.out.println(“Sum of numbers from 1 up to 10 =“ + sum); } } The above program gives the following output: Sum of numbers from 1 up to 10 = 55 Control Statements 57 The above program 5.7 can be written in another form as given in program 5.8. The loop variable n can be declared inside the for structure itself. The iterator is optional. If there is no need for an iterator in a program, it can be left blank. Program 5.8 /* This program illustrates the use of for statement. Notice that n is declared inside the for loop. The iterator is left blank as it has been done in the block statement itself. */ class ForDemo2 { public static void main(String args []) { int sum = 0; for (int n = 10; n > 0; ) sum += n––; System.out.println(“Sum of numbers from 1 up to 10 = “ + sum); } } The for loop in program 5.8 can be improved further and written in a compact form as : for (int n=10; n>0; sum+=n––); G In a for structure, one, two or all the three components, initializer, condition, iterator, can be absent. The statement for ( ; ; ) is valid and will make an infinite loop. The following program 5.9 finds the factorial of numbers from 1 to 10. Program 5.9 // This program finds the factorial of a number using for // statement. class FactProg { public static void main(String args []) { int n = 10; long fact = 1; 58 Programming in JAVA2 for (int i = 1; i <= n; ++i) { fact *= i; System.out.println(“Factorial of “ + i + “ = “ + fact); } } } The above program gives the following output: Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of Factorial of 1=1 2=2 3=6 4 = 24 5 = 120 6 = 720 7 = 5040 8 = 40320 9 = 362880 10 = 3628800 The for loops can be nested one within another as shown below: - - - - - - - - - - - - - - - - - - for (i=1; i<n; i++) // outer loop begins { - - - - - - - - - - - - - - for (k=1; k<m; k++) // inner loop begins { . . . } // inner loop ends . . . } // outer loops ends . . . The following program 5.10 illustrates the nested for loop. multiplication tables for 2, 3 and 4. It generates Control Statements 59 Program 5.10 // This program illustrates the nested for loop. class MulTable { public static void main(String args []) { int i, j, m = 4, n = 5; int prod; for (i = 2; i <= m; ++i) { System.out.println(“Multiplication Table for“ + i); for (j = 1; j <= n; ++j) { prod = j * i; System.out.println(j + “X” + i + “ = “ + prod); } System.out.println(“ “);//create one line space } } } The above program gives the following output: Multiplication Table for 2 1X2 = 2 2X2 = 4 3X2 = 6 4X2 = 8 5X2 = 10 Multiplication Table for 3 1X3 = 3 2X3 = 6 3X3 = 9 4X3 = 12 5X3 = 15 Multiplication Table for 4 1X4 = 4 2X4 = 8 3X4 = 12 4X4 = 16 5X4 = 20 5.6 The break Statement The break statement is to be used only in loops and switch statement. When this statement is executed, the control is taken out of the loop. The loop becomes dead. The flowchart for the break statement is given in fig. 5.9. 60 Programming in JAVA2 . ¯ . ¯ if(condition) break; . ¯ > start of loop ¬ - normal end of loop > Fig.5.9 The Flowchart for break Statement The following program 5.11 illustrates the use of break in a for loop: Program 5.11 // This program illustrates the use of break statement. class BreakDemo { public static void main(String args []) { int n = 5, m = 20; for (int i = 1; i <= m; i++) { if (n * i > 30) { System.out.println(“Exiting the loop”); break; } System.out.println(i + “X” + n + “ = “ + n * i); } } } The above program gives the following output: 1X5 = 5 2X5 = 10 3X5 = 15 4X5 = 20 5X5 = 25 6X5 = 30 Exiting the loop Blocks can be labeled and the break control can be made to exit any labeled block. This is called labeled break. The label for a block can be Control Statements 61 formed by using the rules to form a variable. The labeled break is useful when using nested loops. The following program 5.12 illustrates the labeled break statement: Program 5.12 // This program illustrates the use of labeled break. class LabelBreak { public static void main(String args []) { int n = 0, m = 0; loop1: while (true) { n++; m = 0; System.out.println(“\n loop1 “ + “n = “ + n); loop2: while (++m <= n) { if (n * m > 10) { System.out.println(“Exiting loop2 and loop1”); break loop1; } System.out.println(“loop2 “ + m + “X” + n + “ = “ + n * m); } } System.out.println(“outside loop1”); } } The above program gives the following output: loop1 n = 1 loop2 1X1 = 1 loop1 n = 2 loop2 1X2 = 2 loop2 2X2 = 4 loop1 n = 3 loop2 1X3 = 3 loop2 2X3 = 6 loop2 3X3 = 9 62 Programming in JAVA2 loop1 n = 4 loop2 1X4 = 4 loop2 2X4 = 8 Exiting loop2 and loop1 outside loop1 5.7 The continue Statement The continue statement is used inside the loop control blocks. When the continue statement is executed, the control skips the remaining portion of the loop and goes to the beginning of the loop and continue. The flowchart for the continue statement is given in fig. 5.10: start of loop ¬ - .. ¯ if(condition) continue; ® . ¯ > normal - end of loop Fig.5.10 Flowchart for continue Statement The following program 5.13 illustrates the use of continue statement: Program 5.13 // This program illustrates the use of continue statement. class ContinueProg { public static void main(String args []) { int i = 0; while (++i < 10) { if (i % 2 == 0) continue; System.out.println(i); } } } Control Statements 63 The above program gives the following outptut: 1 3 5 7 9 Like labeled break, labeled continue structure is also available. following program 5.14 illustrates the use of labeled continue: The Program 5.14 // This program illustrates the use of labeled continue // statement. // This program generates prime numbers between 1 and 15. // somasundaramk@yahoo.com class LabelContinue { public static void main(String args []) { int i = 1, n, max = 15; System.out.println(“Prime numbers between 1 and 15”); System.out.println(i); start: for (n = 2; n <= max; ++n) { test: for (i = 2; i < n; ++i) if (n % i == 0) continue start; System.out.println(n); } } } The above program gives the following output: Prime numbers between 1 and 15 1 2 3 5 7 11 13 64 Programming in JAVA2 5.8 The comma Statement Java allows multiple initialization and iteration in the for statement. With this capability, more than one variable can be initialized and more than one iteration can be done. Each of such statements are to be separated by a comma(,). But there can be only one conditional expression. The general form of the multiple initialization and iteration is: for (init1, init2, init3; condition; itr1, itr2, itr3) { Statements; } The following program 5.15 illustrates the use of comma statement. Program 5.15 // This program illustrates the use of comma statement. class CommaDemo { public static void main(String args []) { int n, i, sum; for (i = 1, n = 5; n > 0; i++, n—, sum = 0) { sum = i + n; System.out.println(i + “ + “ + n + “ = “ + sum); } } } The output for the above program is : 1+5=6 2+4=6 3+3=6 4+2=6 5+1=6 After reading this chapter, you should have learned the following: Ü Branching using if...else control Ü Branching using switch control Ü Looping with while, do...while and for...control Ü Using break and continue In the next chapter, you will learn about arrays. Control Statements 65 Worked Out Problems–5 Problem 5.1w The trigonometric functions Sin(x) and Cos(x) are computed using the following formula: Sin(x) = Cos(x) = x3 x – 3! x2 1 – 2! + + x5 5! x4 4! – – x7 7! x6 6! + + x9 9! x8 8! – x 11 11! – x 10 10! Calculate the Sin(x) and Cos(x) values for x=0, 0.5 and 1.5. The following expressions which represent the above are made use of: Sin(x) = m S x + n=1 m Cos(x) = 1 + S n=1 (–1) n x 2n+1 (2n+1)! (–1) n x 2n 2n! Program 5.1w /* ------------------------------------------------------------This program calculates the sin(x) and cos(x) functions. The values obtained are compared with those of Java functions. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Prob51 { public static void main(String args []) { double x, sinx, cosx; int n, fact = 1, factn, factnplus; int m = 5; for (int i = 0; i < 80; i++) 66 Programming in JAVA2 System.out.print("-"); System.out.println("\n"); System.out.println("x \t my sinx \t Java sinx \t my cosx \t Java cosx\n"); for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); for (x = 0; x < 1.6; ) { sinx = x; cosx = 1; for (n = 1; n <= m; n++) { factn = 1; factnplus = 1; for (int i = 2; i <= 2 * n; i++) factn = factn * i; for (int i = 2; i <= (2 * n + 1); i++) factnplus = factnplus * i; sinx = sinx + Math.pow(-1, n) * Math.pow(x, (2 * n + 1)) / factnplus; cosx = cosx + Math.pow(-1, n) * Math.pow(x, 2 * n) / factn; } // Reduce the fractional digits for display double sx = (int)(sinx * 1000); double cx = (int)(cosx * 1000); sinx = sx / 1000; cosx = cx / 1000; double jsx = (int)(Math.sin(x) * 1000); double jcx = (int)(Math.cos(x) * 1000); jsx = jsx / 1000; jcx = jcx / 1000; Control Statements 67 System.out.println(x + "\t" + sinx + "\t\t" + jsx +"\t\t" + cosx + "\t\t" + jcx); x = x + 0.5; } for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------------------------------------x my sinx Java sinx my cosx Java cosx -------------------------------------------------------------------------------0.0 0.0 0.0 1.0 0.5 0.479 0.479 0.877 1.0 0.841 0.841 0.54 1.5 0.997 0.997 0.07 -------------------------------------------------------------------------------- 1.0 0.877 0.54 0.07 Problem 5.2w An electricity board charges different rates for different categories of consumption of power. Category 1 is domestic users, category 2 is educational institutions, category 3 is commercial institutions and category 4 is industries. The tariff for energy consumption is Rs.1.00 / unit for category 1, Rs.1.75 / unit for category 2, Rs. 2.50 / unit for category 3 and Rs.3.00 / unit for category 4. Write a program to calculate electricity charges for the following data: Consumer Category Unit Consumed Raman 1 75 Balaji 1 250 Public School 2 800 ABC Hardware 3 550 R.M.K. Industry 4 12450 68 Programming in JAVA2 Program 5.2w /* ------------------------------------------------------This program calculates the electricity charges for different categories of consumers. somasundaramk@yahoo.com ------------------------------------------------------------ */ class Prob52 { public static void main(String args []) { String consumers [] = { "Raman", "Balaji", "Public School", "ABC Hardware", "R.M.K.Industry" }; int units [] = {75,250, 800, 550, 12450 }; int conscat [] = { 1, 1, 2, 3, 4 }; double rate [] = {1.0, 1.75, 2.50, 3.0 }; int noc = consumers.length; int i; double bill = 0; //Calculate the electricity charges for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); System.out.println("\t Consumer \t Category \t Units \t Charges"); for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); for (i = 0; i < noc; i++) { switch (conscat[i]) { case 1: bill = units[i] * 1.0; break; case 2: bill = units[i] * 1.75; break; case 3: bill = units[i] * 2.5; break; Control Statements 69 case 4: bill = units[i] * 3.0; break; default: System.out.println("Category mismatch"); } //reduce the number of decimal places bill = (int)(bill * 100); bill = bill / 100; System.out.println(consumers[i] + "\t\t" + conscat[i] + "\t" + units[i] + "\t" + bill); } for (i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------------------------------------Consumer Category Units Charges -------------------------------------------------------------------------------Raman 1 75 75.0 Balaji 1 250 250.0 Public School 2 800 1400.0 ABC Hardware 3 550 1375.0 R.M.K.Industry 4 12450 37350.0 -------------------------------------------------------------------------------- Exercise–5 I. Fill in the blanks 5.1. if..else structure helps to make a ________ from the sequential computation of statements in a program. 5.2. To select one out of many options in a computation, _______ if-else can be used. 5.3. switch statement can be used to select one out ______ options. 5.4. The case value in a switch statement must be _________ . 70 Programming in JAVA2 5.5. The _______ statement tests the condition at the end of the block. 5.6. In a for..loop the condition is tested at the ________ of the block. 5.7. In a for.. statement more than one initializer is allowed. (True/False) 5.8. In a for..statement with more than one initializer, there can be more than one condition. (True/False) 5.9. The break statement can be used only in ______ and ______ statements. 5.10. The _______ statement when encountered takes the control to the end of the loop block. II. Write programs for the following: 5.11. A cloth shop during festival season offers a discount 10% for purchases made up to Rs.1,000, 12% for purchase value of Rs.1000 or more up to Rs 1,500 and 15% for purchase made for Rs.1,500 or more. Write a program to implement the above scheme for a given sales and print out the sales value, discount and net amount payable by a customer. 5.12. The roots of a quadratic equation ax 2+bx+c=0 are given by : –b+ Ö b 2–4ac , x1 = 2a x2 = –b– Ö b 2–4ac 2a , with the condition if (b 2 –4ac) < 0, then the obsolute value |(b 2-ac)| is to be taken. Given a, b, c, write a Java program to compute the two roots x 1 and x 2 . 5.13 An electric appliance shop assigns code 1 to motor, 2 to fan, 3 to tube light and 4 for wires. All other items have code 5 or more. While selling the goods, a sales tax of 8% to motor, 12% to fan, 5% to tube light, 7.5% to wires and 3% for all other items is charged. A list containing the product code and price is given for making a bill. Write a Java program using switch statement to prepare the bill. * * * * * * Arrays The following program 6.3 illustrates the use of two-dimensional array: Program 6.3 // This program illustrates the use of two-dimensional array. class TwoDArray { public static void main(String args []) { int mat [][] = new int[3][4]; //assign values to the elements for (int row = 0; row < 3; row++) for (int column = 0; column < 4; column++) mat[row][column] = row * column; //print the matix for (int row = 0; row < 3; row++) { for (int column = 0; column < 4; column++) System.out.print(“ “ + mat[row][column]); System.out.println(); // print a new line } } } The output of the above program is: 0 0 0 0 0 1 2 3 0 2 4 6 0 3 6 9 In Java, it is possible to have rows of varying columns as given below: int mat [ ] [ ] = new int [3] [ ]; mat[0] = new int [2]; mat[1] = new int [3]; mat[2] = new int [4]; The above statements create the following rows and columns: mat [ ][ ] 0 1 2 3 0 1 2 Fig.6.2 Multi-Dimensional Array with Varying Columns 75 76 Programming in JAVA2 The above statements create a two-dimensional array with row 0 with 2 column elements, row 1 with 3 columns and row 2 with 4 columns. G Matrix of varying column elements can be created in Java. Multi-dimensional arrays can be initialized like one-dimensional array. Each row is enclosed in a pair of braces { } separated by a comma(,). All the rows are then placed inside another pair of braces { } separated by comma(,). The following program 6.4 illustrates the use of initializing two-dimensional array of 3 rows and 4 columns: Program 6.4 // This program illustrates the // initialization of a two-dimensional array. class MultiDInit { public static void main(String args []) { int mat [][] = { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 } }; System.out.println(“The given matrix\n”); for (int row = 0; row < 3; row++) { for (int column = 0; column < 4; column++) System.out.print(“ “ + mat[row][column]); System.out.println(); } } } The above program gives the following result: 0 4 8 1 5 9 2 6 10 3 7 11 In engineering and scientific computations, matrix multiplication is commonly used. The following program 6.5 illustrates one such example. The following program initializes a matrix mat1 with 2 x 3 elements, another one mat2 with 3 x 3 elements and finds the product of both to give a third matrix mat3 of 2 x 3 elements. Arrays Program 6.5 // This program carries out matrix multiplication. class MatMul { public static void main(String args []) { int mat1 [][] = { { 5, 4, 7 }, { 1, 7, 4 } }; int mat2 [][] = { { 1, 5, 7 }, { 2, 4, 6 }, { 3, 5, 7 } }; int mat3 [][] = new int[2][3]; int i, j, k; for (i = 0; i < 2; i++) for (k = 0; k < 3; k++) { mat3[i][k] = 0; for (j = 0; j < 3; j++) mat3[i][k] = mat3[i][k] + mat1[i][j] * mat2[j][k]; } System.out.println(“\nMatrix 1\n”); for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) System.out.print(“ “ + mat1[i][j]); System.out.println(); } System.out.println(“\nMatrix 2\n”); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) System.out.print(“ “ + mat2[i][j]); System.out.println(); } System.out.println(“\nProduct Matrix\n “); for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) System.out.print(“ “ + mat3[i][j]); 77 78 Programming in JAVA2 System.out.println(); } } } The above program gives the following output: Matrix 1 5 4 7 1 7 4 Matrix 2 1 5 7 2 4 6 3 5 7 Product Matrix 34 76 108 27 53 77 After reading this chapter, you should have learned the following: Ü A collection of like type is called an array. Ü Array elements can be accessed by an index. Ü Single and multi-dimensional arrays are supported in Java language. Ü Multi-dimensional arrays with varying columns can be declared. In the next chapter, you will learn about Java classes. Arrays 79 Worked Out Problems–6 Problem 6.1w Write a program to arrange a set of n integers in descending order. Program 6.1w /*---------------------------------------------------------This program arranges the given set of integers in a descending order. somasundaramk@yahoo.com ------------------------------------------------------------ */ class Prob61 { public static void main(String args []) { int mark [] = { 35, 56, 76, 45, 87, 61, 53, 87, 79, 80, 50, 25, 35, 48 }; int temp, i, j; int maxn = mark.length; // Print out the given numbers System.out.println("The given numbers \n"); for (i = 0; i < maxn; i++) System.out.print(mark[i] + " "); System.out.println(" \n "); // Sort the numbers in descending order for (i = 0; i < maxn; i++) { for (j = i + 1; j < maxn; j++) if (mark[j] > mark[i]) { temp = mark[i]; mark[i] = mark[j]; mark[j] = temp; } } // Print out the sorted numbers System.out.println("The sorted numbers \n"); for (i = 0; i < maxn; i++) System.out.print(mark[i] + " "); } } The above program gives the following output: 80 Programming in JAVA2 The given numbers 35 56 76 45 87 61 53 87 79 80 50 25 35 48 The sorted numbers 87 87 80 79 76 61 56 53 50 48 45 35 35 25 Problem 6.2w The runs scored by 5 batsman in 4 cricket matches played in different cities are given below. Find out the total and average runs scored by each player. Find out the player who scored the highest total. Sehwag Sachin Dravid Yuvaraj Ganguly Delhi 45 75 51 40 35 Mumbai 130 170 45 70 90 Kolkata 10 60 125 65 55 Chennai 75 55 65 40 120 Program 6.2w /* ----------------------------------------------------------This program finds out the total score, average score and the highest scorer among 5 cricket players for games played in 4 different places. somasundaramk@yahoo.com ----------------------------------------------------------- */ class Prob62 { public static void main(String args []) { String players [] = {“Sehwag","Sachin", "Dravid", "Yuvaraj", "Ganguly" }; String places [] = { "Delhi", "Mumbai", "Kolkata", "Chennai" }; int scores [][] ={ {45,75,51,40,35}, {130,170,45,70,90}, {10,60,125,65,55}, {75,55,65,40,120} }; Arrays int row, column; row = scores.length; column = scores[0].length; int total [] = new int[column]; int average [] = new int[column]; int maxscore; String maxplayer; //Print out the score details for (int i = 0; i < 85; i++) System.out.print("-"); System.out.println("\n"); for (int i = 0; i < players.length; i++) System.out.print("\t" + players[i]); System.out.println("\n"); for (int i = 0; i < 85; i++) System.out.print("-"); System.out.println("\n"); // Print out the scores for (int i = 0; i < row; i++) { System.out.print(places[i] + "\t"); for (int j = 0; j < column; j++) System.out.print(scores[i][j] + "\t"); System.out.println("\n"); } // Find out the total scores for each player for (int j = 0; j < column; j++) for (int i = 0; i < row; i++) total[j] = total[j] + scores[i][j]; // Print out the total scores for (int i = 0; i < 85; i++) System.out.print("-"); System.out.println("\n"); System.out.print("Total " + "\t"); for (int j = 0; j < column; j++) System.out.print(total[j] + "\t"); System.out.println("\n"); for (int i = 0; i < 85; i++) System.out.print("-"); System.out.println("\n"); // Find out the average and print it out for (int j = 0; j < column; j++) average[j] = total[j] / row; 81 82 Programming in JAVA2 System.out.print("Avg "); for (int j = 0; j < column; j++) System.out.print(average[j] + "\t"); System.out.println("\n"); for (int i = 0; i < 85; i++) System.out.print("-"); System.out.println("\n"); //Find out the highest scorer maxscore = 0; maxplayer = " "; for (int i = 0; i < column; i++) if (total[i] > maxscore) { maxscore = total[i]; maxplayer = players[i]; } System.out.print("Highest scorer is " + maxplayer + ", who scored a total of " + maxscore + “ runs “); } } The above program gives the following output: -----------------------------------------------------------------------------------Sehwag Sachin Dravid ------------------------------------------------------------------------------------- Yuvaraj Ganguly Delhi 45 75 51 40 35 Mumbai 130 170 45 70 90 Kolkata 10 60 125 65 55 Chennai 75 55 65 40 120 215 300 53 75 ------------------------------------------------------------------------------------Total 260 360 286 ------------------------------------------------------------------------------------Avg 65 90 71 ------------------------------------------------------------------------------------Highest scorer is Sachin, who scored a total of 360 runs. Arrays 83 Problem 6.3w Check out whether the words given below are palindromes (words when arranged in reverse order give the same words). manmohan madam malayalam Program 6.3w /* ----------------------------------------------------------This program checks out whether the given words are palindromes or not. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Prob63 { public static void main(String args []) { char words [][] = {{'m','a','n','m','o','h', 'a', 'n' }, { 'm','a','l','a','y','a','l', 'a', 'm' }, { 'm', 'a', 'd', 'a', 'm' } }; int i, j, n, wordlen; int wordcount = words.length; int charcount; // Print out the given words System.out.println("The given words are: \n"); for (i = 0; i < wordcount; i++) System.out.print((new String(words[i])) + " "); System.out.println("\n"); // Testing the words to find plaindrome for (i = 0; i < wordcount; i++) word: { charcount = words[i].length; for (j = 0, n = charcount - 1; j < n; j++, n--) if (words[i][j] != words[i][n]) { System.out.println((new String(words[i])) + " : is NOT a palindrome\n"); break word; } 84 Programming in JAVA2 System.out.println((new String(words[i])) + ": a PALINDROME\n"); } is } } The above program gives the following output: The given words are: manmohan malayalam madam manmohan : is NOT a palindrome malayalam: is a PALINDROME madam: is a PALINDROME Problem 6.4w Write a program to transpose the given matrix: 5 10 12 3 25 7 8 9 12 6 13 35 11 4 7 10 Program 6.4w /*----------------------------------------------------------This program transposes the given matrix. somasundaramk@yahoo.com --------------------------------------------------------------*/ class Prob64 { public static void main(String args []) { int cmat [][] ={{ 5, 10, 12, 3 },{ 25, 7, 8, 9 }, { 12, 6, 13, 35 },{ 11, 4, 7, 10 } }; int row = cmat.length; int column = cmat[0].length; int trancmat [][] = new int[column][row]; int i, j; // Print the given matrix System.out.println("The given matrix\n"); Arrays 85 for (i = 0; i < row; i++) { for (j = 0; j < column; j++) { trancmat[j][i] = cmat[i][j]; System.out.print(" " + cmat[i][j]); } System.out.println(" \n"); } // The transpose of the matrix System.out.println("The transpose of the matrix\n"); for (i = 0; i < row; i++) { for (j = 0; j < column; j++) System.out.print(" " + trancmat[i][j]); System.out.println(" \n"); } } } The above program gives the following output: The given matrix 5 10 12 3 25 7 8 9 12 6 13 35 11 4 7 10 The transpose of the matrix 5 25 12 11 10 7 6 4 12 8 13 7 3 9 35 10 86 Programming in JAVA2 Exercise–6 I. Fill in the blanks 6.1 Array is a collection of _________ data. 6.2 In Java, array is treated as an ________ . 6.3 ________ operator is used to create an array. 6.4 Multi-dimensional arrays can have _____ columns(elements). 6.5 When an array is declared with initial values, the new operator is _______ . II. Write Java programs for the following: 6.6 Write a Java program to find the largest value from a set of given integers. 6.7 Write a Java program that finds the sum of each column of a 5 x 4 matrix of integer values. 6.8 Write a Java program that finds the largest element of each row of a matrix of double type values. 6.9 Write a Java program to find the determinant of the given matrix of 4 x 4 elements. * * * * * * Classes 93 Program 7.2 // This program illustrates the use of method in a class. // somasundaramk@yahoo.com class Rectangle { int lenth; //These two are instance variables int breadth; void assign(int x, int y) { // Method declaration lenth = x; breadth = y; } } class RectangleDemo { public static void main(String args []) { Rectangle rec = new Rectangle(); rec.assign(20, 15); System.out.println(“rec.lenth = “ + rec.lenth); System.out.println(“rec.breadth = “ + rec.breadth); } } The above program gives the following output: rec.lenth = 20 rec.breadth = 15 7.5 Constructors A constructor is used to assign initial values to an object when it is created. In many cases, initial values are needed for instance variables. In the previous section 7.4, we have seen that a method was used to initialize instance variables. Using constructors, instance variables can be assigned initial values automatically when an object is created. Constructors are special methods. The name of the constructor shall be the same as the name of the class itself. There can be any number of constructors in a class. The general form of declaring a constructor is: class classname { type instance variable; classname(parameter-list1) { body1; } classname(parameter-list2) { 94 Programming in JAVA2 body2; } type methodname(parameter-list3) { body; } } The following program 7.3 illustrates the use of constructor: Program 7.3 // This program shows how to define a constructor. // somasundaramk@yahoo.com class Rectangle { int lenth; int breadth; Rectangle(int x, int y) { // defining a constructor lenth = x; breadth = y; } } class Constructor { public static void main(String args []) { Rectangle rec = new Rectangle(20, 15); System.out.println(“rec.lenth = “ + rec.lenth); System.out.println(“rec.breadth = “ + rec.breadth); } } The above program gives the following output: rec.lenth = 20 rec.breadth = 15 7.6 Instance Variable Hiding In declaring methods and constructors, parameters are used as arguments. The name of parameters are generally different from that of the instance variables. However, Java allows parameters and instance variables to have the same name. In order to identify instance variables from formal parameters, the key word this is used. this refers to the current object. The following program 7.4 illustrates the use of this in a class: Classes 95 Program 7.4 // This program shows how to use the keyword this // in instance variable hiding. // somasundaramk@yahoo.com class Rectangle { int lenth; int breadth; Rectangle(int lenth, int breadth) { this.lenth = lenth; this.breadth = breadth; } } class ThisDemo { public static void main(String args []) { Rectangle rec = new Rectangle(20, 15); System.out.println(“rec.lenth = “ + rec.lenth); System.out.println(“rec.breadth = “ + rec.breadth); } } The above program gives the following output: rec.lenth = 20 rec.breadth = 15 Constructors with different parameter list is called constructor overloading. G Constructors are used to initialize the instance variable. The following program 7.5 is an example for constructor overloading. Program 7.5 // This program illustrates the constructor overloading. // somasundaramk@yahoo.com class Rectangle { int lenth; int breadth; Rectangle(int lenth, int breadth) { 96 Programming in JAVA2 this.lenth = lenth; this.breadth = breadth; } Rectangle() { lenth = 0; breadth = 0; } } class Constrload { public static void main(String args []) { Rectangle rec1 = new Rectangle(20, 15); Rectangle rec2 = new Rectangle(); System.out.println(“rec1.lenth = “ + rec1.lenth); System.out.println(“rec1.breadth = “ +rec1.breadth); System.out.println(“rec2.lenth = “ + rec2.lenth); System.out.println(“rec2.breadth =“+rec2.breadth); } } The above program gives the following output: rec1.lenth = 20 rec1.breadth = 15 rec2.lenth = 0 rec2.breadth = 0 7.7 this in a Constructor One constructor of a class can refer to another constructor of the same class through the keyword this. The following program 7.6 illustrates the use of this to refer another constructor of the same class: Program 7.6 // This program illustrates the use of this in constructor. // somasundaramk@yahoo.com class Rectangle { int lenth; int breadth; Rectangle(int lenth, int breadth) { this.lenth = lenth; this.breadth = breadth; Classes 97 } Rectangle(Rectangle obj) { this(obj.lenth, obj.breadth); // makes use of the // previous constructor } } class Constrthis { public static void main(String args []) { Rectangle rec1 = new Rectangle(20, 15); Rectangle rec2 = new Rectangle(rec1); System.out.println(“rec1.lenth = “ + rec1.lenth); System.out.println(“rec1.breadth = “ +rec1.breadth); System.out.println(“rec2.lenth = “ + rec2.lenth); System.out.println(“rec2.breadth =“+ rec2.breadth); } } The above program gives the following output: rec1.lenth = 20 rec1.breadth = 15 rec2.lenth = 20 rec2.breadth = 15 Having seen simple methods and constructors, we will now consider a method that does some computing and returns a value to the calling section. The following program 7.7 calculates the area of the rectangle through the Area method: Program 7.7 // This program illustrates the use of a method in a class. // somasundaramk@yahoo.com class Rectangle { double lenth, breadth; double Area(double l, double b) { lenth = l; breadth = b; return lenth * breadth; } } 98 Programming in JAVA2 class Rectarea1 { public static void main(String args []) { double rec_area; Rectangle rec = new Rectangle(); rec_area = rec.Area(7.5, 4.5); System.out.println(“Length = “ + rec.lenth); System.out.println(“Breadth = “ + rec.breadth); System.out.println(“Area of rectangle = “ + rec_area); } } The above program gives the following output: Length = 7.5 Breadth = 4.5 Area of rectangle = 33.75 The above program 7.7 can also be written in the following form (program 7.8): Program 7.8 // This program illustrates the use of a method in a class. // somasundaramk@yahoo.com class Rectangle { double lenth, breadth; Rectangle(double l, double b) { lenth = l; breadth = b; } double Area() { return lenth * breadth; } } class Rectarea2 { public static void main(String args []) { double rec_area; Rectangle rec = new Rectangle(7.5, 4.5); Classes 99 rec_area = rec.Area(); System.out.println(“Length = “ + rec.lenth); System.out.println(“Breadth = “ + rec.breadth); System.out.println(“Area of rectangle = “ + rec_area); } } The above program gives the following output: Length = 7.5 Breadth = 4.5 Area of rectangle = 33.75 The result for the above program 7.8 is the same as that we saw in the previous program 7.7. Now, we will add one more method in program 7.7 to calculate the circumference of the rectangle. The program 7.9 calculates area and circumference of a rectangle. Program 7.9 // This program illustrates the use of two methods in a class. // somasundaramk@yahoo.com class Rectangle { double lenth, breadth; Rectangle(double l, double b) { lenth = l; breadth = b; } double Area() { return lenth * breadth; } double Circum() { return 2 * (lenth + breadth); } } class Rectarea3 { public static void main(String args []) { double rec_area, rec_circum; Rectangle rec = new Rectangle(7.5, 4.5); 100 Programming in JAVA2 rec_area = rec.Area(); rec_circum = rec.Circum(); System.out.println(“Length = “ + rec.lenth); System.out.println(“Breadth = “ + rec.breadth); System.out.println(“Area of rectangle = “ + rec_area); System.out.println(“Circumference of rectangle = “ + rec_circum); } } The above program gives the following output: Length = 7.5 Breadth = 4.5 Area of rectangle = 33.75 Circumference of rectangle = 24.0 One can also print the required values within the method itself instead of calling the method to compute the required values and print them out. The following program 7.10 does that kind of job: Program 7.10 // This program illustrates the use of two methods in a class. // The printing of values is done in the method itself. // somasundaramk@yahoo.com class Rectangle { double lenth, breadth; Rectangle(double l, double b) { lenth = l; breadth = b; } void Area() { System.out.println(“Area of rectangle = “ + lenth * breadth); } void Circum() { System.out.println(“Circumference of rectangle = “ +2 * (lenth + breadth)); } } class Rectarea4 { public static void main(String args []) Classes 101 { Rectangle rec = new Rectangle(7.5, 4.5); System.out.println(“Length = “ + rec.lenth); System.out.println(“Breadth = “ + rec.breadth); rec.Area(); rec.Circum(); } } The above program gives the following output: Length = 7.5 Breadth = 4.5 Area of rectangle = 33.75 Circumference of rectangle = 24.0 7.8 Method Overloading A class can contain any number of methods. Methods can parameters as input for data manipulation. These parameters are called signature. Java permits many methods to have the same name, but different type signatures. This way of methods having the same name, but different type signature is known as method overloading. G take type with with Methods of a class with the same name but with different type signature are called overloading methods. Overloading methods exhibit the concept of polymorphism. The following program 7.11 illustrates the use of method overloading. The following program contains a class with two methods with the same name Area but with different type signature. When two parameters are given, one method finds the area of a rectangle and another one finds the area of a square when a single parameter is passed as its argument. Program 7.11 // This program illustrates method overloading. // somasundaramk@yahoo.com class Rectangle { double lenth, breadth; double Area(double l, double b) { lenth = l; breadth = b; return lenth * breadth; } 102 Programming in JAVA2 double Area(double a) { //overloading method lenth = a; breadth = a; return lenth * breadth; } } class Overload { public static void main(String args []) { double area; Rectangle rec = new Rectangle(); area = rec.Area(7.5, 4.5); System.out.println(“Area of rectangle = “ + area); area = rec.Area(8.5); System.out.println(“Area of square = “ + area); } } The above program gives the following output: Area of rectangle = 33.75 Area of square = 72.25 7.9 Passing Objects as Parameter to Methods We have seen that methods in a class can take parameters as inputs and process them. Objects can also be passed as parameters to the methods. The following program 7.12 contains methods that take object as a parameter: Program 7.12 // This program illustrates passing an object as a // parameter to a method. // somasundaramk@yahoo.com class Rectangle { double lenth, breadth; Rectangle(double l, double b) { lenth = l; breadth = b; } double Area(Rectangle r) { return r.lenth * r.breadth; } } class Objectparam Classes 103 { public static void main(String args []) { double area; Rectangle rec = new Rectangle(7.5, 4.5); area = rec.Area(rec); System.out.println(“Area of rectangle = “ + area); } } The above program gives the following output: Area of rectangle = 33.75 In the above program 7.12, we have seen that an object is passed as reference to access the values of the parameters. This method of passing parameters is known as passing by reference, as the object reference variable contains only reference to the object. When arguments are passed as values, it is known as passing by value. Passing of the parameters in the earlier programs was done through passing by value. After reading this chapter, you should have learned the following: Ü Classes define data and method. Ü Object is an instance of a class. Ü Constructors are methods used to initialize variables of an object. Ü Methods with same name but with different type signature are called overloading methods. Ü Overloading methods exhibit polymorphism property. In the next chapter, you will learn about inheritance. 104 Programming in JAVA2 Worked Out Problems–7 Problem 7.1w A hardware shop adds a certain tax on any sales made. It gives a certain percentage of cash discount in the total cost depending on the product. Write a Java program to calculate the total cost, discount and the net amount a customer has to pay for the following data: Cost 245 750 1500 Tax 8.5 12.0 9.5 Percentage of Discount 5.0 8.5 7.2 Program 7.1w /* ---------------------------------------------------------This program shows how to calculate the tax and discount for sales made in a shop. somasundaramk@yahoo.com ---------------------------------------------------------- */ class Sales { int cost, tax, total, discount, net; double tr, dc; Sales(int p, double txrate, double dis) { cost = p; tr = txrate; dc = dis; } int Tax() { tax = (int)(cost * tr / 100); return tax; } int Total() { total = cost + tax; return total; } int Discount() { discount = (int)(total * dc / 100); return discount; Classes 105 } int Net() { return (total - discount); } } class Prob71 { public static void main(String args []) { Sales s1 = new Sales(245, 8.5, 5.0); Sales s2 = new Sales(750, 12.0, 8.5); Sales s3 = new Sales(1500, 9.5, 7.2); for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); System.out.println("Sales \t Tax Rs.\t Total Rs.\t Discount Rs. \t Net Cost Rs."); for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); System.out.println( s1.cost + "\t" + s1.Tax() + "\t\t" + s1.Total() + "\t\t" + s1.Discount() + "\t\t" + s1.Net() + "\n"); System.out.println( s2.cost + "\t" + s2.Tax() + "\t\t" + s2.Total() + "\t\t" + s2.Discount() + "\t\t" + s2.Net() + "\n"); System.out.println( s3.cost + "\t" + s3.Tax() + "\t\t" + s3.Total() + "\t\t" + s3.Discount() + "\t\t" + s3.Net() + "\n"); for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: 106 Programming in JAVA2 ----------------------------------------------------------------------------------------------------------------------Sales Tax Rs. Total Rs. Discount Rs. Net Cost Rs. ----------------------------------------------------------------------------------------------------------------------245 20 265 13 252 750 90 840 71 769 1500 142 1642 118 1524 ----------------------------------------------------------------------------------------------------------------------Problem 7.2w Write a Java program for problem 5.1w using separate methods for Sin(x), Cos(x) and factorial calculation. Program 7.2w /* ---------------------------------------------------------This program calculates the sin(x) and cos(x) functions by computing the sin series and cos series functions. The results are compared with the results obtained by using Java Sin and cos. This is an illustration to show how to create the class and methods. somasundaramk@yahoo.com ---------------------------------------------------------- */ class Trigno { double x; int i, n = 5; long factn; Trigno(double x) { this.x = x; } long Factfun(int nmax) { long fact = 1; for (i = 2; i <= nmax; i++) fact *= i; return fact; } Classes 107 double Sinfun() { double six = x; for (int k = 1; k <= n; k++) { factn = Factfun(2 * k + 1); six = six + Math.pow(-1, k) * Math.pow(x, (2 * k + 1)) / factn; } return six; } double Cosfun() { double cox = 1; for (int k = 1; k <= n; k++) { factn = Factfun(2 * k); cox = cox + Math.pow(-1, k) * Math.pow(x, 2 * k) / factn; } return cox; } } class Prob72 { public static void main(String args []) { double x, sinx, cosx, jsx, jcx; Trigno trg; for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); System.out.println("x \t my sinx \t Java sinx \t my cosx \t Java cosx\n"); for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); for (x = 0; x < 1.6; ) { trg = new Trigno(x); sinx = trg.Sinfun(); cosx = trg.Cosfun(); // Reduce the fractional digits for display double sx = (int)(sinx * 1000); double cx = (int)(cosx * 1000); sinx = sx / 1000; 108 Programming in JAVA2 cosx = cx / 1000; jsx = (int)(Math.sin(x) * 1000); jcx = (int)(Math.cos(x) * 1000); jsx = jsx / 1000; jcx = jcx / 1000; System.out.println(x + "\t" + sinx + "\t\t" + jsx + "\t\t" + cosx + "\t\t" + jcx); x = x + 0.5; } for (int i = 0; i < 80; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -----------------------------------------------------------------------------------------------------------x my sinx Java sinx my cosx Java cosx ------------------------------------------------------------------------------------------------------------0.0 0.0 0.0 1.0 1.0 0.5 0.479 0.479 0.877 0.877 1.0 0.841 0.841 0.54 0.54 1.5 0.997 0.997 0.07 0.07 ------------------------------------------------------------------------------------------------------------- Problem 7.3w A bank, in one scheme, gives a simple interest of 9.5% per annum for deposits made in that bank. In another scheme, it gives a compound interest of 9.0% per annum. A customer wants to deposit a sum of Rs.25,000 for 5 years. Write a program to calculate the total amount a customer gets after 5 years so that the customer can choose a better scheme. Total amount for P, for N years, with an interest rate R, in simple interest = PNR / 100 + P in compound interest = P(1+r/100) N Program 7.3w /* ---------------------------------------------------------This program calculates the total amount a customer will get for a deposit of Rs. 25,000 rupees in simple interest and compound interest for 5 years in a bank. somasundaramk@yahoo.com --------------------------------------------------------- */ Classes 109 class Deposit { int principal, year; int simple, compound; Deposit(int prin, int yr) { principal = prin; year = yr; } int Simple(double rate) { simple = principal + (int)(principal * year * rate /100); return simple; } int Compound(double rate) { compound = (int)(principal * Math.pow((1 + rate / 100), year)); return compound; } } class Prob73 { public static void main(String args []) { Deposit depo = new Deposit(25000, 5); System.out.println("Amount deposited = Rs. " + depo.principal); System.out.println("Amount after " + depo.year + " years in simple interest is = Rs. " + depo.Simple(9.5)); System.out.println("Amount after " + depo.year + " years in compound interest is = Rs. " + depo.Compound(9.0)); } } The above program gives the following output: Amount deposited = Rs. 25,000 Amount after 5 years in simple interest is = Rs. 36,875 Amount after 5 years in compound interest is = Rs. 38,465 110 Programming in JAVA2 Exercise–7 I. Fill in the blanks 7.1. A _______ defines the data and the methods used to manipulate them. 7.2. A _______ is like the blueprint for a building. 7.3. An instance of a class is _________ . 7.4. The variable defined in a class is called _________ variable. 7.5. The _______ operator creates an object and returns a ______ to the object. 7.6. A variable that stores the object reference is called _______ . 7.7. When an object reference variable is printed, only the ________ is printed and not the content of the object. 7.8. The instance variable of a class can be accessed using the ______ operator. 7.9. A special type of method that is used to initialize an object is called _______ . 7.10. The name of the class and the name of the constructor must be the same. (True / False) 7.11. The key word this in a class can be used to refer to a _______ in the same class. 7.12. When one or more methods have the same name but with different parameters, then the methods are called _______ methods. 7.13. The type signature of a method refers to the ________ passed to the method. II. Write Java programs for the following problems: 7.14. A mark list contains a register number, name and marks for sub1, sub2 and sub3. Write a Java class to define them. 7.15. Add a method to the class defined in problem 7.14 to find the average of the three subjects and print out the average value. 7.16. Write a constructor to initialize all the variables of the class defined in problem 7.14. 7.17. The employee list for a company contains employee code, name, designation and basic pay. The employee is given a house rent Classes 111 allowance (HRA) of 10% of the basic pay and dearness allowance (DA) of 45% of the basic pay. The total pay of the employee is calculated as Basic Pay + HRA + DA. details of the employee. Write a class to define the Write a constructor to assign the required initial values. Add a method to calculate HRA, DA and total pay and print them. Write another class with a main method. Create objects for three different employees and calculate the HRA, DA and total pay. 7.18. A mark list contains reg.no. and marks for three subjects, sub1, sub2 and sub3. Write a class to define the mark list. to initialize all the variables. Write a constructor Write a method called Result (int min) where, min indicates the minimum mark for a “Pass” for each subject. This method will declare a candidate as “Pass”, if the candidate secures marks in each subject greater than or equal to min. Write another overloading method Result (int min, int merit), where merit indicates that a candidate who get a “Pass” and average of the three subjects equal to or greater than merit is eligible for getting a scholarship. Write another class with a main method and try the methods for 5 different candidates to determine whether they get “Pass” and also determine whether they are eligible for scholarship. * * * * * * 112 Programming in JAVA2 BLANK Inheritance 119 appropriate method is selected depending upon the situation. Thus, method overriding exhibits polymorphism. Java does this during run time and is called dynamic method dispatch. Java supports multi-level inheritance as given below: Class A Class B Extends A Class C Extends B Fig.8.1 Multi-Level Inheritance in Java Using this principle, subclasses in multilevel can be created. G A method in a subclass having the same name and type signature of a superclass method is called overriding method. Overriding method exhibits polymorphism property. 8.3 Final Class Inheritance allows creation of subclasses. However, if need arises, inheritance can be prevented by declaring a class as final. A class declared as final cannot have subclasses. The following program 8.5 shows the use of final class: Program 8.5 // Program to demonstrate final class final class FinCircle { // this prevents creation of any subclass of double radius; Circle 120 Programming in JAVA2 final double PHI = 22.0 / 7; FinCircle(double r) { radius = r; } double Area() { return PHI * radius * radius; } double Circum() { return 2 * PHI * radius; } } class FinalClass { public static void main(String args []) { double ar, sar; FinCircle cir = new FinCircle(3.5); ar = cir.Area(); sar = cir.Circum(); System.out.println(“\n Area of the circle of radius “ + cir.radius + “ = “ + ar); System.out.println(“\n Circumference of the circle of radius “ + cir.radius + “ = “ + sar); } } The above program gives the following output: Area of the circle of radius 3.5 Circumference of the circle of radius 3.5 8.4 = 38.5 = 22.0 Final Method Methods in a class can be protected from overriding methods in subclasses. Like final classes, methods can be declared with the modifier final. Methods declared as final cannot have overriding methods in the subclasses. The following program 8.6 illustrates the use of final method: Program 8.6 // This program illustrates the final method. class Circle { double radius; final double PHI = 22.0 / 7; Circle(double r) Inheritance 121 { radius = r; } final double Area() { // protected from overriding by a subclass method return PHI * radius * radius; } double Circum() { return 2 * PHI * radius; } } class Cylinder extends Circle { double height; Cylinder(double r, double h) { super(r); height = h; } double Surface() { return Circum() * height; } double Volume() { return PHI * radius * radius * height; } } class FinalMethod { public static void main(String args []) { double area, section_area, surface_area, volume; Circle cir = new Circle(5.5); Cylinder cyl = new Cylinder(3.2, 12.5); area = cir.Area(); System.out.println(“\n Area of the circle of radius “ + cir.radius + “ = “ + area); System.out.println(“\n Calculations for the cylinder of radius “ + cyl.radius + “ and height “ + cyl.height); section_area = cyl.Area(); surface_area = cyl.Surface(); volume = cyl.Volume(); System.out.println(“\n Cross-sectional area = “ + section_area); 122 Programming in JAVA2 System.out.println(“\n Surface area = “ + surface_area); System.out.println(“\n Volume = “ + volume); } } The above program gives the following output: Area of the circle of radius 5.5 = 95.07142857142857 Calculations for the cylinder of radius 3.2 and height 12.5 Cross-sectional area = 32.182857142857145 Surface area = 251.42857142857142 Volume = 402.28571428571433 So far, all the programs have been written by writing all the classes in the same file. It is not required so. If a class is needed in several programs, it is required to write the class, compile and store in the same directory. That class can be used in any number of classes without actually writing it in the respective programs. In the above program, you store the class FinCircle in a file FinCircle.java. The remaining part can be stored in FinalMethod.java. Compile FinCircle.java first, which generates FinCircle.class. Then compile FinalMethod.java and then execute FinalMethod. 8.5 Final Variables Variables can also be declared as final. final variables are constants. You cannot assign any new value to them once you have declared them as final. final variables must be assigned values while declaring them to be final. The general form of declaring a final variable is: final type VariableName = Value; By convention, final variables Following are a few examples for final: are final int PASS_MARK = 40; final int MINUTE_VAL = 60; declared with uppercase letters. final double INTEREST_RATE = 12.5; 8.6 final double UPPER_LIMIT = 120.25; final double PHI = 3.142; Object Destruction and Garbage Collection When objects are created, they occupy some memory space of the computer. When an object is no more in use, Java identifies them automatically Inheritance 123 and frees the memory. This is called garbage collection. There is no separate destructor method in Java. In certain situations, objects may use other than memory, like a file or a system resource. In such cases, care must be taken to free those resources before the object is destroyed. In order to provide such a facility, Java has finalize() method. This method can be put inside the class. Before an object is destroyed, Java runs the finalize() method. The user can define whatever action to be taken inside the finalize() method. Though, in most cases, it works, but that is not guaranteed for every time. Therefore, a programmer has to find other means to release the resources from objects marked for destruction. 8.7 Recursion When a method calls itself, it is called recursion. There are problems which can be programmed easily using recursion. Java supports recursive method. Consider the problem of computing the factorial of a given number. The formula for finding factorial is given by : n! = 1x2x3....n The above formula can be written as: n! = n * (n-1)! = n * (n-1)*(n-2)! = n * (n-1)*(n-2)*(n-3)! etc. and finally 0! = 1! = 1. The following program 8.7 implements the above formula using the recursive method: Program 8.7 // This program illustrates the use of recursive method. class Factfun { long Fact(int n) { if (n == 0 || n == 1) return 1; else return n * Fact(n - 1); } } class FindFact { public static void main(String args []) { Factfun f = new Factfun(); 124 Programming in JAVA2 System.out.println(“\n Factorial of 5 = “ + f.Fact(5)); System.out.println(“\n Factorial of 10= “ + f.Fact(10)); } } The above program gives the following output: Factorial of 5 = 120 Factorial of 10 = 3628800 8.8 Static Methods, Block and Variables 8.8.1 Static method We have so far seen that methods are called on the objects. That is, methods are called in relation to an instance of a class. Java provides a mechanism, in which methods can be called without an instance of a class. Such methods are called static methods. Static methods are declared by using the modifier static. For example, the main() is a static method as it has to function independent of any object. Static methods can be called directly, if the method is within the same class or can be called by specifying its class name along with the method name if it is in a different class. The general form calling a static method is : classname.static_method; A static method cannot access any instance variable of that class. It cannot make use of this or super inside the method. It can only access static methods and static variables. The following program 8.8 illustrates the use of a static method within the same class: Program 8.8 // This program illustrates the use of a static method within // the same class. class StaticDemo1 { static void Add(int a, int b) { int sum = a + b; System.out.println(“Sum of numbers =” + sum); } Inheritance 125 public static void main(String args []) { Add(5, 24); } } The output of the above program is: Sum of numbers = 29 The following program 8.9. illustrates the use of a static method from a different class: Program 8.9 // This program illustrates the use of a static // method from a different class. // somasundaramk@yahoo.com class StatClass { static void Add( int a, int b ) { int sum =a+b; System.out.println(“Sum of numbers =”+ sum); } } class StaticDemo2 { public static void main(String args[]) { StatClass.Add(5,24); } } The above program gives the same result as that of the previous program. 8.8. G A static method can be called directly. 8.8.2 Static Variables Instance variables of Java can also be declared as static. When a variable is declared as static, it becomes a class variable rather than an object variable. Static variables can be accessed by any part of the program. Even if an instance is created, the static variables retain the last modified value. In effect it becomes a global variable. 126 Programming in JAVA2 For example, consider the following program 8.10: Program 8.10 // This program illustrates the use of static variables. class Statvar { int i = 0, j = 0; void Printval() { System.out.println(“\n i =” + i); System.out.println(“\n j =” + j); } } class StatvarDemo { public static void main(String args []) { Statvar sv = new Statvar(); System.out.println(“\n Value of variables in the first object”); sv.Printval(); sv.i = 10; sv.j = 15; System.out.println(“\n Value of variables in the second object”); Statvar sv1 = new Statvar(); sv1.Printval(); } } The above program gives the following output: Value of variables in the first object i =0 j =0 Value of variables in the second object i =0 j =0 In the above program 8.10, if we declare the instance variables i and j as: static int=0, j=0; in the class Statvar, you will get the following result: Value of variables in the first object Inheritance 127 i=0 j=0 Value of variables in the second object i = 10 j = 15 You will observe from the above result, that when the variables i and j are declared as static, they retain the value set in the first object and, hence, when the second object is created, i and j retain the last modified value. G A static variable is a class variable. Any object of the class in which the static variable is defined can modify the value of a static variable. Such modification will be reflected in all the objects. 8.8.3 Static Block In certain cases, it may be needed to execute a set of statements in a class only once and independent of the instance. In Java, such statements can be placed in a block and declared as static. Such blocks are called static blocks. When a class is loaded, the block is executed. In the subsequent instances, the static blocks are not executed. With this feature, it is possible to execute a set of instructions in the static block even in the absence of a main method. The following program 8.11 illustrates the static block. Program 8.11 // This program illustrates the use of static block. class Statblock { void Printmsg() { System.out.println(“\n Printed inside Printmsg() method”); } static { System.out.println(“\n Printed inside static block”); } } class StatblockDemo { public static void main(String args []) 128 Programming in JAVA2 { Statblock sb = new Statblock(); System.out.println(“\n First object”); sb.Printmsg(); Statblock sb1 = new Statblock(); System.out.println(“\n Second object”); sb1.Printmsg(); } } The above program gives the following output: Printed inside static block First object Printed inside Printmsg() method Second object Printed inside Printmsg() method 8.9 Abstract Classes In the inheritance hierarchy, we have seen, while going down, one encounters subclasses which have definite instance variables and methods. Similarly, when we go up in the hierarchy, common properties of classes can be abstracted and defined in a single class. This helps to deal a complex problem in one class. For example, consider geometrical shapes, circle, rectangle and parallelogram. All of them have certain common properties like area and circumference. The common properties can abstracted and brought under a common class, Shape, with methods for calculating the area and circumference. But these methods cannot have a concrete body as the formulae for calculating area and circumference are different. Shape Circle Fig.8.2 Rectangle Triangle Abstraction of Commonalities of Several Classes to Common Class Inheritance 129 Therefore, methods are defined without a concrete body. Java allows defining of methods without body and such methods are called abstract methods. Abstract methods are defined with a key word abstract. A class containing at least one abstract method is called as an abstract class. Since abstract classes do not have concrete methods, objects for abstract classes cannot be created. However, object reference variables of abstract classes can be created. Further, when an abstract class is defined, a subclass of the abstract class must give a concrete method. Otherwise, the subclass also becomes an abstract class. The following program 8.12 has an abstract class and an abstract method: Program 8.12 // Program to illustrate abstract class and abstract method abstract class Shape { double area; final double PHI = 22.0 / 7.0; abstract double Area(); // abstract method } class Rectangle extends Shape { double lenth, breadth; Rectangle(double x, double y) { lenth = x; breadth = y; } double Area() { area = lenth * breadth; return area; } } class Circle extends Shape { double radius; Circle(double r) { radius = r; } double Area() { area = PHI * radius * radius; return area; } 130 Programming in JAVA2 } class AbstractDemo { public static void main(String args []) { Rectangle rec = new Rectangle(6.0, 4.0); double ar; ar = rec.Area(); System.out.println(“\n Area of the rectangle = “ + ar); Circle cr = new Circle(5.25); ar = cr.Area(); System.out.println(“\n Area of the circle = “ + ar); } } The above program gives the following output: Area of the rectangle = 24.0 Area of the circle = 86.625 G A method without a body is called as an abstract method. A class containing an abstract method is called as an abstract class. After reading this chapter, you should have learned the following: Ü A subclass inherits all the properties of the superclass. Ü Methods having the same name and type signature are called overriding methods. Ü A final class cannot be subclassed. Ü Static methods can be called without objects. Ü Classes having abstract methods are called as abstract classes. In the next chapter, you will learn about packages and interfaces. Inheritance 131 Worked Out Problems–8 Problem 8.1w Write a class to find the mean value of a set of given numbers using the formula: x = Sx n Extend this class to compute the standard deviation using the following formula: S.D= S( x – x) 2 n use the folloiwng data: x=14, 22, 9, 15, 20, 17, 12, 11 Problem 8.1w /* ----------------------------------------------------------This program calulates the arithmetic mean in the superclass and the standard deviation in the subclass. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Arithmetic { double num []; int araylen; Arithmetic(double a []) { araylen = a.length; num = new double[araylen]; for (int i = 0; i < araylen; i++) num[i] = a[i]; } double Mean() { double sum = 0; for (int i = 0; i < araylen; i++) sum += num[i]; double mean = sum / araylen; return mean; } } 132 Programming in JAVA2 class Stdd extends Arithmetic { double dif []; Arithmetic arith; int araylen; double xmean; Stdd(double x []) { super(x); araylen = x.length; dif = new double[araylen]; xmean = super.Mean(); for (int i = 0; i < araylen; i++) { dif[i] = (x[i] - xmean); dif[i] = dif[i] * dif[i]; } } double Std() { arith = new Arithmetic(dif); double std = Math.sqrt(arith.Mean()); return std; } } class Prob81 { public static void main(String args []) { double x [] = { 14,22, 9, 15,20,17,12,11 }; //print out the given numbers System.out.println("The given numbers are: \n"); for (int i = 0; i < x.length; i++) System.out.print(x[i] + " "); System.out.println(" \n "); Stdd sd = new Stdd(x); double xm = sd.Mean(); double sdev = sd.Std(); // reduce the no of decimap digits sdev = (int)(sdev * 100); sdev = sdev / 100; xm = (int)(xm * 100); Inheritance 133 xm = xm / 100; System.out.println("Mean of the numbers = " + xm); System.out.println("\nStandard deviation = " + sdev); } } The above program gives the following output: The given numbers are: 14.0 22.0 9.0 15.0 20.0 17.0 12.0 11.0 Mean of the numbers = 15.0 Standard deviation = 4.18 Problem 8.2w A bank gives a simple interest of 9.25% per annum for deposits made in the bank. It also gives a compound interest of 8.5% per annum for deposits. A customer would like to choose any one of the scheme depending on his requirement. A customer would like to deposit Rs.25,000 for 5 years. Write a program to implement this using abstract class. Program 8.2w /* ----------------------------------------------------------This program calulates the simple interst and compound interest using abstarct class. somasundaramk@yahoo.com ------------------------------------------------------------- */ abstract class Deposit { double principal; int year; abstract double Interest(int p, double rate, int yr); } class Simple extends Deposit { double Interest(int p, double rate, int year) { principal = p; this.year = year; double total = p * (1 + year * rate / 100); 134 Programming in JAVA2 return total; } } class Compound extends Deposit { double Interest(int p, double rate, int year) { principal = p; this.year = year; double total = p * Math.pow((1 + rate / 100), year); return total; } } class Prob82 { public static void main(String args []) { Deposit d1 = new Simple(); Deposit d2 = new Compound(); double sim = d1.Interest(25000, 9.25, 5); double com = d2.Interest(25000, 8.5, 5); // reduce the no of decimal digits sim = (int)(sim * 100); com = (int)(com * 100); sim = sim / 100; com = com / 100; System.out.println( "Total after " + d1.year + " years for Rs. " + d1.principal + " in simple interest is = Rs. " + sim); System.out.println("\nTotal after " + d2.year + " years for Rs. " + d2.principal + " in compound interest is = Rs. " + com); } } The above program gives the following output: Total after 5 years for Rs. 25,000.0 in simple interest is = Rs. 36,562.5 Total after 5 years for Rs. 25000.0 in compound interest is = Rs. 37,591.41 Inheritance 135 Exercise–8 I. Fill in the blanks: 8.1. To create a subclass, the keyword __________ is used. 8.2. To refer to a superclass constructor, the keyword _______ is used. 8.3. A subclass can be created which inherits only a few methods of the superclass. (True/False) 8.4. Methods having the same name and different type signature are called ______ methods. 8.5. Methods having the same name and same type signature are called ______ methods. 8.6. Polymorphism property is implemented through _________ and ________ . 8.7. To prevent inheritance of a class, it should be declared as _________ . 8.8. A method declared as ________ cannot have overriding method. 8.9. _________ method can be called without the instance of a class. 8.10. _________ variable is called a class variable. 8.11. A block statement that is to be initialized only once at the time of loading the class is to be declared as _________ . 8.12. A method without the body is called __________ method. 8.13. A class having an abstract method is to be declared as _______ . II. Write Java programs for the following: 8.14. Write a class with a method to find the area of a rectangle. Create a subclass to find the volume of a rectangular shaped box. 8.15. Write a class called square with a method Area (double a) that finds the area (a 2) of the square. Create a class Cube which is a subclass of Square and write an overriding method Area(double a) that finds the surface area (6a 2 ) of the cube. 8.16. Write a class with a static method that returns the maximum value of three given integers. Write another class with main method and call the static method to print the maximum values for two sets of integer values (say {5, 2, 10}, {75, 20, 89}). 136 8.17. Programming in JAVA2 Write an abstract class with an abstract method void Special (int n). Create a subclass of this class and implement the Special method that finds the numbers that are perfect squares from 1 up to n. 8.18. Write an abstract class Special with an abstract method double Process (double P, double R). Create a subclass Discount and implement the Process() method with the following formula: net = P – P* R/100 Return the net value. Create another subclass Tax for Special and implement the Process() method with the following formula: total = P + P * R/100 Return the total. * * * * * * Packages and Interfaces 143 // private x = “ + a.x_pri); System.out.println(“\n protected x = “ + a.x_pro); System.out.println(“\n public x = “ + a.x_pub); } } class AccessDemo { public static void main(String args []) { A a = new A(); B b = new B(); C c = new C(); System.out.println(“\nPrinting in the same package”); a.PrintA(); b.PrintB(); c.PrintC(); } } Go to a directory one above the jbook1 and compile the AccessDemo.java. (Trying to compile AccessDemo.java in the same directory jbook1 will give error). Then execute the program by issuing the command: java jbook1.AccessDemo You will get the following output: Printing in the same package Printing in class A x = 25 private x = 35 protected x = 45 public x = 55 Printing in subclass B x = 25 protected x = 45 public x = 55 Printing in non-subclass C x = 25 protected x = 45 public x = 55 Now create another package soms. Create the following program 9.4 PackageDemo.java. Please note that the class A in package jbook1 is declared as public. Otherwise you cannot access it in another package. 144 Programming in JAVA2 Program 9.4 // Program to illustrate the use of package package soms; import jbook1.*; class D extends A { void PrintD() { System.out.println(“\n Printing in subclass D in another package”); // System.out.println(“ x = “ + x); // System.out.println(“ private x = “ + x_pri); System.out.println(“\n protected x = “ + x_pro); System.out.println(“\n public x = “ + x_pub); } } class E { void PrintE() { A a = new A(); System.out.println(“\n Printing in different package,non-subclass E”); System.out.println(“\n Public x = “ + a.x_pub); } } class PackageDemo { public static void main(String args []) { A a = new A(); //B b= new B(); //C c= new C(); D d = new D(); E e = new E(); System.out.println(“\n Printing in different pack age”); // a.PrintA(); //b.PrintB(); //c.PrintC(); d.PrintD(); e.PrintE(); } } The above program gives the following result: Printing in different package Packages and Interfaces 145 Printing in subclass D in another package protected x = 45 public x = 55 Printing in different package,non-subclass E Public x = 55 You can assign different modifiers to the variables and methods in the classes and see the effect of access modifiers. The access modifier for a class is either public or no modifier. 9.4 Interfaces Defining Interfaces Interfaces are similar to abstract classes, but differ in their functionality. Interfaces define methods without body. Interfaces cannot have instance variables. But, it can contain final variables, which must be initialized with values. The methods can have type signature. The interfaces help to implement multiple inheritance in Java. The general form of defining an interface is : modifier interface ifname { final type var1 = val1; final type var2 = val2; modifier return_type mname1(type signature1) ; modifier return_type mname2(type signature2); } Here, the modifier can be either public or no modifier. var1, var2 are final variables and val1 and val2 are values. ifname is the name of the interface, mname1 and mname2 are method names. When the interface is declared as public any other class can make use of it. The following is an example for interface declaration: // illustration for interface interface Calculation{ final double pi= 3.142; double Area( double r); } Implementing an Interface Once an interface is defined, another class should implement all the methods of the interface. An interface can be implemented in any number of classes. A class can implement any number of interfaces. The general form of implementing an interface is: modifier class classname [extends superclass] implements 146 Programming in JAVA2 interface1, interface2 . . . interfaceN { body; } Here the modifier is either public or no modifier. Java does not support multiple inheritance like in C++. supports only multilevel inheritance. Class A Class A Class A Java Class A Class B Extends A Class C Extends B Class D Extends A, B, C Multilevel Inheritance Multiple Inheritance Fig.9.3 Multiple Inheritance and Multilevel Inheritance interface1 interface2 interface3 Class Multi implements interface1, interface2, interface3 Fig.9.4 Interfaces in Java Help to Realize the Functionality of Multiple Inheritance. Packages and Interfaces G 147 A class can implement more than one interface, exhibiting multiple inheritance. The functionality of multiple inheritance in Java is realized through the interfaces, in which a class can implement any number of interfaces. In the implementing class, concrete methods are to be given for the abstract methods defined in the interface. The type signature of the overriding methods in the class must match the type signature of the interface methods. The concrete methods are to be declared as public. If concrete methods are not given in the implementing class, that class must be declared as abstract. A class implementing an interface can also have additional methods of its own. The following is an example for implementing an interface Calculation: class Circle implements Calculation { public double Area (double x) { double ar; ar = pi*x*x; // area of circle. return ar; } } G When an interface method is implemented in a class, it must be declared as public. Another class can implement the same interface Calculation in a different form, but with the same type signature. The following class shows how the interface is implemented in a different class: // Program to illustrate interface implementation class Sphere implements Calculation{ public double Area(double x){ double surface_area =4.0*pi*x*x; return surface_area; } } An interface can be extended to create another interface. For example, the following interface extends the previous interface Calculation: 148 Programming in JAVA2 interface Average extends Calculation { void Mean (double[] d); } Now, any class that implements the Average must implement both the methods Area and Mean. The following program 9.5 illustrates the use of interface: Program 9.5 // Program to illustrate the use of interface // Calculates the simple interest and compound interest interface Deposit { void Interest(double principal, int year, double rate); } class Simple implements Deposit { public void Interest(double p, int n, double r) { double intr, total; intr = p * n * r / 100.0; total = p + intr; System.out.println(“\nPrincipal amount = Rs “ + p); System.out.println(“No of years = “ + n); System.out.println(“Interest rate r = “ + r); System.out.println(“Interest amount = Rs “ + intr); System.out.println(“Total amount after “ + n + “years in simple interest = Rs “ + total); } } class Compound implements Deposit { public void Interest(double p, int n, double r) { double intr, total; total = p * Math.pow(1 + r / 100.0, n);// pow(x,y) //finds the value of x to the power y intr = total - p; System.out.println(“\nPrincipal amount = Rs “ + p); System.out.println(“No of years = “ + n); System.out.println(“Interest rate r = “ + r); System.out.println(“Interest amount = Rs “ + intr); System.out.println(“Total amount after “ + n + “ years in compound interest = Rs “ + total); Packages and Interfaces 149 } } class InterestCal { public static void main(String args []) { Simple sim = new Simple(); Compound com = new Compound(); sim.Interest(12500.0, 4, 12.5); com.Interest(12500.0, 4, 12.5); } } The above program gives the following result: Principal amount = Rs 12500.0 No of years = 4 Interest rate r = 12.5 Interest amount = Rs 6250.0 Total amount after 4 years in simple interest = Rs 18750.0 Principal amount = Rs 12500.0 No of years = 4 Interest rate r = 12.5 Interest amount = Rs 7522.5830078125 Total amount after 4 years in compound interest = Rs 20022.5830078125 After reading this chapter, you should have learned the following: Ü Package statement indicates the location of a file in a directory. Ü To refer and access classes in a package, the import statement is used. Ü Access modifier realizes the data encapsulation property. Ü Access modifiers give protection to data and methods in varying degrees. Ü Interfaces allow predefined conceptual methods to be implemented in many different ways. Ü Through interfaces, multiple interitance can be realized. In the next chapter, you will learn about wrapper classes. 150 Programming in JAVA2 Worked Out Problems–9 Problem 9.1w Write an interface called Hyperbolic with a method to find either Cosh or Sinh. Implement this interface to calculate Sinh(x) and Cosh(x) given by: 10 Sinh(x) = x + S n=1 10 Cosh(x) = 1 + S n=1 x 2n+1 (2n+1)! x 2n 2n! for x=0.5 to 5.5 in steps of 0.5. Program 9.1w /* ----------------------------------------------------------This program calculates the hyperbolic sine and cosine functions using interface. somasundaramk@yahoo.com --------------------------------------------------------------*/ interface Hyper { final int n = 10; double Hypfun(double x); } class Hysin implements Hyper { double sinh; long factn; int i; long Factfun(int nmax) { long fact = 1; for (i = 2; i <= nmax; i++) fact *= i; return fact; } public double Hypfun(double x) Packages and Interfaces { sinh = x; for (int k = 1; k <= n; k++) { factn = Factfun(2 * k + 1); sinh = sinh + Math.pow(x, (2 * k + 1)) / factn; } return sinh; } } class Hycos implements Hyper { double cosh; long factn; int i; long Factfun(int nmax) { long fact = 1; for (i = 2; i <= nmax; i++) fact *= i; return fact; } public double Hypfun(double x) { cosh = 1; for (int k = 1; k <= n; k++) { factn = Factfun(2 * k); cosh = cosh + Math.pow(x, (2 * k)) / factn; } return cosh; } } class Prob91 { public static void main(String args []) { double x, sinh, cosh, jsh, jch; Hyper hcos; Hyper hsin; int pn = 50; for (int i = 0; i < pn; i++) 151 152 Programming in JAVA2 System.out.print("-"); System.out.println("\n"); System.out.println("x \t sinh \t cosh \t \n"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); for (x = 0; x < 5.1; ) { hsin = new Hysin(); hcos = new Hycos(); sinh = hsin.Hypfun(x); cosh = hcos.Hypfun(x); // Reduce the fractional digits for display double sx = (int)(sinh * 1000); double cx = (int)(cosh * 1000); sinh = sx / 1000; cosh = cx / 1000; System.out.println(x + "\t" + sinh +"\t" + cosh); x = x + 0.5; } for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------x sinh cosh -------------------------------------------------0.0 0.0 1.0 0.5 0.521 1.127 1.0 1.175 1.543 1.5 2.129 2.352 2.0 3.626 3.762 2.5 6.05 6.132 3.0 10.017 10.067 3.5 16.542 16.572 4.0 27.289 27.308 4.5 45.002 45.014 5.0 74.203 74.209 -------------------------------------------------- Packages and Interfaces 153 Exercise–9 I. Fill in the blanks 9.1. Package statement indicates the directory in which the _____ is stored. 9.2. Package statement helps to create many classes to have ____ name. 9.3. To make use of a class defined in a package in another class, the ___ statement is to be used. 9.4. The concept of data encapsulation is realized through _____ . 9.5. If a variable is to be visible to the subclass in any package and to all classes in the same package, it must be declared as ______ . 9.6. The first statement of a Java program is _____, if used. 9.7. In a Java program, import statement must appear immediately after _______ statement. 9.8. The default package that is implicitly called in a Java program is _______ . 9.9. _______ help to realize the concept multiple inheritance in Java language. 9.10. Interface has methods _________ body. 9.11. ______ variable can be used in an interface. 9.12. To make use of an interface, it must be ________ in another class. 9.13. A class can implement _____ number of interfaces. 9.14. If a class does not implement all methods in an interface, that class must be declared as _______ . II. Write Java programs for the following: 9.15. Write a Java class called Sumn that finds the sum of all numbers from 1 up to the given number n. This class is in the directory with path c:\java\pac. Write a package statement inside the class Sumn. 9.16. Write an interface called Numbers, with a method int Process (int x, int y). Write a class called Sum, in which the method Process finds the sum of two numbers and returns an int value. class Write another called Average, in which the Process method finds the average of the two numbers and returns an int. 154 9.17. Programming in JAVA2 Write an interface called Exam with a method Pass (int mark) that returns a boolean. Write another interface called Classify with a method Division (int average) which returns a string. Write a Class called Result which implements both Exam and Classify. The Pass method should return true if the mark is greater than or equal to 50 else false. The Division method must return “FIRST” when the parameter average is 60 or more, “SECOND” when average is 50 or more but below 60, “NO DIVISION” when average is less than 50. * * * * * * Wrapper Classes 161 Table 10.4 Additional Methods Defined in Integer Class Method Purpose of the Method 1. static Integer valueOf(String s) Returns an Integer object of the String s representing an int 2. static Integer valueOf(String s, int radix) Returns an Integer object for the value specified by String s using the radix 3. int compareTo(Integer i) Compares the numerical value of the invoking object with i; returns 0, if both are equal, negative if i>object and positive if i<object 4. boolean equals(Integer i) Returns true if the invoking object is equal to i, otherwise false 5. static int parseInt(String s) Returns the int equivalent of the number contained in the String s using radix 10 6. static int parseInt(String s, int radix) Returns the int equivalent of the number contained in the String s using radix 7. static String toString(int n ) Returns a String that contains the decimal equivalent of n 8. static String toString(int n, int radix) Returns a String that contains the decimal equivalent of n using the radix 9. static String toBinaryString(int n) Returns a String that contains the binary equivalent of n 10. static String toOctalString(int n) Returns a String that contains octal equivalent of n 11. static String toHexString(int n) Returns a String that contains the hexadecimal equivalent of n Use of some methods defined in Integer class is given in program 10.3. Program 10.3 //This program illustrates some of the methods in //Integer class. class IntegerDemo { public static void main(String args []) { 162 Programming in JAVA2 Integer i1 = new Integer(87456); Integer i2 = new Integer(“681523”); System.out.println(“\n i1 object = “ + i1); System.out.println(“\n 2*i1 value = “ + 2 * i1.intValue()); System.out.println(“\n i2 object = “ + i2); System.out.println(“\n 2*i2 value = “ + 2 * i2.intValue()); System.out.println(“\n is (i1 == i2)?: “ + i1.equals(i2)); System.out.println(“\n i1.compareTo(i2) : “ + i1.compareTo(i2)); Integer i3 = Integer.valueOf(“fa26”, 16); System.out.println(“\n Decimal equivalent of hex fa26= “ + i3); System.out.println(“\n byte value of Integer object i3 = “ + i3.byteValue()); System.out.println(“\n int value of Integer object i3 = “ + i3.intValue()); System.out.println(“\n double value of Integer object i3 = “ + i3.doubleValue()); int i4 = Integer.parseInt(“85671”); System.out.println(“\n Integer value of i4 = “ + i4); int inum = 97234; System.out.println(“\n binary equivalent of decimal“ + inum + “ = “ + Integer.toBinaryString(inum)); System.out.println(“\n hexadecimal equivalent decimal “ + inum + “ = “ + Integer.toHexString(inum)); System.out.println(“\n Minimum value of Integer = “ + Integer.MIN_VALUE); System.out.println(“\n Maximum value of Integer = “ + Integer.MAX_VALUE); } } The above program gives the following output: i1 object = 87456 2*i1 value = 174912 i2 object = 681523 2*i2 value = 1363046 is (i1 == i2)?: false i1.compareTo(i2) : -1 Decimal equivalent of hex fa26= 64038 byte value of Integer object i3 = 38 int value of Integer object i3 = 64038 Wrapper Classes 163 double value of Integer object i3 = 64038.0 Integer value of i4 = 85671 binary equivalent of decimal 97234 = 10111101111010010 hexadecimal equivalent decimal 97234 = 17bd2 Minimum value of Integer = -2147483648 Maximum value of Integer = 2147483647 10.1.4 Long Class The Long class is used to wrap long type. class are : i) Long (long n) ii) Long (String s) The constructors for Long where n is a long type and s is a String that represents a long type. Apart from the methods given in table 10.1, additional methods defined in Long are given in table 10.5. Table 10.5 Additional Methods Defined in Long Class Method Purpose of the Method 1. static Long valueOf(String s) Returns a Long object of the String s 2. static Long valueOf(String s, int radix) Returns a Long object for the value specified by String s using the radix 3. int compareTo(Long L) Compares the numerical value of the invoking object with L; returns 0, if both are equal, negative if L>object and positive if L<object 4. boolean equals(Long L) Returns true if the invoking object is equal to L, otherwise false 5. static long parseLong(String s) Returns the long equivalent of the number contained in the String s using radix 10 6. static long parseLong(String s, int radix) Returns the long equivalent of the number contained in the String s using radix 7. static String toString(long n ) Returns a String that contains the decimal equivalent of n 8. static String toString(long n, int radix) Returns a String that contains the decimal equivalent of n using the radix 164 9. Programming in JAVA2 static String toBinaryString(long n) Returns a String that contains the binary equivalent of n 10. static String toOctalString(long n) Returns a String that contains octal equivalent of n 11. static String toHexString(long n) Returns a string that contains the hexadecimal equivalent of n The use of some of the methods in Long class is given in program 10.4. Program 10.4 // This program illustrates some of the methods defined // in class Long. class LongDemo { public static void main(String args []) { Long L1 = new Long(87456); Long L2 = new Long(“681523”); System.out.println(“\n L1 object = “ + L1); System.out.println(“\n 2*L1 value = “ + 2 * L1.longValue()); System.out.println(“\n L2 object = “ + L2); System.out.println(“\n 2*L2 value = “ + 2 * L2.longValue()); System.out.println(“\n is (L1 == L2 )?: “ + L1.equals(L2)); System.out.println(“\n L1.compareTo(L2) = “ + L1.compareTo(L2)); Long L3 = Long.valueOf(“234ab34df”, 16); System.out.println(“\n Decimal equivalent of hex 234ab34df = “ + L3); System.out.println(“\n byte value of Long object L3 = “ + L3.byteValue()); System.out.println(“\n int value of Long object L3 = “ + L3.intValue()); System.out.println(“\n double value of Long object L3 = “ + L3.doubleValue()); long L4 = Long.parseLong(“3bcdef29”, 16); System.out.println(“\n long value of L4 = 3bcdef29 = “ + L4); int inum = 97234; System.out.println(“\n binary equivalent of decimal “ + inum + “ = “ + Long.toBinaryString(inum)); Wrapper Classes 165 System.out.println(“\n hexadecimal equivalent of decimal “ + inum + “ = “ + Long.toHexString(inum)); System.out.println(“\n Minimum value of Long = “ + Long.MIN_VALUE); System.out.println(“\n Maximum value of Long = “ + Long.MAX_VALUE); } } The above program gives the following output: L1 object 2*L1 value L2 object 2*L2 value is (L1 == L2 )?: false L1.compareTo(L2) Decimal equivalent of hex 234ab34df byte value of Long object L3 int value of Long object L3 double value of Long object L3 long value of L4 = 3bcdef29 binary equivalent of decimal 97234 hexadecimal equivalent of decimal 97234 Minimum value of Long Maximum value of Long = 87456 = 174912 = 681523 = 1363046 = -1 = 9473570015 = -33 = 883635423 = 9.473570015E9 = 1003351849 = 10111101111010010 = 17bd2 = -9223372036854775808 = 9223372036854775807 10.1.5 Float Class The Float class wraps the float type. The constructors in Float are: Float(double x) Float(float x) Float(String s) where s is a String representation of a float. The Float class has the following additional predefined constants: Constant NaN POSITIVE_INFINITY NEGATIVE_INFINITY Description Not a Number + µ – µ Apart from methods given in table 10.1, additional methods defined in Float are given in table 10.6. 166 Programming in JAVA2 Table 10.6 Additional Methods Defined in Float Class Method Purpose of the Method 1. static Float valueOf(String s) Returns a Float object of the String s 2. int compareTo(Float f) Compares the numerical value of the invoking object with f; returns 0, if both are equal, negative if f>object and positive if f<object 3. boolean equals(Float f) Returns true if the invoking object is equal to f, otherwise false. 4. static float parseFloat(String s) Returns the float equivalent of the number contained in the String s using radix 10 5. static String toString(float x) Returns a String equivalent of x 6. boolean isInfinite() Returns true if the invoking object contains an infinite value, otherwise false 7. static boolean isInfinite (float x) Returns true if x is infinite, otherwise false 8. boolean isNaN() Returns true if the invoking object contains a value that is not a number, otherwise false 9. static boolean isNaN(float x) Returns true if x is not a number, otherwise false The following program 10.5 illustrates some of the methods defined in Float class: Program 10.5 // This program illustrates some of the methods defined in // the class Float. class FloatDemo { public static void main(String args []) { Float f1 = new Float(234.5621); Float f2 = new Float(745.32f); Float f3 = new Float(“562.64”); Wrapper Classes System.out.println(“\n Float object f1 = “ + f1); System.out.println(“\n Float object f2 = “ + f2); System.out.println(“\n byte value of Float object f1 = “ + f1.byteValue()); System.out.println(“\n short value of Float object f1 = “ + f1.shortValue()); System.out.println(“\n float value Float object f1 = “ + f1.floatValue()); System.out.println(“\n float value of Float object f3 = “ + f3.floatValue()); System.out.println(“\n is(f1= = f2)? : “ + f1.equals(f2)); System.out.println(“\n f1.compareTo(f2) = “ + f1.compareTo(f2)); float f4 = Float.parseFloat(“765.89”); System.out.println(“\n float value from the string \”765.89\” = “ + f4); System.out.println(“\n isInfinte(4.5/0) ?= “ + Float.isInfinite((float)4.5 / 0)); System.out.println(“\n is f1 is not a number? “ + f1.isNaN()); System.out.println(“\n Maximum value for float = “ + f1.MAX_VALUE); System.out.println(“\n Minimum value for float = “ + f1.MIN_VALUE); System.out.println(“\n Positive infinity = “ + f1.POSITIVE_INFINITY); } } The above program gives the following output: Float object f1 = 234.5621 Float object f2 = 745.32 byte value of Float object f1 = -22 short value of Float object f1 = 234 float value Float object f1 = 234.5621 float value of Float object f3 = 562.64 is(f1= = f2)? : false f1.compareTo(f2) = -1 float value from the string “765.89” = 765.89 isInfinte(4.5/0) ?= true is f1 is not a number? false Maximum value for float = 3.4028235E38 Minimum value for float = 1.4E-45 Positive infinity = Infinity 167 168 10.1.6 Programming in JAVA2 Double Class The Double class wraps the double type. The constructors in Double are: Double (double x) Double (String s) The constants defined in Float class are also available for Double class. Apart from methods given in table 10.1, additional methods defined in Double are given in table 10.7. Table 10.7 Additional Methods Defined in Double Class Method Purpose of the Method 1. static Double valueOf(String s) Returns Double object of the String s 2. int compareTo(Double d) Compares the numerical value of the invoking object with d; returns 0, if both are equal, negative if d>object and positive if d<object 3. boolean equals(Double d) Returns true if the invoking object is equal to d, otherwise false 4. static double parseDouble(String s) Returns the double equivalent of the number contained in the String s using radix 10 5. static String toString(double d) Returns the string equivalent of d 6. boolean isInfinite() Returns true if the invoking object contains an infinite value, otherwise false 7. static boolean isInfinite(double d) Returns true if d is infinite, otherwise false 8. boolean isNaN() Returns true if the invoking object contains a value that is not a number, otherwise false 9. static boolean isNaN(double d) Returns true if d is not a number, otherwise false Program 10.6 illustrates some of the methods defined in Double class. Wrapper Classes 169 Program 10.6 // This program illustrates some of the methods defined in // the class Double. class DoubleDemo { public static void main(String args []) { Double d1 = new Double(23434567.5621); Double d2 = new Double(3.45e123); Double d3 = new Double(“5624567.64”); System.out.println(“\n Double object d1 = “ + d1); System.out.println(“\n Double object d2 = “ + d2); System.out.println(“\n Double object d3 = “ + d3); System.out.println(“\n byte value of Double object d1 = “ + d1.byteValue()); System.out.println(“\n int value of Double object d1= “ + d1.intValue()); System.out.println(“\n float value of Double object d1 = “ + d1.floatValue()); System.out.println(“\n double value of Double object d1= “ + d1.doubleValue()); System.out.println(“\n is(d1= = d2)? : “ + d1.equals(d2)); System.out.println(“\n d1.compareTo(d2) = “ + d1.compareTo(d2)); double d4 = Double.parseDouble(“765.89”); System.out.println(“\n double value from the string \”765.89\” = “ + d4); System.out.println(“\n isInfinte(2345.67843/0) ? : “ + Double.isInfinite(2345.67843 / 0)); System.out.println(“\n is d1 not a number? : “ + d1.isNaN()); System.out.println(“\n Maximum value for double = “ + d1.MAX_VALUE); System.out.println(“\n Minimum value for double = “ + Double.MIN_VALUE); System.out.println(“\n Negative infinity = “ + Double.NEGATIVE_INFINITY); } } The above program gives the following output: Double object d1 = 2.34345675621E7 Double object d2 = 3.45E123 Double object d3 = 5624567.64 byte value of Double object d1 = 71 int value of Double object d1 = 23434567 170 Programming in JAVA2 float value of Double object d1 = 2.3434568E7 double value of Double object d1= 2.34345675621E7 is(d1= = d2)? : false d1.compareTo(d2) = -1 double value from the string “765.89” = 765.89 isInfinte(2345.67843/0) ? : true is d1 not a number? : false Maximum value for double = 1.7976931348623157E308 Minimum value for double = 4.9E-324 Negative infinity = -Infinity 10.2 The Character Class The Character class wraps the char type. The constructor for this class is Character (char C). The Character class has the following predefined constants: Constant MAX_RADIX MIN_RADIX MAX_VALUE MIN_VALUE Description The largest radix The smallest radix Maximum value of character Minimum value of character Some of the methods defined in Character are given in table 10.8. Table 10.8 Method Methods Defined in Character Class Purpose of the Method 1. char charValue() Gets the character 2. static boolean isDefined(char c) If c is defined in Unicode, it returns true, otherwise false 3. static boolean isDigit(char c) If c is a digit, it returns true, otherwise false 4. static boolean isLetter(char c) If c is a letter, it returns true, otherwise false 5. static boolean isLowerCase(char c) If c is in lowercase, it returns true, otherwise, false 6. static boolean isUpperCase(char c) If c is in uppercase, it returns true, otherwise false Wrapper Classes 171 7. static boolean isWhiteSpace(char c) If c is a white space, it returns true, otherwise false 8. static char toLowerCase(char c) Converts c to lower case 9. static char toUpperCase(char c) Converts c to upper case int compareTo(Character c) Compares the object c with the invoking object and returns 0 if both are equal, negative if c>object and positive if c < object 10. Program 10.7 illustrates some of the methods defined in Character class. Program 10.7 // This program illustrates the use of some of the methods // in Character class. class CharacterDemo { public static void main(String args []) { Character c1 = new Character(‘d’); char c2 = ‘G’; char c3 = ‘7’; System.out.println(“\n Character object = :” +c1); System.out.println(“\n char value of Character object =: “ + c1.charValue()); System.out.println(“\n Is “ + c2 + “ is defined in character set?: “ + Character.isDefined(c2)); System.out.println(“\n Is “ + c2 + “ is a digit?:“ + Character.isDigit(c2)); System.out.println(“\n Is “ + c3 + “ is a digit?:“ + Character.isDigit(c3)); System.out.println(“\n Is “ + c2 + “ is in lower case?:“ + Character.isLowerCase(c2)); System.out.println(“\n Is “ + c2 + “ is in upper case?:“ + Character.isUpperCase(c2)); System.out.println(“\n Maximum radix = : “ + Character.MAX_RADIX); System.out.println(“\n Minimum radix = : “ + Character.MIN_RADIX); } } 172 Programming in JAVA2 The above program gives the following output: Character object = :d char value of Character object =: d Is G defined in character set?: true Is G a digit?: false Is 7 a digit?: true Is G in lower case?: false Is G in upper case?: true Maximum radix = : 36 Minimum radix = : 2 10.3 The Boolean Class The Boolean class wraps the boolean type. Boolean class are : The constructors in Boolean(boolean b) Boolean(String s) where b is a boolean value true or false and s is a string containing boolean value. Some of the methods defined in Boolean are given in table 10.9. Table 10.9 Methods Defined in Boolean Class Method Purpose of the Method 1. boolean booleanValue() Gives the boolean equivalent, otherwise false 2. boolean equals(Boolean b) Gives true if the invoking object and b are equal, otherwise false 3. static Boolean valueOf(String s) Gives true if the String s contains true, otherwise false After this chapter, you should have learned the following: Ü Wrapper classes help to create objects for basic types. Ü Basic type of parameters can be passed by reference using wrapper class objects. In the next chapter, you will learn about mathematical methods used for engineering and scientific calculations. Wrapper Classes 173 Worked Out Problems-10 Problem 10.1w The average height and weight of men and women are given below. Write a program to input the sex, age and height and display the expected weight of that person. Average Weight of Men Agewise Height 15-16 17-19 20-24 25-29 30-39 40-49 50-59 60-69 5’0” 44 52 55 57 58 59 60 59 5’1” 46 53 56 58 59 60 61 60 5’2” 48 54 57 59 60 61 62 61 5’3” 50 56 58 60 61 62 63 62 5’4” 52 58 59 61 62 64 65 63 5’5” 54 60 61 62 63 65 66 64 5’6” 56 61 62 63 64 66 67 65 5’7” 58 63 64 65 66 67 68 66 5’8” 60 64 65 66 67 68 70 67 5’9” 62 66 67 68 69 70 71 68 5’10” 64 67 68 69 70 71 72 69 5’11” 67 69 70 71 72 74 75 71 6’0” 68 70 71 72 73 75 76 72 6’1” 69 71 72 73 74 76 77 73 50-59 60-69 Average Weight of Women Agewise Height 15-16 17-19 20-24 25-29 30-39 40-49 4’10” 43 44 45 47 51 53 54 56 4’11” 45 46 47 48 52 54 55 57 5’0” 46 47 49 51 53 55 56 58 5’1” 48 49 50 52 54 56 57 59 5’2” 49 51 52 53 55 57 58 60 5’3” 51 52 53 54 56 58 59 61 5’4” 52 53 54 55 57 59 60 62 5’5” 54 55 56 58 59 60 61 63 5’6” 56 57 58 59 60 61 62 64 5’7” 58 59 60 61 62 63 64 66 5’8” 60 61 62 63 64 65 66 68 174 Programming in JAVA2 Program 10.1w /* ----------------------------------------------------------This program estimates the weight of a person using the standard height-weight-age table . The tables are stored in the interface Humanweight. Any class that implements this interface can access the two tables. somasundaramk@yahoo.com --------------------------------------------------------------*/ import java.io.*; import java.text.*; interface Humanweight { final int MWEIGHT [][] = { { 44, 52, 55, 57, 58, 59, 60, 59 }, { 46, 53, 56, 58, 59, 60, 61, 60 }, { 48, 54, 57, 59, 60, 61, 62, 61 }, { 50, 56, 58, 60, 61, 62, 63, 62 }, { 52, 58, 59, 61, 62, 64, 65, 63 }, { 54, 60, 61, 62, 63, 65, 66, 64 }, { 56, 61, 62, 63, 64, 66, 67, 65 }, { 58, 63, 64, 65, 66, 67, 68, 66 }, { 60, 64, 65, 66, 67, 68, 70, 67 }, { 62, 66, 67, 68, 69, 70, 71, 68 }, { 64, 67, 68, 69, 70, 71, 72, 69 }, { 67, 69, 70, 71, 72, 74, 75, 71 }, { 68, 70, 71, 72, 73, 75, 76, 72 }, { 69, 71, 72, 73, 74, 76, 77, 73 } }; final int FWEIGHT [][] = { { 43, 44, 45, 47, 51, 53, 54, 56 }, { 45, 46, 47, 48, 52, 54, 55, 57 }, { 46, 47, 49, 51, 53, 55, 56, 58 }, { 48, 49, 50, 52, 54, 56, 57, 59 }, { 49, 51, 52, 53, 55, 57, 58, 60 }, { 51, 52, 53, 54, 56, 58, 59, 61 }, { 52, 53, 54, 55, 57, 59, 60, 62 }, { 54, 55, 56, 58, 59, 60, 61, 63 }, { 56, 57, 58, 59, 60, 61, 62, 64 }, { 58, 59, 60, 61, 62, 63, 64, 66 }, { 60, 61, 62, 63, 64, 65, 66, 68 } }; } class Prob101 implements Humanweight { public static void main(String args []) Wrapper Classes { int inage = 0; int inheight = 0; String insex = "a"; String s; int column = 0, mrow = 0, frow = 0; try { // Read the key board to get the input InputStreamReader isr = new InputStreamReader (System.in); BufferedReader br = new BufferedReader(isr); DecimalFormat df = new DecimalFormat(); Number n; System.out.println("To find your expected weight, feed in the following information :"); System.out.print("Type in your sex (m/f) : "); s = br.readLine(); insex = s.trim(); System.out.print("Type in your height in inches (5 feet 3inch as 63) : "); s = br.readLine(); n = df.parse(s); inheight = n.intValue(); System.out.print("Type in your age in completed years : "); s = br.readLine(); n = df.parse(s); inage = n.intValue(); } catch (IOException ie) { System.out.println("IO Error"); } catch (ParseException pe) { System.out.println("Parse exception"); } // Find the age range if (inage < 15) System.out.println(" You are below the age range defined in this program\n "); else if (inage <= 16) column = 0; else if (inage <= 19) column = 1; else if (inage <= 24) column = 2; else if (inage < 29) column = 3; 175 176 Programming in JAVA2 else if (inage < 39) column = 4; else if (inage < 49) column = 5; else if (inage < 59) column = 6; else if (inage < 69) column = 7; else System.out.println("You are above the age range defined in this program "); //Find the height row for male if (insex.equals("M") || insex.equals("m")) { if ((inheight < 60) || (inheight > 73)) System.out.println(" You are out of the the height range defined in this program\n "); else { mrow = inheight - 60; System.out.println("You should have a weight about " + MWEIGHT[mrow][column] + " Kg\n"); } } else // Find the height row for female if (insex.equals("F") || insex.equals("f")) { if ((inheight < 58) || (inheight > 68)) System.out.println(" You are out of the height range defined in this program\n "); else { frow = inheight - 58; System.out.println("You should have a weight about " + FWEIGHT[frow][column] + " kg\n"); } } else System.out.println("Type the sex data properly\n"); } } The above program gives the following output: To find your expected weight, feed in the following information: Type in your sex (m/f) :m Type in your height in inches (5 feet 3inch as 63) :70 Type in your age in completed years :51 You should have a weight about 72 kg Wrapper Classes 177 Exercise-10 I. Fill in the blanks 10.1 Wrapper classes help to create objects for _________ types. 10.2 Using wrapper classes simple types ______ be passed by reference to methods. 10.3 The superclass of Integer and Long is _________ . 10.4 The wrapper classes are defined in __________ package. 10.5 ________ method converts a string represented in a number system with r as radix to byte value. II. Write Java programs for the following: 10.6 Write a class called Convert with one method that takes Integer as object and prints out two times the int value of the object while another method that takes up Integer object and prints out three times the double value of the object. Write another class Main, create an Integer object and Convert object. Call the two methods in the Convert object and find out the int and double values. 10.7. Write a program that converts the string “7845” to its binary, octal and hexadecimal equivalents. 10.8. Write a program that finds uppercase letters, white spaces and digits of a character array. 10.9. Write a program that converts the characters in the given char array to upper-case letters. 10.10. Write a program that converts the int type numbers a=34 and b=36 to binary string. Bitwise AND a and b and print out the binary string of the resulting value. * * * * * * 178 Programming in JAVA2 BLANK 179 Chapter 11 MATHEMATICAL METHODS In this chapter, the mathematical methods used scientific and engineering applications are explained. for For scientific and engineering calculations, a variety of mathematical functions are needed. Java provides these functions in the Math class available in java.lang package. Math class has two constants E and PHI. The methods defined in Math class are given in table 11.1. Table 11.1 Methods Defined in Math Class All are static methods. Method Purpose of the Method 1. double sin(double x) Returns the sine value of angle x in radians 2. double cos(double x) Returns the cosine value of the angle x in radians 3. double tan(double x) Returns the tangent value of the angle x in radians 4. double asin(double x) Returns angle value in radians for arcsin of x 180 Programming in JAVA2 5. double acos(double x) Returns angle value in radians for arccos of x 6. double atan(double x) Returns angle arctangent of x 7. double exp(double x) Returns exponential (e x) value of x 8. double log(double x) Returns the natural logarithm of x 9. double pow(double x, double y) Returns x to the power of y (x y ) 10. double sqrt(double x) Returns the square root of x 11. int abs(int n) Returns absolute value of n. The abs method is also available for arguments of type long, float and double. 12. double ceil(double x) Returns the smallest whole number greater than or equal to x 13. double floor(double x) Returns the largest whole number less than or equal to x 14. int max(int n, int m) Returns the maximum of n and m. The max method is also available for arguments of type long, float and double. 15. int min(int n, int m) Returns the minimum of n and m. This min method is also available for arguments of type long, float and double. 16. double rint(double x) Returns the rounded whole number of x 17. int round(float x) Returns the rounded int value of x 18. long round(double x) Returns the rounded long value of x 19. double random() Returns a random value between 0 and 1.0 20. double toRadians(double angle) Converts the angle in degrees to radians 21. double toDegrees(double angle) Converts the angle in radians to degrees value in radians for Mathematical Methods 181 22. double cbrt(double x) Returns the cube root of x 23. double copySign(double magnitude, double sign) Returns the first floating argument with the sign of the second floating point argument. Sign takes the value of -1.0, or +1. 24. double cosh(double x) Returns the hyperbolic cosine of x. 25. double hypot(double x, double y) Returns sqrt(x 2+y 2). 26. double log10(double x) Returns the logarithm to the base10 of x. 27. double signum(double x) Returns the sign of the number -1.0 if x<0, 0 if x=0 1 if x>0 28. double sinh(double x) Returns the hyperbolic sine of x. 29. double tanh(double x) Returns the hyperbolic tangent of x. The following program 11.1 gives the use of some of the mathematical methods given in table 11.1. Program 11.1 /* This program illustrates some of the methods defined in Math class.To run this program jdk1.6 or higher version is needed. somasundaramk@yahoo.com */ class MathDemo1{ public static void main(String args[]){ double x= 3.6,y =0.5,log20; double s90= Math.toRadians(90) ; double as1= Math.asin(1.0); System.out.println("\n The angle 90 degress = " +s90 + " radians"); System.out.println("\n Value of sin " + s90 + " = " +Math.sin(s90)); System.out.println("\n Value of arcsin(1.0) = " +as1); System.out.println("\n Value of 22/7/2 = " + 22.0/7.0/2.0 ); System.out.println("\n Java Math.E = " + Math.E); System.out.println("\n Value of exp(1) = " + Math.exp(1.0)); 182 Programming in JAVA2 System.out.println("\n Java Math.PI = " + Math.PI); System.out.println("\n mathematical pi = 22/7 = " + 22.0/7.0 ); System.out.println("\n " +x+" rounded by rint = " + Math.rint(x )); System.out.println("\n "+x+" rounded by round = " + Math.round(x )); System.out.println("\n "+x+" rounded by ceil = " + Math.ceil(x )); System.out.println("\n "+x+" rounded by floor = " + Math.floor(x )); System.out.println("\n Natural logarithm of 10.0 = " +Math.log(10. )); log20 = Math.log10(20); System.out.println("\n logarithm to base 10 of 20.0 = " +log20); System.out.println("\n anti log of " +log20 + " = " + Math.exp(Math.log(10)*log20)); System.out.println("\n Hyperbolic sin of "+y+" = " + Math.sinh(y)); System.out.println("\n Hyperbolic cos of "+y+" = " + Math.cosh(y)); System.out.println("\n Hyperbolic tan of "+y+" = " + Math.tanh(y)); } } The above program gives the following output: The angle 90 degress = 1.5707963267948966 radians Value of sin 1.5707963267948966 = 1.0 Value of arcsin(1.0) = 1.5707963267948966 Value of 22/7/2 = 1.5714285714285714 Java Math.E = 2.718281828459045 Value of exp(1) = 2.7182818284590455 Java Math.PI = 3.141592653589793 mathematical pi = 22/7 = 3.142857142857143 3.6 rounded by rint = 4.0 3.6 rounded by round = 4 3.6 rounded by ceil = 4.0 3.6 rounded by floor = 3.0 Natural logarithm of 10.0 = 2.302585092994046 logarithm to base 10 of 20.0 = 1.3010299956639813 anti log of 1.3010299956639813 = 20.000000000000007 Hyperbolic sin of 0.5 = 0.5210953054937474 Hyperbolic cos of 0.5 = 1.1276259652063807 Hyperbolic tan of 0.5 = 0.46211715726000974 Mathematical Methods 183 After reading this chapter, you should have learned the following: Ü Mathematical methods for trigonometric, logarithmic, hyperbolic, rounding and random number generating functions. In the next chapter, you will learn about exceptions. Worked Out Problems-11 Problem 11.1w Using Lagrange’s interpolation formula n f(x) = S fk(x)lR(x) R=0 where l i(x)= (x-x 0 )(x-x 1 )...(x-x i-1 )(x-x i+1 )...(x-x n ) (x i -x 0 )(x i -x 1 )...(x i -x i-1 )(x i -x i+1 )...(x i -x n ) compute value of f(x) at x=1.700 from the following table: x f(x) 1.1275 0.1197 1.1503 0.13957 1.1735 0.15931 1.1972 0.17902 Program 11.1w /* ---------------------------------------------------------This program calculates the value of function at a given point using the given numerical table using Lagrange's interpolation formula. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Lagrange { double fx [], x []; int n; double lfun []; double gx; Lagrange(double x [], double fx []) { 184 Programming in JAVA2 this.x = x; this.fx = fx; n = x.length; lfun = new double[n]; } double Interpolate(double gx) { //calculate the Lagrange factors this.gx = gx; double fgx = 0; for (int k = 0; k < n; k++) { lfun[k] = 1; for (int i = 0; i < n; i++) if (i != k) lfun[k] *= (gx - x[i]) / (x[k] - x[i]); } for (int i = 0; i < n; i++) fgx += lfun[i] * fx[i]; return fgx; } } class Prob111 { public static void main(String args []) { double x [] = {1.1275, 1.1503, 1.1735, 1.1972 }; double fx [] = {0.1197, 0.13957, 0.15931,0.17902 }; int n = x.length; int pn = 80; Lagrange lf = new Lagrange(x, fx); double newfx = lf.Interpolate(1.17); //print out the inout values. for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.print("x \t"); for (int i = 0; i < n; i++) System.out.print(x[i] + " "); System.out.println("\n"); System.out.print("f(x) \t"); for (int i = 0; i < n; i++) System.out.print(fx[i] + " "); System.out.println("\n"); for (int i = 0; i < pn; i++) System.out.print("-"); // reduce the fractional digits to 5 Mathematical Methods 185 newfx = (int)(newfx * 100000); newfx = newfx / 100000; System.out.println("Using Lagrange's interpolation formula\n"); System.out.println("the value of f(x) at x= " + lf.gx + " = " + newfx); } } The above program gives the following output: -------------------------------------------------------------------------------x 1.1275 1.1503 1.1735 1.1972 f(x) 0.1197 0.13957 0.15931 0.17902 -------------------------------------------------------------------------------Using Lagrange's interpolation formula the value of f(x) at x= 1.17 = 0.15636 Problem 11.2w Calculate the value of the integral I = 2 p 1 ó 2 e-t /2 dt õ 0 with h=0.1, using Trapezoidal rule given by I = h (y 0 +y n )+h(y 1 +y 2 +...y n-1 ) 2 Program 11.2w /* ------------------------------------------------------------This program intergrates the given function using Trapezoidal rule. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Trapez { int n; double fx []; double h; Trapez(double x [], double inc) { 186 Programming in JAVA2 fx = x; h = inc; n = x.length; } double Integrate() { double sum = 0; sum = sum + (fx[0] + fx[n - 1]) * h / 2.0; for (int i = 1; i < n - 1; i++) sum += h * fx[i]; return sum; } } class Prob112 { public static void main(String args []) { Trapez tpz; double low = 0; double high = 1.0; double h = 0.1; double mult = Math.sqrt(2.0 / Math.PI); int n = (int)((high - low) / h); double fx [] = new double[n + 1]; double t = 0; // compute the fx values for (int i = 0; i <= n; i++) { fx[i] = mult * Math.exp(-t * t / 2.0); t += h; } tpz = new Trapez(fx, h); double tpzval = tpz.Integrate(); //reduce to 5 decimal places tpzval = (int)(tpzval * 100000); tpzval = tpzval / 100000; System.out.println("Integral value = " + tpzval); } } The above program gives the following output: Integral value = 0.68228 Mathematical Methods 187 Problem 11.3w Using Simpson’s 1/3 rule, compute the following integral: 1 ó I = ecos2px dx 0õ with h = 0.1 Simpson’s 1/3rd rule is given by I = h (y 0+4y 1+2y 2+4y 3+2y 4+...+y n ) 3 Program 11.3w /* ------------------------------------------------------------This program intergrates the given function using Simpson's 1/3rd rule. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Simpson { int n; double fx []; double h; Simpson(double x [], double inc) { fx = x; h = inc; n = x.length; } double Integrate() { double sumodd = 0, sumeven = for (int i = 1; i < n - 1; i sumodd += fx[i]; for (int i = 2; i < n - 1; i sumeven += fx[i]; sum = sum + h * (fx[0] + 4 * fx[n - 1]) / 3.0; return sum; } } class Prob113 0, sum = 0; += 2) += 2) sumodd + 2 * sumeven + 188 Programming in JAVA2 { public static void main(String args []) { Simpson sim; double low = 0; double high = 1.0; double h = 0.1; double mult = 2.0 * Math.PI; int n = (int)((high - low) / h); double fx [] = new double[n + 1]; double x = 0; // compute the fx values for (int i = 0; i <= n; i++) { fx[i] = Math.exp(Math.cos(mult * x)); x += h; } sim = new Simpson(fx, h); double simval = sim.Integrate(); //reduce to 5 decimal places simval = (int)(simval * 100000); simval = simval / 100000; System.out.println("Using Simpson's 1/3rd rule"); System.out.println("Integral value = " + simval); } } The above program gives the following output: Using Simpson's 1/3rd rule Integral value = 1.26588 Problem 11.4w Compute the integral value for values given below using Simpson’s 1/3rd rule: x 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 y 1.0 0.9901 0.9615 0.9174 0.8621 0.8 0.7353 0.6711 0.6098 0.5525 1.0 0.5 Program 11.4w /* -------------------------------------------------------This program intergrates the given function using Simpson's 1/ 3rd rule using the table of numerical values of an unknown function. somasundaramk@yahoo.com ------------------------------------------------------------- */ Mathematical Methods 189 class Simpson { int n; double fx []; double h; Simpson(double x [], double inc) { fx = x; h = inc; n = x.length; } double Integrate() { double sumodd = 0, sumeven = 0, sum = 0; for (int i = 1; i < n - 1; i += 2) sumodd += fx[i]; for (int i = 2; i < n - 1; i += 2) sumeven += fx[i]; sum = sum + h * (fx[0] + 4 * sumodd + 2 * sumeven + fx[n - 1]) / 3.0; return sum; } } class Prob114 { public static void main(String args []) { Simpson sim; double h = 0.1; int n; int pn = 30; // no fo characters used for making line double fx [] ={1.0, 0.9901,0.9615,0.9174,0.8621,0.8, 0.7353,0.6711,0.6098, 0.5525,0.5}; n = fx.length; double x [] ={0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9, 1.0}; // Print out the given values System.out.println("The given values are:"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("x \t y=f(x) \n"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); for (int i = 0; i < n; i++) System.out.println(x[i] + "\t" + fx[i]); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); 190 Programming in JAVA2 sim = new Simpson(fx, h); double simval = sim.Integrate(); //reduce to 5 decimal places simval = (int)(simval * 100000); simval = simval / 100000; System.out.println("Using Simpson's 1/3rd rule"); System.out.println("Integral value = " + simval); } } The above program gives the following output: The given values are: -----------------------------x y=f(x) -----------------------------0.0 1.0 0.1 0.9901 0.2 0.9615 0.3 0.9174 0.4 0.8621 0.5 0.8 0.6 0.7353 0.7 0.6711 0.8 0.6098 0.9 0.5525 1.0 0.5 -----------------------------Using Simpson's 1/3rd rule Integral value = 0.78539 Problem 11.5w Compute the first derivative of f(x) for the following table of values x 1.0 f(x) 1.0 1.05 1.1 1.15 1.2 1.3 1.02470 1.04881 1.07238 1.09544 1.11803 1.14017 The differentiation is carried out using the formula: f’ i(x i) = 1.25 f(x i+1 )–f(x i ) h for i = 0, 1, ..., n-1 Mathematical Methods 191 Program 11.5w /* ----------------------------------------------------------This program finds the first derivative of the given table of f(x) values. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Function { int n; double fx []; double dfx []; double h; Function(double x [], double inc) { fx = x; h = inc; n = x.length; dfx = new double[n - 1]; } double [] Differentiate() { for (int i = 0; i < n - 1; i++) dfx[i] = (fx[i + 1] - fx[i]) / h; return dfx; } } class Prob115 { public static void main(String args []) { Function fun; double h = 0.1; int n; int pn = 50; // no of characters used for making line double fx [] ={1.0,1.02470,1.04881,1.07238,1.09544, 1.11803,1.14017}; n = fx.length; double x [] ={ 1.0,1.05, 1.1, 1.15,1.2,1.25,1.3}; double dfx [] = new double[n - 1]; // Print out the given values System.out.println("The given values and their first derivatives are :"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("x \t f(x) \t f'(x)"); for (int i = 0; i < pn; i++) 192 Programming in JAVA2 System.out.print("-"); System.out.println("\n"); // create the function fun = new Function(fx, h); //differentiate the f(x) dfx = fun.Differentiate(); int dn = dfx.length; for (int i = 0; i < dn; i++) { double diffval = dfx[i]; //reduce to 5 decimal places diffval = (int)(diffval * 100000); diffval = diffval / 100000; System.out.println(x[i] + "\t" + fx[i]); System.out.println("\t\t\t" + diffval); } System.out.println(x[n - 1] + "\t" + fx[n - 1]); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: The given values and their first derivatives are: --------------------------------------------------------x f(x) f'(x) --------------------------------------------------------1.0 1.0 0.24699 1.05 1.0247 0.2411 1.1 1.04881 0.2357 1.15 1.07238 0.23059 1.2 1.09544 0.2259 1.25 1.11803 0.22139 1.3 1.14017 --------------------------------------------------------- Mathematical Methods 193 Problem 11.6w Solve the first order differential equation dy dx = xy 1/3 , with y 0 (1) = 1 for x=1 to 3, in steps of 0.5 using Runge-Kutta method y 1 = y 0+1/6(k 1 +2k 2 +2k 3 +k 4), where, k 1 = hf(x, y) k 2 = hf(x+½h, y+½k 1 ) k 3 = hf(x+½h, y+½k 2 ) k 4 = hf(x+h, y+k 3 ) Program 11.6w /* ------------------------------------------------------------This program solves a first order differential equation using Runge-Kutta 4-point formula.For details see the book Introduction to Numerical Analysis, F.B.Hildebrand, Tata McGrawHill, New Delhi somasundaramk@yahoo.com ------------------------------------------------------------- */ class Equation { double x, y, fy; Equation(double ex, double ey) { x = ex; y = ey; fy = x * Math.pow(y, 1 / 3.0); } } class RungeKutta { double x, y, h, dy; Equation eq; RungeKutta(double rx, double ry, double dx) { x = rx; y = ry; h = dx; } 194 Programming in JAVA2 double Solve() { double k1, k2, k3, k4; eq = new Equation(x, y); k1 = h * eq.fy; eq = new Equation(x + h / 2, y + k1 / 2); k2 = h * eq.fy; eq = new Equation(x + h / 2, y + k2 / 2); k3 = h * eq.fy; eq = new Equation(x + h, y + k3); k4 = h * eq.fy; dy = (k1 + 2 * k2 + 2 * k3 + k4) / 6.0; return dy; } } class Prob116 { public static void main(String args []) { RungeKutta rk; double y, dy; double x, h = 0.1; int pn = 35; x = 1; y = 1; System.out.println("Solving differential equation by Runge -Kutta method\n"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("x \t y"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println(x + "\t" + y); for (x = 1.0; x < 3.0; ) { rk = new RungeKutta(x, y, h); dy = rk.Solve(); y = y + dy; x = x + h; // reduce to 5 decimal place accuracy for // printing double py = (int)(y * 100000); py = py / 100000; double px = (int)(x * 10); px = px / 10; System.out.println(px + "\t" + py); } for (int i = 0; i < pn; i++) Mathematical Methods 195 System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: Solving differential equation by Runge-Kutta method ----------------------------------x y ----------------------------------1.0 1.0 1.1 1.10681 1.2 1.22787 1.3 1.36413 1.4 1.51656 1.5 1.68617 1.6 1.87398 1.7 2.08104 1.8 2.30842 1.9 2.55718 2.0 2.82842 2.1 3.12323 2.2 3.44272 2.3 3.78799 2.4 4.16016 2.5 4.56035 2.6 4.98969 2.7 5.44931 2.8 5.94033 2.9 6.46389 3.0 7.02113 ----------------------------------Problem 11.7w Find one root of the following equation using Newton-Raphson method f(x) = x 3 + 2x 2 + 10x -20 = 0 by Newton-Raphson method, x n+1 = x n – f(x n ) f’(x n ) for n = 0, 1, 2, 3 until the required result is obtained. For this method, x 0 value is to be supplied. By inspection, the above equation has one root between x = 1 and 2. Hence, initial value may be taken as x = 1.0 196 Programming in JAVA2 Program 11.7w /* ------------------------------------------------------------This program finds one root of the given equation using NewtonRaphson iterative method. This method needs an intital value. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Prob117 { public static void main(String args []) { double fx, fdx, x, x1; int pn = 50; x = 1.0; int count = 0; for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("Iteration \t x \t\t f(x)"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); while (true) { fx = Math.pow(x, 3) + 2.0 * Math.pow(x, 2) + 10.0 * x - 20.0; fdx = 3.0 * Math.pow(x, 2) + 4.0 * x + 10.0; x1 = x - fx / fdx; count++; System.out.println(count + " \t " + x1 + "\t" + fx); if (Math.abs(1. - x / x1) < 1.0e - 08) break; x = x1; } for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("One root = " + x1 + " after " + count + " iterations "); } } Mathematical Methods 197 The above program gives the following output: ----------------------------------------------------------------------------------------------Iteration x f(x) ----------------------------------------------------------------------------------------------1 1.4117647058823528 -7.0 2 1.3693364705882352 0.9175656421738232 3 1.3688081886175318 0.011148119412446533 4 1.3688081078213745 1.704487072373695E-6 5 1.3688081078213727 3.907985046680551E-14 -----------------------------------------------------------------------------------------------One root = 1.3688081078213727 after 5 iterations Exercise-11 I. Fill in the blanks : 11.1. The Math class is packaged in ______________ . 11.2. The method that returns the smallest integer that is greater than or equal to the given double value is ___________ . 11.3. The method that returns the largest integer that is less than or equal to the given double value is _________ . II. Write Java program for the following : 11.4 The projection of the radius of a rotating wheel is given by y = R Sin(q) Write a Java program to compute y value for q = 0 to 2 . 11.5. The angle for the point (x, y) is calculated using q = tan -1 (y/x). Write a Java program to find the angle q for three sets of (x, y). 11.6. The roots of a quadratic equation ax 2 + bx + c = 0 is given by x = – b ± Ö b 2–4ac 2a Write a Java program to find the roots for 2 sets of a, b and c. 11.7. Write a Java program to generate a five-digit random number. 11.8. A set of 10 integers are given. Store them in an array. Using only max() method, write a Java program to find the largest integer in the given set. 198 11.9. Programming in JAVA2 The hyperbolic Sin of x is given by Sinh(x) = ex + e -x 2 Write a Java program to compute the Sinh(x) for x = 0 to 12.5 in steps of 0.5. 11.10. The free falling rain drop of mass m is governed by the equation: dv/dt = 32 - cv 2 /m where c/m = 2. Calculate the velocity v for different times. Assume v(0) = 0. Use Runge-Kutta method. 11.11. Calculate the integral value of the following equation using Simpson’s rule: 1.4 ó x dx I = 1õ * * * * * * 199 Chapter 12 EXCEPTIONS In this chapter, you will learn about exceptions. Exceptions are abnormal conditions occuring in a program. When such exceptions occur, the program aborts or hangs, leaving the user without any information. This chapter explains how to manage such situations. A Java program, compiled and error-free, will execute and complete the task for which the program has been developed. However, there are occasions in which a program running smoothly in normal conditions may encounter errors in abnormal conditions such as divide by zero. Such errors occurring in abnormal conditions are called exceptions. The errors may occur internally in the program code or through the resources the program is trying to access. The sources of errors may be user-input errors such as giving a wrong URL, device errors such as printer not ready, physical limitations such as disk full or memory not enough and code errors like array index out of bound, trying to access an empty stack and divide by zero error. If such exceptions are not caught, the program aborts at the point of occurring of the exception. Java provides appropriate mechanisms to handle such exceptions. The objective of handling exceptions is to inform the user about the error or to take an alternative path to overcome the problem and complete the remaining task. This helps the user to know what is happening inside the program. In the absence of such messages, the user may end up with unexpected output. 200 Programming in JAVA2 12.1 Types of Exceptions All exceptions in Java are handled by a superclass Throwable defined in java.lang package. The Throwable class has two subclasses, Exception and Error. Exception again has two subclasses, IOException and RuntimeException. The Exception hierarchy is given in fig. 12.1. Throwable Error Exception IOException RuntimeException Fig.12.1 The Exception Hierarchy RuntimeException Exception occurring in the program code at runtime are handled in this class. Divide by zero error, array index out of bound, wrong cast and null pointer access are of this type. These types of errors could have been avoided, if the programmer had taken care to write the program. These exceptions can be caught and handled by Java. IOException Exceptions occurring while accessing I/O devices are handled in this class. File not found, end of file encountered are of this type. Exception In this class, a user can create one’s own Exception and use it in Java program. All Exceptions under this class are to be caught and handled. Error Errors which are beyond the control of the programmers are dealt in this class. Disk full and memory not enough are of this type. Java does not provide any mechanism to handle them and should not be caught. Exceptions 201 12.2 Catching Exceptions Java developers have identified commonly occurring exceptions and they are specified in the Exception. When such exceptions appear in a program at runtime, they are to be caught and handled. The Exception is caught by try...catch mechanism. The general form of the try...catch block is: try { ... statements that may give exceptions } catch (ExceptionType e1){ statements to handle Exception Type1 } catch (ExceptionType e2) { statements to handle ExceptionType2 } finally { statements to be executed whether an exception occurs or not } The terms try, catch and finally are Java keywords. e1 and e2 are errors. In the try block, the statements that are suspected to cause exceptions are placed. ExceptionType1 and ExceptionType2 are the different exception types. The catch block contains statements that are to be executed in the event of occurring of an Exception. Multiple catch blocks for single try block can be set up, each catch block dealing one specific type of exception out of several occurring inside the try block. The try block may be constructed to trap any number of exceptions. If an exception occur in the try block and if there is no matching catch block, the program is aborted. In case no Exception occurs inside the try block, all catch block statements will be skipped and only statements in the finally block will be executed. This finally block will be executed irrespective of whether an Exception occurs or not. The catch block statements are operative only for the preceeding try block. The finally block is optional. The following program 12.1 contains an array out of bounds Exception that is caused during the runtime and aborted without completing the program. Program 12.1 // This program illustrates the Exception in a program. class ExceptionDemo1 { public static void main(String args []) { 202 Programming in JAVA2 int mat [] = new int[10]; mat[10] = 25; System.out.println(“Last element of mat = “ +mat[9]); } } The above program gives the following error message and aborts the execution: Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 10 at ExceptionDemo1.main(ExceptionDemo1.java:5) The above error message indicates that an ArrayIndexOutOfBoundsException as defined in java.lang package has occurred in the main method of the program ExceptionDemo1.java at line 5. In program 12.1, the array index for the mat array can take values from 0 to 9 only. However the program tried to access an element at index 10, which is out of bounds. Now, we will make use of an exception-handling feature of Java to handle the Exception using try and catch. The following program 12.2, uses the try...catch structure to handle the array out of bounds Exception: Program 12.2 // This program illustrates the catch of an Exception // in a program. class CatchException1 { public static void main(String args []) { int mat [] = new int[10]; try { mat[10] = 25; } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“Array index out of bounds in mat array”); mat[9] = 25; } System.out.println(“Beyond the exception point “); System.out.println(“Last element of mat = “ + mat[9]); } } The above program gives the following output: Exceptions 203 Array index out of bounds in mat array Beyond the exception point Last element of mat = 25 The output of the above program 12.2 shows that the program crossed the array out of bounds exception and completed the whole program. In the catch block, any statement that can provide remedy to the statement causing the exception may be placed. In a try block, when an exception occurs, the control skips all statements from that point till the end of try block. Therefore, care must be taken to include a statement in a try block. In case, an exception occurs in a code and if it is not going to cause any problem to your results, then an empty block{} can be placed after the catch block. The following program 12.3 illustrates the above two concepts in a try. . . catch block overlapping with a for loop: Program 12.3 // Program to illutrate the behavior of a try block class TryBehave { public static void main(String args []) { int i, x, con = 4; for (i = 1; i < 8; i++) try { x = 25 / (con - i); System.out.println(“\n quot =” + x); } catch (ArithmeticException e) { System.out.println(“\n Divide by zero error for i =” + i); } catch (ArrayIndexOutOfBoundsException e) { } } } The above program gives the following output: quot =8 quot =12 quot =25 Divide by zero error for i =4 204 Programming in JAVA2 quot =-25 quot =-12 quot =-8 G In a try ... catch block, when an exception occurs, all statements between the statement causing the exception and the end of the try block will be skipped. Hence a programmer must decide which statements are to be placed inside a try block. 12.2.1 Nested try Blocks Nested try block, one try block enclosing another try block, is permitted in a Java program. The catch statements are operative for the corresponding statement blocks defined by { and }. The following program 12.4, illustrates the nested try block: Program 12.4 // This program illustrates the nested Try block. class NestedTry { public static void main(String args []) { int vec [] = { 3, 5, 4, 10, 2 }; int nmr = 24; int quot, sum = 0; for (int i = 0; i <= 5; i++) { try { quot = nmr / (2 - i); try { sum += vec[i]; } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“\n Array index out of bounds at index(inner try) = “ + i); } catch (ArithmeticException e) { System.out.println(“\n Divide by zero error at i (inner try) = “ + i); } Exceptions 205 System.out.println(“\n Quotient = “ + quot); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“\n Array index out of bounds at index(outer try) = “ + i); } catch (ArithmeticException e) { System.out.println(“\n Divide by zero error at i (outer try) = “ + i); } } System.out.println(“\n Sum of numbers = “ + sum); } } The above program gives the following output: Quotient = 12 Quotient = 24 Divide by zero error at i (outer try) = 2 Quotient = -24 Quotient = -12 Array index out of bounds at index (inner try) = 5 Quotient = -8 Sum of numbers = 20 The above program finds quotient of integer division of the variable nmr by i - 2 and finds the sum of the array vec with five elements. When the for loop is repeated, divide by zero error occurs and the control skips all the statements till the end of outer try block and looks for the matching catch statement. Thus the catch statement in the outer try block for ArithmeticException is caught and the catch block statements are executed. Since the control has skipped all statements between the occurrence of the exception and the corresponding }, of the corresponding try block, sum += vec[i] for i=2 is not executed. Hence, the final value of sum gives only 20 instead of 24. When the array index i takes the value 5, ArrayIndexOutOfBoundsException occurs in the inner try block and is caught and handled. The control then exits the inner try block and the remaining two print statements are executed. 12.2.2 Hierarchy of Multiple Catch Blocks When multiple catch blocks are set up for a try block, then the subclass exceptions are to be caught first and then the superclass exceptions. In case superclass exception handlers are placed first, followed by handlers for subclass 206 Programming in JAVA2 exceptions, then Java compiler will give a code not reached error. Suppose in a multiple catch block, the first catch block catches an exception of type Exception followed by another catch block to catch RuntimeException, then code not reached error will occur. The following program 12.5 illustrates this: Program 12.5 // This program illustrates the multiple catch with improper // hierarchy. // This program will give compile error. class Multicatch { public static void main(String args []) { int vec [] = {3,5,4,10,2}; int nmr = 24; int quot, sum = 0; for (int i = 0; i <= 5; i++) { try { quot = nmr / (2 - i); sum += vec[i]; System.out.println(“\n Quotient = “ + quot); } catch (Exception e) { System.out.println(“\n Array index out of bounds at index = “ + i); } catch (ArithmeticException e) { System.out.println(“\n Divide by zero error at i = “ + i); } } System.out.println(“\n Sum of numbers = “ + sum); } } The above program when compiled will give the following error: Multicatch.java:17: catch not reached. } catch(ArithmeticException e){ 1 error Exceptions 207 In the above program, the first catch block catches exception of a superclass Exception while the second catch block catches the ArithmeticException belonging to RuntimeException, which is a subclass of Exception (see fig. 12.1). Hence, the compile error. If the order of the catch blocks is interchanged, the program will be error-free and can be executed. G In a multiple catch block, the subclass exceptions are to be caught first followed by superclass exceptions. 12.3 Rethrowing Exceptions When an exception is caught in a method, it is up to the programmer to deal with it. If it is known how to handle the exception, it can be handled, otherwise it can be rethrown. Rethrowing is done through the throw clause. Unless the rethrown exception is caught again, the program will abort. After the throw statement, no other statement should be placed in that block. If any statement is placed after the throw statement in that block, Java will give code not reached, compile error. The following program 12.6 illustrates how to rethrow an exception. The exception is not recaught and hence aborts after rethrow. Program 12.6 // This program demonstrates rethrowing an exception. class Rethrow { public static void main(String args []) throws Exception { int nmr = 24, i, quot; for (i = 0; i <= 5; i++) try { quot = nmr / (i - 2); System.out.println(“\n Quotient = “ + quot); } catch (ArithmeticException e) { System.out.println(“\n Rethrowing the exception at i =” + i); throw e; } } } 208 Programming in JAVA2 The above program gives the following result: Quotient = -12 Quotient = -24 Rethrowing the exception at i =2 Exception in thread “main” java.lang.ArithmeticException: / by zero at Rethrow.main(Compiled Code) The following program 12.7 illustrates recatching a rethrown exception and makes the program to complete its remaining task: Program 12.7 // This program demonstrates recatching of exception. class Recatch { public static void main(String args []) { int nmr = 24, i, quot; for (i = 0; i <= 5; i++) try{ try { quot = nmr / (i - 2); System.out.println(“\n Quotient = “ + quot); } catch (ArithmeticException e) { System.out.println(“\n Rethrowing the exception at i =” + i); throw e; } } catch (ArithmeticException e) { System.out.println(“\n Recaught e”); } } } The above program gives the following output: Quotient = -12 Quotient = -24 Rethrowing the exception at i =2 Recaught e Quotient = 24 Quotient = 12 Quotient = 8 Exceptions 209 12.4 Creating Your Own Exceptions All the exceptions we have seen so far are defined inside the Java language. We have seen how to catch them and rethrow them. There may be programs that may create errors, which are not covered in Java’s predefined exceptions. If any such error occurs, it can be brought under the Throwable or its subclasses. This provides a mechanism by which a new exception can be created. The general form of creating an exception is: new ThrowableClass(); or new ThrowableClass(String s) The ThrowableClass can be Throwable or its subclasses. There are two constructors for Throwable and its subclasses. The first constructor needs no argument and the second constructor takes a string as an argument. The string is assigned as the name of the exception. For example, the following statements create a new exception called MyException with an argument and is thrown using throw clause. Throwable MyException = new Throwable(“Help Me”); throw MyException; The following program 12.8. creates a new exception, throws it and catches it. Program 12.8 // This program illustrates the creation of a new exception. class MyException { public static void main(String args []) { Throwable MyExpn = new Throwable(“Help Me”); try { System.out.println(“\n A new exception is thrown”); throw MyExpn; } catch (Throwable e) { System.out.println(“\n The exception is caught here. \n \n The exception is “ + e); } } } 210 Programming in JAVA2 The above program gives the following output: A new exception is thrown The exception is caught here. The exception is java.lang.Throwable: Help Me The following program 12.9 creates an Exception subclass named NewExp, creates an object of that type, throws it and catches it. Program 12.9 // This program creates subclass of Exception throws it // and catches it. class NewExp extends Exception { NewExp(String s) { System.out.println(“\n Untamed exception is thrown out:” + s); } public static void main(String args []) { NewExp ne = new NewExp(“Lion”); try { throw ne; } catch (Exception e) { System.out.println(“\n I caught that exception and tamed it : “ + e); } } } The above program gives the following output: Untamed exception is thrown out:Lion I caught that exception and tamed it : NewExp 12.5 Broadcasting that a Method Throws Exception When a method is developed for carrying out a task, it may generate various types of exceptions. Some of the exceptions generated cannot be handled by the method itself. Therefore, it is important to broadcast that the method is going to throw an exception, so that the caller of that method can handle the exception appropriately. Exceptions of type Error that cannot be handled at all and RuntimeException that could have been avoided by the Exceptions 211 programmer should not be broadcast. Only exceptions other than Error or RuntimeException can be broadcast. The broadcasting is done using the throws keyword. The broadcasting is made while declaring the method. The general form of broadcasting that a method throws an exception is: return-type methodname(parameter_list) throws Exception1, Exception2 { method_body } For example, the following method broadcasts two exceptions: static double readDouble() throws IOException, ParseException { . . . String s = br.readLine(); } In the above example, the method readDouble() announces that the method is likely to cause two exceptions, IOException and ParseException. The following program 12.10 illustrates how to broadcast that a method throws an exception. Program 12.10 // This program broadcasts that its method is going to // throw an exception. class Cal { int x, y; int Process(int a, int b) throws Exception { x = a; y = b; System.out.println(“\n I dont know what to do these numbers “ + a + “ and “ + b); throw new Exception(“AVAJ”); // return (a+b); This statement cannot be placed // after throw. Will give compile error. } } class Broadcast { public static void main(String args []) { 212 Programming in JAVA2 Cal cl = new Cal(); try { cl.Process(10, 25); } catch (Exception e) { System.out.println(“\n The thrown Excepion is: “ + e + “ \n\t and is caught in main”); System.out.println(“\n Sum of the two numbers is “ + (cl.x + cl.y)); } } } The above program gives the following output: I dont know what to do these numbers 10 and 25 The thrown Exception is: java.lang.Exception: AVAJ and is caught in main Sum of the two numbers is 35 12.6 The finally Block In a try...catch block, all statements will be executed, if no exception occurs. When an exception occurs, the statements placed in between the point of occurring of the exception and the end of the block will be skipped and the control looks for a matching catch block. In certain problems, it is essential to execute certain statements, like closing a file, irrespective of whether an exception occurs or not. Such essential statements are placed in the finally block. Program 12.11 illustrates the use of finally block. Program 12.11 // Program to illustrate the finally block. class Finally { public static void main(String args []) { int i, x, con = 2; for (i = 1; i < 4; i++) try { x = 25 / (con - i); System.out.println(“\n quot =” + x); } catch (ArithmeticException e) { System.out.println(“\n Divide by zero error Exceptions 213 for i =” + i); } finally { System.out.println(“\n Exception or no Exception this will be printed always”); } } } The above program gives the following result: quot =25 Exception or no Exception this will be printed always Divide by zero error for i =2 Exception or no Exception this will be printed always quot =-25 Exception or no Exception this will be printed always G The statements in a finally block are always executed, irrespective of whether an exception occurs or not. 12.7 Checked and Unchecked Exceptions Java developers have identified certain exceptions which must be made known to the programmer at the compile time itself. Such exceptions are listed and the compiler checks whether any of the listed exceptions occur in a program during compilation. Such exceptions are called checked exceptions. Exceptions that are not listed in the list are identified during runtime. Such exceptions are called unchecked exceptions. Only checked exceptions are to be broadcast in a throws clause. Table 12.1 gives some checked exceptions and table 12.2 gives some unchecked exceptions. Table 12.1 Some Checked Exceptions Exception 1. 2. ClassNotFoundException CloneNotSupportedException 3. 4. IllegalAccessException InterruptedException 5. NoSuchMethodException Cause for the Exception Class not found Trying to clone an object which has not implemented clonable interface Access to a class is refused One thread is interrupted by another thread. The referred method does not exist. 214 Programming in JAVA2 Table 12.2 Some Unchecked Exceptions Exception Cause for the Exception 1. 2. 3. 4. ArithmeticException ArrayIndexOutOfBoundsException ClassCastException IllegalArgumentException 5. 6. 7. NegativeArraySizeException NullPointerException NumberFormatException 8. StringOutOfBoundsException Arithmetic error Array index is beyond the bounds. Invalid cast Invalid arguments passed to a method Array with negative index Invalid use of null Incorrect conversion of string to a number Trying to access a string beyond its bounds More exceptions can be found in www.java.sun.com After reading this chapter, you should have learned the following: Ü What is an exception? Ü The types of exception Ü Establishing try...catch block Ü The use of throw and throws clause Ü Creating your own exception In the next chapter, you will learn about I/O classes. Exercise-12 I. Fill in the blanks 12.1. An abnormal condition occurring in a Java program is called _______. 12.2. The programmer avoidable errors are exceptions of type _____. 12.3. Exceptions arising out of memory and memory not enough are of the type _____. They are _____ be caught. 12.4. The codes inside the ________ block of an exception handling structure will be executed irrespective of whether an exception occurs or not. 12.5. When exceptions belonging to a superclass and subclass occur inside a try block, the class exception must be caught first. Exceptions 215 12.6. User-defined exceptions can be created using ________ class. 12.7. When a method cannot handle an Exception that is generated in it, the method must declare it using the keyword _________ . 12.8. Exceptions that are identified during compile time are called ______ exception. II. Write Java programs for the following: 12.9. It is required to compute the following expression: x f = x2 – y2 for different values of x = 1.0 to 5.0 in steps of 0.5 and y = 0 to 4.0 in steps of 0.5. Write a Java program to compute the values of f by including an appropriate exception handling block when x = y. 12.10. A mark list containing register number and marks for a subject is given. The marks and register number are to be read. If the marks are < 0, user-defined IllegalMarkException is thrown out and handled with the message “Illegal Mark”. For all valid marks, the candidate will be declared as “PASS” if the marks are equal to or greater than 40, otherwise it willl be declared as “FAIL”. IllegalMarkException by extending the Exception. MarkProcess to process the mark. Write a class called Write another class In the MarkProcess class write a Validation (int mark) method, which if marks are <0, will throw an Exception of type IllegalMarkException. Result() which will declare the result. Write another method Write a class containing main method that will create an object of type MarkProcess and call the methods in it to declare the result. 12.11. Write a class to sort the given set of n integers in descending order. Include a try block to locate the array index out of bounds exception and catch it. * * * * * * 216 Programming in JAVA2 BLANK 217 Chapter 13 INPUT AND OUTPUT CLASSES In this chapter, you will learn about input/output handling process. Java treats all data as a stream of bytes or characters. A large number of classes to deal with disk files, memory and source/destination independent process are available in Java. Some of the important classes are explained in this chapter. 13.1 I/O Streams Java’s input/output(I/O) operations are intricate, complex to understand, but more flexible and powerful. Java developers have focused their attention for non-keyboard oriented data handling. They wanted to perform platform independent I/O operations. Hence, the complexity. All I/O operations in Java are stream-based. All the data is treated as a stream of bytes or characters. The streams start from or end with files, memory, monitor, keyboard and network sockets. The sources from where data are read from is called input stream. The sink to which the data are written into is called output stream. Since Java’s two-byte, unicode characters are different from the conventional single-byte characters, Java has two types of streams, byte stream and character stream (Fig. 13.1.). A character stream deals with unicode characters. Each stream has its own input stream and output stream classes. I/O operations of byte stream are handled by two abstract classes InputStream and 218 Programming in JAVA2 OutputStream. Similarly, the character stream has Reader and Writer abstract classes. The I/O related classes are available in java.io package and are to be imported into the programs which are using I/O classes. byte stream Data Source Data Sink character stream Data Sink Data Source Fig.13.1 The Streams in Java I/O All the streams, InputStream, OutputStream, Writer and Reader, are opened automatically when their objects are created. Similarly, if a stream object is not in use any more, the stream is closed automatically. Hence, explicit close statement is not a must in a Java program. G Data used in Java are handled in two streams, byte stream and character stream. There are several classes in java.io package and they are given in table 13.1. Table 13.1 Classes Contained in java.io Package BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter DataInputStream DataOutputStream File FileDescriptor FileInputStream FileOutputStream FilePermission FileReader FileWriter FilterInputStream FilterOutputStream FilterReader FilterWriter Input and Output Classes InputStream InputStreamReader ObjectInputStream ObjectInputStream.GetField ObjectOutputStream 219 LineNumberReader ObjectOutputStream.Putfield ObjectStreamClass ObjectStreamField OutputStream OutputStreamWriter PipedInputStream PipedOutputStream PipedReader PipedWriter PrintStream PrintWriter PushbackInputStream PushbackReader RandomAccessFile Reader SequenceInputStream SerializablePermission StreamTokenizer StringReader StringWriter Writer To deal with all classes and the methods in them in detail will be voluminous. Therefore, most commonly used classes are explained in the following sections. Once the knowledge of using a stream is understood, any other stream can be handled easily. For simple console based I/O, Console, Scanner and Formatter classes are added in JDK5 onwards. They are discussed in Chapter 24. 13.2 The File Class The File class is used only to know the details about a file. It cannot be used to read or write bytes into a file. It helps to study a file before handling it. The File class has the following constructors: i) File(String dirpath) ii) File(String dirpath, String filename) iii) File(File object, String filename) where, dirpath is directory path, filename is the name of the file and object is File type object. Some of the methods defined in File class are given in table 13.2. Table 13.2 Some of the Methods Defined in File Class Method Purpose of the Method 1. String getName() Returns the name of the directory or file of the invoking object 2. String getPath() Returns the path of the invoking object 3. String getAbsolutePath() Returns the absolute path of the invoking object 4. String getParent() Returns the name of the parent directory of the invoking object 220 Programming in JAVA2 5. boolean exists() Returns true if the dir/file object exists, otherwise false 6. boolean canWrite() Returns true if the File object is writable, otherwise false 7. boolean canRead() Returns true if the File object is readable, otherwise false 8. boolean isDirectory() Returns true if the invoking object is a directory, otherwise false 9. boolean isFile() Returns true if the invoking object is a file, otherwise false 10. boolean isHidden() Returns true if the File object is hidden, otherwise false 11. long lastModified() Returns a long value representing the last modified date in milliseconds 12. long length() Returns a long value representing the size of the file in bytes 13. boolean renameTo (File newname) Renames the File object with the new name; returns true upon successful renaming, otherwise false 14. boolean delete() Deletes the file of the invoking object; returns true on successful deletion, otherwise false 15. boolean setReadOnly() Sets the file of the invoking object to read only mode; returns true on successful setting, otherwise false 16. void deleteOnExit() Deletes the file of the invoking object upon the termination of Java Virtual Machine 17. String[] list() Lists the files in the directory of the invoking object and returns a String array 18. boolean setWritable(boolean writable, boolean owneronly) Sets the owner’s or everybody’s write permission for this pathname. 19. boolean setWritable(boolean writable) Sets the owner’s write permission for this pathname. Input and Output Classes 221 20. boolean setReadable(boolean readable boolean owneronly) Sets the owner’s or everybody’s read permission for this pathname. 21. boolean setReadable(boolean readable) Sets the owner’s read permission for this pathname. 22. boolean setExecutable(boolean Sets the owner’s or everybody’s executable, boolean owneronly)execute permission for this pathname. 23. boolean setExecutable(boolean Sets the owner’s execute permission executable) for this pathname. 24. boolean canExecute() Tests whether the application can execute the file denoted by this pathname. 25. long getTotalSpace() Returns the size of the partition specified by this partitionname. 26. long getFreeSpace() Returns the number of unallocated bytes in the partition specified by this partitionname. 27. long getUsableSpace() Returns the number of bytes available to this virtual machine in the partition specified by this partitionname. The following program 13.1 gives the use of some of the methods in file Class: Program 13.1 /*This program illustrates some of the methods defined in File class. Requires jdk1.6 or higher. somasundaramk@yahoo.com */ import java.io.*; class FileDemo{ public static void main(String args[]){ File partd = new File("d:"); File fpath = new File("d:/jdk1.6/bin/nchp13"); File fname = new File(fpath,"Isreader.java"); System.out.println("Total space avilable in d :" +partd.getTotalSpace()); System.out.println("Free space avilable in d :" +partd.getFreeSpace()); System.out.println("Usable space avilable in d :" +partd.getUsableSpace()); System.out.println("Path of the dir :" +fname.getPath()); 222 Programming in JAVA2 System.out.println("Name of the file :" +fname.getName()); System.out.println("Size of the file :" +fname.length()); System.out.println("Does "+fname.getName() +" is executable? "+fname.canExecute()); System.out.println("Does "+fpath.getName() +" is a directory? "+ fpath.isDirectory()); System.out.println("Does "+fname.getName() +" is a file? "+fname.isFile()); System.out.println("Does the file "+fname.getName() +" exists ? "+fname.exists()); System.out.println("Does the directory " +fpath.getName() +" exists ? "+fpath.exists()); System.out.println("Modified on" + fpath.lastModified()); String dirlist[] = fpath.list(); int n= dirlist.length; System.out.println("\nDirectory of " +fpath.getName()+"\n"); System.out.println("Total files in this directory is:" +n); System.out.println("The first 5 files are:"); for(int i = 0;i<5;i++) System.out.println(dirlist[i]); File nname = new File("Myname.java"); fname.renameTo(nname); System.out.println("Does the file "+fname.getName() +" exists ? "+fname.exists()); } } The above program gives the following output: Total space avilable in d :19025039360 Free space avilable in d :2586697728 Usable space avilable in d :2586697728 Path of the dir :d:\jdk1.6\bin\nchp13\Isreader.java Name of the file :Isreader.java Size of the file :1024 Does Isreader.java is executable? true Does nchp13 is a directory? true Does Isreader.java is a file? true Does the file Isreader.java exists ? true Does the directory nchp13 exists ? true Modified on 1173021947312 Directory of nchp13 Total files in this directory is :134 The first 5 files are: Input and Output Classes 223 adrs.dat awt Biodata.class buf1.dat Buffrdr.class Does the file Isreader.java exists ? false G A File class is used to study the properties of a file. This class can not be used to read data from a file or write data into a file. 13.3 Byte Stream In this, stream data are accessed as a sequence of bytes. All types other than character or text are dealt in this stream. This stream, as mentioned earlier, has two abstract classes, InputStream and OutputStream. Since InputStream and OutputStream are abstract classes, objects of this type cannot be created. However, object references of this type can be declared. These two classes have abstract and concrete methods. The abstract methods are implemented in the subclasses. The class hierarchy in Inputstream is given in fig. 13.2 and for OutputStream in fig. 13.3. InputStream ByteArrayInputStream FileInputStream PipedInputStream FilterInputStream SequenceInputStream ObjectInputStream BufferedInputStream CheckedInputStream PushbackInputStream DataInputStream Fig.13.2 Class Hierarchy in InputStream OutputStream ByteArrayOutputStream FileOutputStream FilterOutputStream PipedOutputStream ObjectOutputStream BufferedOutputStream CheckedOutputStream PrintStream DataOutputStream Fig.13.3 Class Hierarchy in OutputStream 224 Programming in JAVA2 13.3.1 InputStream The InputStream has methods given in table 13.3. These methods are used to input bytes from input stream. All the methods can throw IOException. Table 13.3 Methods Defined in InputStream Method Purpose of the Method 1. abstract int read() Reads one byte and returns an int representation of that byte; returns -1 at the end of the stream 2. int read(byte b[]) Reads into an array of bytes b and returns the number of bytes read; reads a maximum of b.length bytes, returns -1 at the end of the stream 3. int read(byte b[], int off, int len) Reads len number of bytes into the byte array b, starting at b[off] and returns the number of bytes read; returns -1 at the end of the stream 4. int available() Returns the number of bytes available for reading 5. void close() Closes the input stream 6. void mark(int marklen) Puts a mark at the current position and remembers it until marklen bytes are read 7. boolean markSupported() Returns true if the stream supports mark() 8. void reset() The read control is reset to the previous set mark. Subsequent read() will reread these bytes. 9. long skip(long m) Skips m bytes of the input stream and returns the actual number of bytes skipped 13.3.2 OutputStream The abstract class OutputStream has methods given in table 13.4. These methods are used to send bytes to the output stream. All the methods can throw IOException. Input and Output Classes 225 Table 13.4 Methods Defined in OutputStream Method Purpose of the Method 1. abstract void write(int b) Writes a single byte b to an output stream 2. void write(byte b[]) Writes an array of byte b to an output stream 3. void write(byte b[], int off, int len) Writes len number of bytes starting from b [off] to an output stream 4. void flush() Flushes the output buffer; that is, it sends any buffered byte to its destination 5. void close() Closes the output stream 13.4 Disk File Handling The two abstract classes, InputStream and OutputStream, have a number of concrete subclasses, which implement the abstract methods. Only objects of these subclasses can be created for input stream and output stream. FileInputStream and FileOutputStream are subclasses of InputStream and OutputStream respectively. These two are used for handling disk files. 13.4.1 FileInputStream This class is used to read bytes from a disk file. The FileInputStream class has the following constructors: i) FileInputStream(String filename) Creates a file input stream, using the file mentioned in filename ii) FileInputStream(File fobject) Creates a file input stream, using the information given in the Object fobject Both the constructors can throw FileNotFoundException. All the superclass methods given in table 13.2, except mark(), reset() and close(), are overriden by this class. Methods in this stream can only read a byte or an array of bytes. Therefore, only byte-oriented data can be handled in this stream. The following program 13.2 shows the use of FileInputStream. program reads a byte at a time from a file as int and prints it out as such. This 226 Programming in JAVA2 Program 13.2 // This program illustrates the use of FileInputStream. import java.io.*; class Fileinput1 { public static void main(String args []) { try { FileInputStream fis = new FileInputStream(“c:/ jdk1.2.1/bin/chp13/test.dat”); int c; while ((c = fis.read()) != -1) System.out.print(c); fis.close(); } catch (FileNotFoundException e) { System.out.println(“File not found”); } catch (IOException e) { System.out.println(“File read error”); } } } The above program gives the following output: 65326632671310495051325152533254555613104848493255545 43257565013105051325351325455131049503253503250521310 It can be seen from the above result, the (ASCII) bytes are read as int and printed as int. To get visually readable bytes they are to be cast as char and printed out as ASCII values (65 for A,49 for 1, 32 for blank, 1310 for new line, etc). Modifying the print statement in the above program as: System.out.print((char)c); the following output is obtained: ABC 123 345 678 001 766 982 23 53 67 12 52 24 Input and Output Classes 227 13.4.2 FileOutputStream This class is used to write bytes into a disk file. class has the following constructors: The FileOutputStream i) FileOutputStream(String filename) Creates a new file output stream by creating a new file with name filename; if a file already exists with that name, it will be deleted. ii) FileOutputStream(File fobject) Creates a new file output stream by creating a new file using the information given in the object fobject iii) FileOutputStream(String filename, boolean append) Creates a new file output stream using the file filename; is true, the data is appended at the end of the file. if append All the constructors can throw an IOException or a SecurityException. The following program 13.3 illustrates the use of FileOutputStream. This program copies an existing file to a new file. It then reads the new file and prints out the int bytes as char. Program 13.3 // This program illustrates the FileOutputStream. import java.io.*; class Fileoutput { public static void main(String args []) { File fin = new File(“test.dat”); File fot = new File(“out.dat”); System.out.println(“The size of file test.dat is “ + fin.length() + “ bytes”); try { FileInputStream fis = new FileInputStream(fin); FileOutputStream fos = new FileOutputStream(fot); int c; System.out.println(“\nThe file test.dat is copied to out.dat”); while ((c = fis.read()) != -1) fos.write(c); fis.close(); FileInputStream fis1 = new FileInputStream(fot); System.out.println(“\nThe following bytes are read from out.dat \n”); 228 Programming in JAVA2 int count = 0; while ((c = fis1.read()) != -1) { System.out.print((char)c); count++; } System.out.println(“\nThe size of file out.dat is “ + count + “ bytes”); fis1.close(); } catch (FileNotFoundException e) { System.out.println(“\n File not found “); } catch (IOException e) { System.out.println(“\n I/O problem “); } } } The above program gives the following output: The size of file test.dat is 53 bytes The file test.dat is copied to out.dat The following bytes are read from out.dat ABC 123 345 678 001 766 982 23 53 67 12 52 24 The size of file out.dat is 53 bytes G Disk files are handled by FileInputStream FileOutputStream classes. Both are byte stream. and 13.5 Memory Handling Data stored in memory are handled ByteArrayInputStream and ByteArrayOutputStream. by two streams, 13.5.1 ByteArrayInputStream This class is used to read bytes from a memory. Objects of this class are used to create input stream with memory buffers as data source. All the methods of the InputStream are either inherited or overridden in this class. The constructors for this class are : Input and Output Classes i) ByteArrayInputStream(byte b[]) Creates a new byte array input stream with name b, bytes are read out 229 from which the ii) ByteArrayInputStream(byte b[], int off, int len) Creates a new byte array input stream with name b, from which bytes will be read out starting at b[off], a maximum of len bytes The following program 13.4. illustrates the use of ByteArrayInputStream. This program also shows how the byte buffers are handled as byte array. Program 13.4 /* This program illustrate the use of ByteArrayInputStream somasundaramk@yahoo.com */ import java.io.*; class Bytearray{ public static void main(String args[]){ File fin = new File("test.dat"); int count =(int) fin.length(); byte mem[] = new byte[count]; ByteArrayInputStream bais= new ByteArrayInputStream(mem); try{ FileInputStream fis= new FileInputStream(fin); fis.read(mem); System.out.println("\n Size of the file read into the memory buffer is "+count + " bytes"); System.out.println("\n This memory is read like a file and printed below\n"); int c; while(( c=bais.read())!= -1) System.out.print((char)c); fis.close(); bais.close(); }catch(FileNotFoundException e){ System.out.println("\n File not found"); }catch(IOException e){ System.out.println("\n IO error"); } System.out.println("\n Memory is treated as an array and printed in the conventional method\n"); for(int i=0;i<count;System.out.print((char)mem[i++])); } } The above program gives the following output: 230 Programming in JAVA2 Size of the file read into the memory buffer is 53 bytes This memory is read like a file and printed below ABC 123 345 678 001 766 982 23 53 67 12 52 24 Memory is treated as an array and printed in the conventional method ABC 123 345 678 001 766 982 23 53 67 12 52 24 13.5.2 ByteArrayOutputStream This class is used to write bytes into memory. Objects of this class are used to create output stream with memory buffers as data sink. This has all the methods of the superclass OutputStream. The constructors for this class are : i) ByteArrayOutputStream() Creates a new byte array output stream with an initial memory buffer of capacity 32 bytes and grows with need ii) ByteArrayOutputStream(int len) Creates a new byte array output stream with an initial memory buffer of capacity len bytes; will throw IllegalArgumentException, if len is negative The following program 13.5 shows the use of ByteArrayOutputStream: Program 13.5 // This program illustrates the use of ByteArrayOutputStream. import java.io.*; class Bytearrayout { public static void main(String args []) { File fin = new File(“test.dat”); int count = (int)fin.length(); System.out.println(“\nA test file of size “ + count +“ bytes is sent to memory buffer”); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { Input and Output Classes 231 FileInputStream fis = new FileInputStream(fin); int c; while ((c = fis.read()) != -1) bos.write(c); fis.close(); bos.close(); } catch (FileNotFoundException e) { System.out.println(“\n File not found”); } catch (IOException e) { System.out.println(“\n IO error”); } System.out.print(“\nThe content of the memory buffer is \n “); System.out.print(bos.toString()); } } The above program gives the following output: A test file of size 53 bytes is sent to memory buffer The content of the memory buffer is ABC 123 345 678 001 766 982 23 53 67 12 52 24 G 13.6 Memory-oriented I/O ByteArrayInputStream Both are byte stream. operations are handled in and ByteArrayOutputstream. Filtered Byte Streams Each stream in Java provides methods to access the data in different forms. The basic byte streams access the data in byte form. The raw bytes cannot be used for any useful purpose. For converting bytes to useful forms such as char, string, int, etc., Java has several streams. These streams work on other streams and convert between byte to useful form or vice versa. Such streams that can take other stream as argument are called filtered streams. The Java has FilterInputStream and FilterOutputStream. 232 Programming in JAVA2 There are several filtered streams which can work only on other streams. In many practical situations, only filtered streams are useful. In the following sections some of the filtered streams are discussed: char, string, int… Filter Inputstream byte Input Stream Data Source a. FilterInputStream char, string, int… Filter Outputstream byte Output Stream Data Sink b. FilterOutputStream Fig.13.4 Filtered Byte Streams 13.6.1 BufferedInputStream This is a subclass of FilterInputStream. This class is used to increase the efficiency of reading bytes from an input stream. Fetching a byte and sending it to the destination one after another is a time-consuming process. Instead, bytes can be read and stored in a buffer memory before sending it to the destination. Once the buffer is full, the bytes can be sent to the destination. This class has the following constructors: i) BufferedInputStream(InputStream ins) Creates a new buffered input stream for the bytes in the underlying InputStream ins ii) BufferedInputStream(InputStream ins, int size) Creates a new buffered input stream with a buffer capacity of size bytes for the bytes in the underlying InputStream ins BufferedInputStream has all the methods of InputStream. following program 13.6 illustrates the use of BufferedInputStream: Program 13.6 // This program illustrates the use of BufferedInputStream. import java.io.*; class Bufinput1 { public static void main(String args []) { The Input and Output Classes 233 File f = new File(“buf1.dat”); try { BufferedInputStream bufins = new BufferedInputStream(new FileInputStream(f)); int len = bufins.available(); System.out.println(“Bytes available for reading:“ + len); System.out.println(“\nIs this stream mark supported? : “ + bufins.markSupported()); System.out.println(“\nThe whole content of a file is given below \n”); int n; while ((n = bufins.read()) != -1) { System.out.print((char)n); } bufins = new BufferedInputStream(new FileInputStream(f));//stream is opened again System.out.println(“\nThe file is again read and the mark & reset methods are called \n”); char c; int i = 0; while ((n = bufins.read()) != -1) { c = (char)n; i++; if (i == len / 4) bufins.mark(64); if (i == (len / 4 + 50)) { bufins.reset(); System.out.println(“\n\nControl goes back to the marked position \n “); } System.out.print(c); } bufins.close(); } catch (FileNotFoundException e) { System.out.println(“File not found “); } catch (IOException e) { System.out.println(“IO error”); } } } 234 Programming in JAVA2 The above program gives the following output: Bytes available for reading : 337 Is this stream mark supported? : true The whole content of a file is given below: This is a demo text for testing the BufferedInputStream. The mark( len) method makes a mark at the current position and remembers it till another len number of bytes are read. When the reset method is invoked, the control goes back to the marked position. For further read , the bytes are re-read again. See this for yourself. The file is again read and the mark & reset methods are called This is a demo text for testing the BufferedInputStream. The mark( len) method makes a mark at the current position and remembers Control goes back to the marked position is a mark at the current position and remembers it till another len number of bytes are read. When the reset method is invoked, the control goes back to the marked position. For further read , the bytes are re-read again. See this for yourself. 13.6.2 BufferedOutputStream This is a subclass of FilterOutputStream. This class is used to send buffered bytes to an underlying output stream in an efficient way. This class has all the methods of OutputStream. The constructors for this class are : i) BufferedOutputStream(OutputStream ous) Creates a new buffered output stream for the bytes meant for the underlying OutputStream ous with a buffer size of 12 bytes ii) BufferedOutputStream(OutputStream ous, int size) Creates a new output stream for the bytes meant for the underlying OutputStream ous with a buffer size of size bytes 13.6.3 DataInputStream It is a subclass of FilterInputStream. This class helps to convert the bytes from an underlying stream to basic types char, byte, int, etc. Constructor for this class is : DataInputStream(Inputstream ins) Creates a new data input stream for the bytes in the underlying InputStream ins The methods defined in this class are given in table 13.5. methods throw IOException. All the Input and Output Classes Table 13.5 235 Methods Defined in DataInputStream Method Purpose of the Method 1. int read(byte[] b) Reads bytes into the byte array b returns the number of bytes read; returns -1 at the end of the stream 2. int read(byte[] b, int off, int len) Reads bytes into the byte array b starting at b[off], len number of bytes; returns the total number of bytes read; returns -1 at the end of the stream 3. void readFully(byte[] b) reads bytes into the byte array b; the maximum bytes read being the capacity of the byte array 4. void readFully (byte[] b, int off, int len) Reads bytes into b, starting at b[off], len number of bytes 5. int skipBytes(int n) Skips n bytes and returns the actual number of bytes skipped 6. boolean readBoolean() Reads a boolean value from the input stream 7. byte readByte() Reads an 8-bit signed byte from the input stream 8. int readUnsignedByte() Reads an 8-bit unsigned byte from the input stream 9. short readShort() Reads two bytes from the input stream and treats it as a 16-bit int 10. int readUnsignedShort() Reads two bytes from the input stream and treat it as a 16-bit unsigned integer 11. char readInt() Reads two bytes from the input stream and treats its as a 16-bit unicode character 12. int readInt() Reads four bytes from the input stream and treats it as an int 13. long readLong() Reads 8 bytes from the input stream and treats it as a long 236 Programming in JAVA2 14. float readFloat() Reads 4 bytes from the input stream and treats it as a float 15. double readDouble() Reads 8 bytes from the input stream and treats it as a double The following program 13.7 illustrates the use of DataInputStream. Program 13.7 // This program illustrates the use of DataInputStream. import java.io.*; class Datainput1 { public static void main(String args []) { File fin = new File(“datainput1.dat”); int size = (int)fin.length(); byte b [] = new byte[size]; byte bt [] = new byte[size]; try { DataInputStream dins = new DataInputStream(new FileInputStream(fin)); System.out.println(“\nPrinted using readFully(b) \n”); dins.readFully(b); for (int i = 0; i < size; System.out.print((char)b[i++])); dins.close(); dins = new DataInputStream(new FileInputStream(fin)); System.out.println(“\nPrinted using readFully(b,off,len) \n”); dins.readFully(bt, 10, 40); for (int i = 0; i < size; System.out.print((char)bt[i++])); dins.close(); } catch (FileNotFoundException e) { System.out.println(“File not found”); } catch (IOException e) { System.out.println(“IO Error”); } } } Input and Output Classes 237 The above program gives the following output: Printed using readFully(b) ABC 123 345 678 001 766 982 23 53 67 12 52 24 Printed using readFully(b,off,len) ABC 123 345 678 001 766 982 23 53 6 Most of the methods that convert bytes to basic type like char, int, long, float, double, etc. give values that are not in human readable form, but are efficient for processing. 13.6.4 DataOutputStream It is a subclass of FilterOutputStream. The methods in this class help to convert the basic types to bytes and pass it to an underlying output stream. The write methods in this class help to create an output stream, which can be read by the methods in DataInputStreams. The data written to the output stream are not in a human readable form. The constructor in this class is: DataOutputStream(OutputStream ous) Creates a new data output stream to write data to an underlying output stream ous Some of the methods defined in DataOutputStream are given in table 13.6. All the methods throw IOException. Table 13.6 Method Methods in DataOutputStream Class All Methods Throw IOException Purpose of the Method 1. void write(int b) Writes the lower 8 bits underlying output stream of b to the 2. void write(byte bf[], int off, int len) Writes len bytes from the byte array bf, starting at bf[off] to the underlying output stream 238 Programming in JAVA2 3. void flush() Sends the buffered bytes to the output stream 4. void writeBoolean(boolean b) Writes the boolean value b to the underlying output stream as 1 byte value 5. void writeByte(int in) Writes the int value as byte value to the underlying stream 6. void writeShort(int in) Writes a short to the underlying output stream as two bytes; the high byte is written first. 7. void writeChar(int in) Writes a char as 2-byte value to the underlying stream; the high byte is written first. 8. void writeInt(int in) Writes an int as 4 bytes to the underlying stream; the high byte is written first. 9. void writeLong(long ln) Writes a long as 8 bytes to the underlying stream; the high bytes are written first. 10. void writeFloat(float f) Converts the float to an int using a special method and writes the int as 4 bytes to the underlying stream; the high byte is written first. 11. void writeDouble(double d) Converts the double to a long using a special method and writes the long as 8 bytes to the underlying output stream; the high byte is written first. 12. void writeBytes(String s) Writes the String s as a sequence of bytes to the underlying output stream after discarding its high 8 bits 13. void writeChars(String s) Writes the String s as a sequence of characters to the underlying output stream 13.7 SequenceInputStream When there are several input streams from which data is to be read, the SequenceInputStream class is used. The SequenceInputStream class has the following constructors: Input and Output Classes 239 i) SequenceInputStream(InputStream inps1, InputStream inps2) Creates a new SequenceInputstream; first it reads data from inputstream inps1 until it is over, then switches to input stream inps2 ii) SequenceInputStream(Enumeration Enumstream) Creates a new SequenceInputStream; it reads from Enumeration streams listed in Enumstream It has methods of the InputStream. The following program 13.8 shows the use of SequenceInputStream: Program 13.8 // This program illustrates the use of SequenceInputStream. import java.io.*; class Sequenceinput { public static void main(String args []) { try { FileInputStream fis1 = new FileInputStream(“c:/ jdk1.2.1/bin/chp13/test1.dat”); FileInputStream fis2 = new FileInputStream(“c:/ jdk1.2.1/bin/chp13/test2.dat”); SequenceInputStream sins = new SequenceInputStream(fis1, fis2); int c; while ((c = sins.read()) != -1) System.out.print((char)c); sins.close(); } catch (FileNotFoundException e) { System.out.println(“File not found”); } catch (IOException e) { System.out.println(“File read error”); } } } The above program gives the following output: This data is taken from first file. 145 677 983 abcde 123.75 240 Programming in JAVA2 This data is taken from second file. 333 883 pq rs tuv 1357 13.8 ObjectOutputStream This is a subclass of OutputStream. This class helps to write objects to an output stream as series of bytes. This is one of the convenient ways of handling data assigned to instance variables of an object. One can create an object, write it to an ObjectOutputStream, which can be read back from an ObjectInputStream. Objects of any type can be written to an object output stream, but they should be read back in the same order. Even objects of basic types, like integer and long, can be written to an object output stream. When an object is written to an output stream, all the class informations are also packed with the data, so that when the data is read as object, all embedded class information is utilized to reconstruct the object. Even image objects can be written to an outputstream using this stream. In order to write an object to an output stream, Java provides a mechanism to convert the object to bytes. This process of conversion of an object to a byte is called serialization. Java has an interface called Serializable. Any class whose object is to be serialized for ObjectOutputStream has to implement this interface. The interface Serializable has no methods. byte Object to ObjectOutputStream Fig. 13.5. Serialization process Fig.13.5 Serialization Process Therefore, the class whose object is to be sent to the ObjectOutputStream, has to simply state that it is implementing Serializable. Constructor for this class is: ObjectOutputStream(OutputStream, ous) Creates a new ObjectOutputStream that writes to an underlying output stream OutputStream ous; can throw IOException ObjectOutputStream is also useful in Remote Method Invocation (RMI). The ObjectOutputStream implements an interface ObjectOutput. Some of the methods in ObjectOutputStream are given in table 13.7. Input and Output Classes Table 13.7 241 Some of the Methods in ObjectOutputStream All Methods Throw IOExceptions Method Purpose of the Method 1. void writeObject(object ob) Writes the specified ObjectOutputStream object to the 2. void write(int b) Writes a single byte to the stream; byte written is low-byte of b. the 3. void write(byte[] b) Writes an array of bytes to the stream 4. void write(byte[] b, int off int len) Writes a subrange of array of bytes of b, starting at b[off], len bytes to the stream 5. void drain() Drains any buffered data to the stream 6. void close() Closes the stream 7. void writeBoolean(boolean b) Writes a boolean to the stream 8. void writeByte(int in) Writes a byte to the stream; the byte written is low-byte of in. 9. void writeShort(int in) Writes a 16-bit short to the stream 10. void writeChar(int ch) Writes a 16-bit char to the stream 11. void writeInt(int in) Writes a 32-bit int to the stream 12. void writeLong(long ln) Writes a 64-bit long to the stream 13. void writeFloat(float fl) Writes a 32-bit float to the stream 14. void writeDouble(double db) Writes a 64-bit double to the stream 15. void writeBytes(String s) Writes String s as a sequence of bytes to the stream 16. void writeChars(String s) Writes String s as a sequence of chars 17. void writeUTF(String s) Writes the String s in UTF format Program 13.9 illustrates the use of ObjectOutputStream. Objects are created from the class Biodata and written to an object file. 242 Programming in JAVA2 Program 13.9 // This program illustrates the use of ObjectOutputStream. import java.io.*; class Biodata implements Serializable { String name; int age; String adrs1; String adrs2; Biodata(String nm, int ag, String ad1, String ad2) { name = nm; age = ag; adrs1 = ad1; adrs2 = ad2; } void Printbio() { System.out.println(“Name : “ + name); System.out.println(“Age : “ + age); System.out.println(“Place : “ + adrs1); System.out.println(“City : “ + adrs2); } } class Objectoutput1 { public static void main(String args []) { try { File f = new File(“obj.dat”); FileOutputStream fos = new FileOutputStream(“obj1.dat”); ObjectOutputStream objos = new ObjectOutputStream(fos); Biodata soms = new Biodata(“K.Somasundaram”, 50, “Dept of Comp. Science”, “Gandhigram624302”); Biodata mag = new Biodata(“S.Magesh”, 12, “3rd Street,Thirunagar”, “Gandhigram 624302”); Biodata kum = new Biodata(“S.P.Kumar”, 17, “JE College”, “Chennai “); Biodata gom = new Biodata(“S.Gomathi”, 35, “3rd Street,Thirunagar”, “Gandhigram 624302”); System.out.println(“\n Objects of the following type are sent to Object file\n”); soms.Printbio(); Input and Output Classes 243 objos.writeObject(soms); objos.writeObject(mag); objos.writeObject(kum); objos.writeObject(gom); objos.flush(); objos.close(); } catch (FileNotFoundException e) { System.out.println(“File not found”); } catch (IOException e) { System.out.println(“IO error”); } } } The above program gives the following output: Objects of the following type are sent to Object file Name Age Place City : K.Somasundaram : 50 : Dept of Comp. Science : Gandhigram 624302 The following program 13.10 shows the use of methods writeInt and writeUTF in ObjectOutputStream. Program 13.10 // This program illustrates the use of ObjectOutputStream. import java.io.*; class Biodata implements Serializable { String name; int age; String adrs1; String adrs2; Biodata(String nm, int ag, String ad1, String ad2) { name = nm; age = ag; adrs1 = ad1; adrs2 = ad2; } 244 Programming in JAVA2 void Printbio() { System.out.println(“Name : “ + name); System.out.println(“Age : “ + age); System.out.println(“Place : “ + adrs1); System.out.println(“City : “ + adrs2); } } class Objectoutput2 { public static void main(String args []) { try { File f = new File(“obj.dat”); FileOutputStream fos = new FileOutputStream(“obj2.dat”); ObjectOutputStream objos = new ObjectOutputStream(fos); Biodata soms = new Biodata(“K.Somasundaram”, 50, “Dept of Comp. Science”, “Gandhigram 624302”); Biodata mag = new Biodata(“S.Magesh”, 12, “3rd Street,Thirunagar”, “Gandhigram 624302”); System.out.println(“\n Objects of the following type are sent to Object file\n”); soms.Printbio(); objos.writeUTF(soms.name); objos.writeInt(soms.age); objos.writeUTF(soms.adrs1); objos.writeUTF(soms.adrs2); objos.writeUTF(mag.name); objos.writeInt(mag.age); objos.writeUTF(mag.adrs1); objos.writeUTF(mag.adrs2); objos.flush(); objos.close(); } catch (FileNotFoundException e) { System.out.println(“File not found”); } catch (IOException e) { System.out.println(“IO error”); } } } Input and Output Classes 245 The above program gives the following output: Objects of the following type are sent to Object file Name Age Place City G : K.Somasundaram : 50 : Dept of Comp. Science : Gandhigram 624302 Objects can be stored as bytes in a file using ObjectOutputStream. To do this, the interface Serializable is to be implemented. 13.9 ObjectInputStream It is a subclass of Inputstream and implements the interface ObjectInput. Data sources created in ObjectOutputStream can be read back in the ObjectInputStream. In this stream, deserialization is done. That is, the data are read from the ObjectInputStream and objects are reconstructed from bytes. bytes Object from ObjectInputStream Fig. 13.6. Object deserialization Fig.13.6 Object Deserialization Only objects that support the Serializable interface can be read from the stream. For reading in an object a no-argument constructor for that class is to be created. When an object is read from the ObjectInputStream, the instance variables of that object are automatically assigned the values. The constructor for the ObjectInputStream is : ObjectInputStream(InputStream, in) Creates a new object inputstream that reads bytes from the specified InputStream in Methods defined in ObjectInputStream are given in table 13.8. 246 Programming in JAVA2 Table 13.8 Methods Defined in ObjectInputStream All Methods Can Throw IOException Method Purpose of the Method 1. Object readObject() Reads an object from the stream; objects referenced by this object are reconstructed. 2. int read() Reads a byte of data; returns -1 at the end of the stream 3. int readByte(byte[] b, int off, int len) Reads bytes from the stream into byte array starting at b[off] len bytes; returns the actual number of bytes read or -1 when the end of the stream is reached 4. int available() Returns the number of bytes that can be read from the stream 5. void close() Closes the input stream 6. boolean readBoolean() Reads in a boolean 7. byte readByte() Reads an 8-bit byte 8. int readUnsignedByte() Reads an unsigned 8-bit byte 9. short readShort() Reads a 16-bit short 10. int readUnsignedShort() Reads an unsigned 16-bit short 11. char readChar() Reads a 16-bit char 12. int readInt() Reads a 32-bit int 13. float readFloat() Reads a 32-bit float 14. double readDouble() Reads a 64-bit double 15. void readFully(byte[] b) Reads bytes into b until all bytes are read 16. void readFully (byte[] b, int off, int len) Reads bytes into b, starting at b[off], len number of bytes 17. int skipBytes(int len) Skips len number of bytes; returns the actual number of bytes skipped 18. String readUTF() Reads a UTF format String Input and Output Classes 247 Program 13.11 illustrates the ObjectInputStream. Here, the object bytes are read and reconstructed to form an object. Notice the declaration of the noargument constructor. It is essential to declare a no-argument constructor. The bytes from the ObjectInputStream are automatically reconstructed to the actual object state. Program 13.11 // This program illustrates the use of ObjectInputStream. import java.io.*; class Biodata implements Serializable { String name; int age; String adrs1; String adrs2; Biodata() { } Biodata(String nm, int ag, String ad1, String ad2) { name = nm; age = ag; adrs1 = ad1; adrs2 = ad2; } void Printbio() { System.out.println(“\nName : “ + name); System.out.println(“Age : “ + age); System.out.println(“Place : “ + adrs1); System.out.println(“City : “ + adrs2); } } class Objectinput1 { public static void main(String args []) { Biodata obj; System.out.println(“\nThe following are read from an object file : \n “); try { ObjectInputStream oins = new ObjectInputStream(new FileInputStream(“obj1.dat”)); while (true) { obj = (Biodata)oins.readObject(); obj.Printbio(); 248 Programming in JAVA2 if (obj.age == 35) break; } oins.close(); } catch (FileNotFoundException e) { System.out.println(“File not found”); } catch (ClassNotFoundException e) { System.out.println(“Class not found Error”); } catch (IOException e) { System.out.println(“IO Error”); } } } The above program gives the following output: The following are read from an object file: Name Age Place City : K.Somasundaram : 50 : Dept of Comp. Science : Gandhigram 624302 Name Age Place City : S.Magesh : 12 : 3rd Street,Thirunagar : Gandhigram 624302 Name Age Place City : S.P.Kumar : 17 : JE College : Chennai Name Age Place City : S.Gomathi : 35 : 3rd Street,Thirunagar : Gandhigram 624302 In the following program 13.12, the individual member values stored in a file are read as basic types and then assigned to the corresponding variables of that object: Input and Output Classes 249 Program 13.12 // This program illustrates the use of ObjectInputStream. import java.io.*; class Biodata implements Serializable { String name; int age; String adrs1; String adrs2; Biodata() { } Biodata(String nm, int ag, String ad1, String ad2) { name = nm; age = ag; adrs1 = ad1; adrs2 = ad2; } void Printbio() { System.out.println(“\nName : “ + name); System.out.println(“Age : “ + age); System.out.println(“Place : “ + adrs1); System.out.println(“City : “ + adrs2); } } class Objectinput2 { public static void main(String args []) { Biodata obj = new Biodata(); System.out.println(“\nThe following are read from an object file \n “); try { ObjectInputStream oins = new ObjectInputStream(new FileInputStream(“obj2.dat”)); while (true) { obj.name = (String)oins.readUTF(); obj.age = (int)oins.readInt(); obj.adrs1 = (String)oins.readUTF(); obj.adrs2 = (String)oins.readUTF(); obj.Printbio(); if (obj.age == 12) break; } oins.close(); 250 Programming in JAVA2 } catch (FileNotFoundException e) { System.out.println(“File not found”); } catch (IOException e) { System.out.println(“IO Error”); } } } The above program gives the following output: The following are read from an object file: Name : K.Somasundaram Age : 50 Place : Dept of Comp. Science City : Gandhigram 624302 Name : S.Magesh Age : 12 Place : 3rd Street,Thirunagar City : Gandhigram 624302 G Bytes in a file can be read back and reconstructed to its corresponding object using the ObjectInputStream. The class reading the bytes has to implement the interface Serializable. 13.10 Random Access File Disk-oriented random access files are handled in the RandomAccessFile class. This stream is an isolated file stream. It has no superclass except for the super Object. This class provides methods that can be used to write and read basic types in a straight-forward manner rather than going through several filter streams. It implements the DataInput and DataOutput interfaces. Hence, methods in RandomAccessFile, DataInputStream and DataOutputStream are common. The constructor for this class are: i) RandomAccessFile(String file, String access) where file, is the name of the file, access is the access mode; the access value is “r” for read only and “rw” for read and write Input and Output Classes ii) 251 RandomAccessFile (File fobject, String access) where fobject is an object of type File Additional methods in RandomAccessFile are given in table 13.9. Table 13.9 Additional Methods in RandomAccessFile Method Purpose of the Method 1. long getFilePointer() Returns the current location of the file pointer 2. void seek(long len) Sets the file pointer to len position from the beginning of the file 3. long length() Returns the length of the file in bytes 4. void setLength(long, newsize) Sets the length of this file to the size newsize Program 13.13 illustrates the creation of a random access file. Note the methods writeInt(...), writeLong(...), etc. are like those in the DataOutputStream. Program 13.13 // This program illustrates the RandomAccessFile - writing. import java.io.*; class Randomfileou { public static void main(String args []) { File rafile = new File(“raf.dat”); int a = 456; long b = 56783245; String st = “This text is a demo string “; System.out.println(“\n The following data is written to a random access file “); System.out.println(“\n int a = “ + a); System.out.println(“\n long b = “ + b); System.out.println(“\n String st = “ + st); try { RandomAccessFile raf = new RandomAccessFile(rafile, “rw”); raf.writeInt(a); raf.writeLong(b); 252 Programming in JAVA2 raf.writeUTF(st); raf.close(); } catch (IOException e) { System.out.println(“\n I/O Problem “); } } } The above program gives the following output: The following data is written to a random access file int a = 456 long b = 56783245 String st = This text is a demo string The following program 13.14 shows how to read a random access file. The getFilePointer() method gives the location of byte, from where the next data will be read from or written to. The method seek() sets the file pointer at a distance from the beginning of the file. The combination of these two methods can b e u sed to access a file created u sin g RandomAccessFile object. Program 13.14 // This program illustrates the RandomAccessFile - reading. import java.io.*; class Randomfilein { public static void main(String args []) { File rafile = new File(“raf.dat”); System.out.println(“Size of the file = “ + rafile.length()); long ap, bp, stp; int a; long b; String st; try { RandomAccessFile raf = new RandomAccessFile(rafile, “rw”); System.out.println(“\n The following data is read from a random access file sequentially:“); ap = raf.getFilePointer(); a = raf.readInt(); System.out.println(“\n int a = “ + a); bp = raf.getFilePointer(); Input and Output Classes 253 b = raf.readLong(); System.out.println(“\n long b = “ + b); stp = raf.getFilePointer(); st = raf.readUTF(); System.out.println(“\n String st = “ + st); System.out.println(“\n The following data is read from a random access file randomly:“); raf.seek(stp); st = raf.readUTF(); System.out.println(“\n String st = “ + st); raf.seek(ap); a = raf.readInt(); System.out.println(“\n int a = “ + a); raf.seek(bp); b = raf.readLong(); System.out.println(“\n long b = “ + b); raf.close(); } catch (IOException e) { System.out.println(“\n I/O Problem “); } } } The above program gives the following output: Size of the file = 41 The following data is read from a random access file sequentially: int a = 456 long b = 56783245 String st = This text is a demo string The following data is read from a random access file randomly: String st = This text is a demo string int a = 456 long b = 56783245 13.11 Character Stream Byte stream, seen in the previous sections, handles the data in binary form, which is efficient for data processing. The character stream deals with the character-oriented text. The characters are stored and retrieved in a human readable form. Java has two abstract classes, Reader and Writer classes. The Reader class deals with reading of streaming character and Writer class deals with writing of streaming character. The methods defined in Reader are given in table 13.10 and that for Writer are given in table 13.11. 254 Programming in JAVA2 Table 13.10 Methods Defined in Reader All Methods Throw IOException Method Purpose of the Method 1. void close() Closes the input stream 2. void mark(int nchars) Makes a mark at the current position and remembers it until nchars are read 3. boolean markSupported() Returns true, if the mark()/ reset() methods 4. int read() Returns an integer value equivalent to the next available character; returns -1 when end of stream is encountered 5. int read (char b[]) Reads characters into the array b[] to its capacity 6. int read(char b[], int off, int len) Reads a maximum of len chars into the char array starting at b[off]; returns the actual number of characters read or -1 when end of stream is encountered 7. void reset() Resets the input pointer to the previously marked position 8. long skip(long nchars) Skips a maximum of nchars and returns the actual number of characters skipped 9. boolean ready() Returns true if the next input request will not wait, otherwise false stream supports Table 13.11 Methods Defined in Writer class All Methods Throw IOException Methods Purpose of the Method 1. void close() Closes the output stream 2. void flush() Flushes the output buffer 3. void write(int char) Writes a single character to the stream 4. void write(char b[]) Writes an array of chars from b[] to the output stream Input and Output Classes 255 5. void write (char b[], int off, int len) Writes a maximum of len chars from the char array b starting at b[off] 6. void write(String s) Writes a String s to the output stream 7. void write (String s, int off, int len) Writes a maximum of len chars of String s starting from off to the output stream The subclasses in Reader and Writer classes are shown in fig. 13.7. Reader BufferedReader CharArrayReader FilterReader InputStreamReader PipedReader StringReader PushbackReader FileReader Writer BufferedWriter CharArrayWriter FilterWriter OutputStreamWriter PipedWriter PrintWriter StringWriter Fig.13.7 FileWriter Subclasses in Reader and Writer Classes Some of the character streams are discussed in the following sections: 13.11.1 CharArrayReader This is a subclass of Reader. It is used to read an array of characters from a memory buffer. It has all methods of a Reader. The constructor in this class are: i) CharArrayReader(char ch[]) Creates a new character array reader stream with buffer ch as data source 256 Programming in JAVA2 ii) CharArrayReader (char ch[], int off, int len) Creates a new character array reader stream with buffer ch as source; the characters starting at ch[off] and len number of characters act as a data source. Program 13.15 shows the use of CharArrayReader stream. Program 13.15 /*This program illustrates the use of CharArrayReader. First part of the program reads bytes from a file and stores them in a char array. It is then used as data source. */ import java.io.*; class Chararrayrdr { public static void main(String args []) { File fin = new File(“charin.dat”); int count = (int)fin.length(); char ch [] = new char[count]; try { int b; int i = 0; FileInputStream fins = new FileInputStream(fin); while ((b = fins.read()) != -1) ch[i++] = (char)b; } catch (FileNotFoundException e) { System.out.println(“File not found exception”); } catch (IOException e) { System.out.println(“IO Error”); } CharArrayReader cardr = new CharArrayReader(ch); try { int n; while ((n = cardr.read()) != -1) System.out.print((char)n); } catch (IOException e) { System.out.println(“IO Error”); } } } Input and Output Classes 257 The above program gives the following output: This text is read from a text file into a memory buffer. The buffer is then used as a data source. The chars are read from that buffer in CharArrayReader stream. 13.11.2 CharArrayWriter This is a subclass of Writer. It is used for writing an array of characters to a memory buffer. It has all the methods of a Writer. The memory buffer automatically grows when characters are written to the stream. i) CharArrayWriter() Creates a new character array writer stream with the default buffer ii) CharArrayWriter(int size) Creates a new character array writer stream with an initial buffer size of size; throws IllegalArgumentException if the size is negative Table 13.12 gives additional methods defined in this stream. Table 13.12 Additional Methods Defined in CharArrayWriter class Method Purpose of the Method 1. void reset() Resets the buffer so that the buffer can be used again 2. int size() Returns the current size of the buffer 3. Char[] toCharArray() Returns a copy of the input data 4. String toString() Converts the input data to String 5. void writeTo(Writer out) Writes the content of the memory buffer to another character output stream Program 13.16 shows the use of CharArrayWriter class and some of the methods in it. Program 13.16 /* This program illustrates the use of CharArrayWriter. First part of the program reads bytes from a file and stores them in a char array. It is then used as data source. The data is read from this source and written to the 258 Programming in JAVA2 CharArrayWriter stream. */ import java.io.*; class Chararraywtr { public static void main(String args []) { File fin = new File(“charwtr.dat”); int count = (int)fin.length(); char ch [] = new char[count]; try { int b; int i = 0; FileInputStream fins = new FileInputStream(fin); while ((b = fins.read()) != -1) ch[i++] = (char)b; fins.close(); } catch (FileNotFoundException e) { System.out.println(“File not found exception”); } catch (IOException e) { System.out.println(“IO Error”); } CharArrayWriter cawtr = new CharArrayWriter(); try { cawtr.write(ch); System.out.println(“\nThe following data is written to CharArrayWriter stream:\n”); System.out.println(cawtr.toString()); int len = cawtr.size(); System.out.println(“\nThe size of the CharArraryWriter (memory buffer) is = “+ len); cawtr.close(); } catch (IOException e) { System.out.println(“IO Error”); } char chnew [] = cawtr.toCharArray(); // copies to //another array } } The above program gives the following output: Input and Output Classes 259 The following data is written to CharArrayWriter stream: Long long ago, I dont know, how long ago, there lived a man called Rip Van Winkle who slept in the jungle for 20 years. The size of the CharArraryWriter (memory buffer) is = 123 13.11.3 InputStreamReader This is a subclass of Reader class. It is used to convert a byte stream to a character stream. Byte streams produce data that are not in a human readable form. Methods in this class help to translate bytes into characters according to a specified character encoding. Constructors in this class are : i) InputStreamReader(InputStream ins) Creates an InputStreamReader that uses the default character encoding where ins is an input stream ii) InputStreamReader(InputStream ins, String encode) Creates an InputStreamReader that uses the specified character encoding encode ins is an InputStream; the methods specified in InputStreamReader are given in table 13.13. Table 13.13 Methods Specified in InputStreamReader Class All Methods Throw IOException Method Purpose of the Method 1. void close() Closes the stream 2. String getEncoding() Returns the name of the character encoding being used by this stream 3. int read() Reads a single character 4. int read (char[] chbuf, int off, int len) Reads characters into a character array chbuf, starting at index point off, len number of characters; returns the actual number of characters read or -1 if end of stream is encountered 5. boolean ready() Returns true if this stream is ready to be read Program 13.17 illustrates the use of InputStreamReader class and a few of the methods specified in it. 260 Programming in JAVA2 Program 13.17 /* This program illustrates the use of InputStreamReader. InputStreamReader is a bridge connecting byte stream to character stream. */ import java.io.*; class Inputstreamrdr { public static void main(String args []) { File fin = new File(“charin.dat”); int count = (int)fin.length(); char ch [] = new char[count]; char b; try { int i = 0; FileInputStream fins = new FileInputStream(fin); InputStreamReader isr = new InputStreamReader(fins); while ((b = (char)isr.read()) != -1) ch[i++] = b; } catch (FileNotFoundException e) { System.out.println(“File not found exception”); } catch (IOException e) { System.out.println(“IO Error”); } int i = 0; while (i < count) System.out.print(ch[i++]); } } The above program gives the following output: Long long ago, I dont know, how long ago, there lived a man called Rip Van Winkle who slept in the jungle for 20 years. Input and Output Classes 261 13.11.4 OutputStreamWriter This is a subclass of Writer. This class helps to convert character output stream to byte output stream, using a specified character encoding. Each OutputStreamWriter makes use of its own character encoding, using CharToByte Converter or using default encoding. Constructors in this class are: i) OutputStreamWriter(OutputStream ous) Creates an OutputStreamWriter that uses a default character encoding; ous is an output stream. ii) OutputStreamWriter(OutputStream ous, String encode) Creates an OutputStreamWriter that uses the encode as character encoding; it throws UnsupportedEncodingException. Methods defined in this class are given in table 13.14. Table 13.14 Methods Defined in OutputStreamWriter Class Method Purpose of the Method 1. void close() Closes the stream 2. void flush() Flushes the stream 3. String getEncoding() Returns the name of the character encoding used in the stream 4. void write(int c) Writes a single character to the output stream 5. void write(String str, int off, int len) Writes a portion of the string starting at index off, len number of characters 6. void write(char[] chbuf, int off, int len) Writes a character array to the output stream starting at array index off, len number of character Program 13.18 shows the use of OutputStreamWriter class and some of the methods in it. This program reads a file “charin.dat” and prints it on the standard output, the monitor. The data written to the output stream reaches the destination only on operating the flush() method. Program 13.18 // This program illustrates the use of OutputStreamWriter. import java.io.*; class Outputstrmwtr 262 Programming in JAVA2 { public static void main(String args []) { int b; try { FileInputStream fins = new FileInputStream(“charin.dat”); OutputStreamWriter osw = new OutputStreamWriter(System.out); System.out.println(“\nThe character encoding used is :” + osw.getEncoding() + “\n”); int i = 0; while ((b = fins.read()) != -1) osw.write(b); System.out.println(“\nFollowing is the data read from the file: \n “); osw.flush(); // only after flush the characters //are printed out osw.close(); } catch (IOException e) { System.out.println(“File not found “); } } } The above program gives the following output: The character encoding used is :Cp1252 Following is the data read from the file: Long long ago, I dont know, how long ago, there lived a man called Rip Van Winkle who slept in the jungle for 20 years. G InputStreamReader converts byte stream to character stream and OutputStreamWriter converts character stream to byte stream. 13.11.5 FileWriter This class is used for writing characters to files. It is a subclass of OutputStreamWriter. It inherits all the superclass methods. As in other streams, this stream can also be layered. It makes use of default character Input and Output Classes 263 encoding. To use other character encoding methods, OutputStreamWriter can be constructed on a FileOutputStream. Constructors in this class are: i) FileWriter(String filename) Creates a new FileWriter stream with the name filename; if filename already exists, it will be deleted and a new file with filename will be created. ii) FileWriter(String filename, boolean append) Creates a new FileWriter stream; if append is true, data will be appended at the end of the file. iii) FileWriter(File fileobj) Creates a new FileWriter stream with the name specified in the fileobj All the constructors will throw IOException. The use of the FileWriter class and a few of its methods are given in program 13.19. This program reads a text file “charin.dat” and copies it to another file “fwtr.dat” and also prints it on the monitor. Program 13.19 // This program illustrates the use of FileWriter. import java.io.*; class Filewtr { public static void main(String args []) { File fin = new File(“charin.dat”); try { int b; FileInputStream fins = new FileInputStream(fin); FileWriter fwtr = new FileWriter(“fwtr.dat”); System.out.println(“The default character encoding is: “ + fwtr.getEncoding()); System.out.println(“\nThe following data is written to the file :\n”); while ((b = fins.read()) != -1) { fwtr.write(b); System.out.print((char)b); } fins.close(); fwtr.close(); } catch (IOException e) 264 Programming in JAVA2 { System.out.println(“File not found”); } } } The above program gives the following output: The default character encoding is: Cp1252 The following data is written to the file: Long long ago, I dont know, how long ago, there lived a man called Rip Van Winkle who slept in the jungle for 20 years. 13.11.6 FileReader This class is used for reading characters from files. It is a subclass of InputStreamReader. It inherits all the methods from its superclass. The constructors in this class are: i) FileReader(String filename) Creates a new FileReader input stream with the source specified in the file filename ii) FileReader(File fileobj) Creates a new FileReader input stream with the source specified in the fileobj Both constructors throw FileNotFoundException. 13.11.7 BufferedReader It is a subclass of Reader. This class is used to reading. It cannot directly access any source. Methods to read characters from an underlying input character buffer and then send the whole content of the buffer to increase the efficiency of in this class can be used stream, store them in a the destination. The constructors in this class are : i) BufferedReader(Reader inr) Creates a buffering character input stream using a default buffer for an underlying Reader stream inr ii) BufferedReader(Reader int, int size) Creates a buffering character input stream using a buffer size of size Input and Output Classes 265 This class inherits the methods from Reader. One important additional method defined in this class is readLine(). It reads characters from an underlying character stream and constructs a line. The line is terminated with line feed (‘\n’) or carriage return (‘\r’). This method returns a String. 13.11.8 BufferedWriter It is a subclass of Writer. This class helps to write characters to an underlying character output stream by buffering characters and sending them as a lot rather than as character after character for each write. A default buffer size may be used or it can be specified in the constructor. It inherits methods from Writer class. One important additional method for this class is newLine() method. By calling newLine() method a newline (\n’) character is generated. Constructors in this class are : i) BufferedWriter(Writer ous) Creates a buffered character output stream using a default buffer size ii) BufferedWriter(Writer ous, int size) Creates a buffered character output stream using a buffer size of size After reading this chapter, you should have learned the following: Ü All data in Java is handled in two streams, byte stream and character stream. Ü Streams are to be layered required form. Ü Objects can be stored as sequence of bytes in a file and retrieved and reconstructed as objects. Ü Different classes are to be used for memory and disk Oriented I/O. for handling the data conveniently and in the In the next chapter, you will learn about strings. 266 Programming in JAVA2 Worked Out Problems-13 Problem 13.1w Write a Java program that lists the file name, its size and the last modified date, just like the dir command of DOS. Program 13.1w /* ------------------------------------------------------------This program lists out the files, their size and last modified date. somasundaramk@yahoo.com --------------------------------------------------------------*/ import java.util.*; import java.text.*; import java.io.*; class Prob131 { public static void main(String args []) { File fpath = new File("c:/jdk1.2.1/bin/chp13"); String dirlist [] = fpath.list(); int n = dirlist.length; int dircount = 0; int filecount = 0; int pn = 40; System.out.println("\nDirectory of " + fpath.getName() + "\n"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("Modified on \t Size \t File name \n"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); long totsize = 0; for (int i = 0; i < n; i++) { File file = new File(dirlist[i]); String fname = file.getName(); long size = file.length(); totsize += size; long dte = file.lastModified(); boolean dir = file.isDirectory(); // Format the long to date format Input and Output Classes 267 Date date = new Date(dte); DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK); if (dir) { dircount++; System.out.println(df.format(date) + "\t <DIR> \t" + fname); } else { filecount++; System.out.println(df.format(date) + "\t" + size + "\t" + fname); } } for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println(filecount + " files\t" + totsize + " bytes"); System.out.println(dircount + " dirs"); } } The above program gives the following output: Directory of chp13 ------------------------------------------------------------------------Modified on Size File name --------------------------------------------------------------------------16/01/07 1570 Keyboard.java 16/01/07 1365 Keyboard.class 17/01/07 919 Bufreader.java 17/01/07 1184 Bufreader.class 23/01/07 247 object.dat 25/01/07 1405 Objectoutput1.java 25/01/07 1406 Objectoutput1.class 25/01/07 1051 Objectinput1.java 31/01/07 46 int.dat ............... .......... ........................ ............... ......... .............. 09/02/07 1600 Randomfilein.class 31/01/07 868 Datainput1.java 31/01/07 1185 Datainput1.class 21/01/07 53 datainput2.dat 09/02/07 870 Randomfileou.txt 01/02/07 593 Datoutput1.java 268 Programming in JAVA2 28/06/06 875 Inputstrmrdr.txt 26/07/06 1565 Prob131.java 26/07/06 1852 Prob131.class 26/07/06 <DIR> awt -------------------------------------------------------------------------120 files 112111 bytes 1 dirs Problem 13.2w Write a Java program to get the address of persons through the keyboard and store them in a file. Program 13.2w /* ------------------------------------------------------------This program reads the address of persons and stores them in a file. somasundaramk@yahoo.com ------------------------------------------------------------- */ import java.io.*; class Prob132 { public static void main(String args []) { boolean more = true; String name, adrs1, adrs2, pin, state; String choice; File fou = new File("adrs.dat"); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); DataOutputStream dous = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fou))); do { // read the key board System.out.print("Type in your name :"); name = br.readLine(); System.out.print("Type in adrs1 "); adrs1 = br.readLine(); System.out.print("Type adrs2 "); adrs2 = br.readLine(); System.out.print("Type PIN number "); pin = br.readLine(); System.out.print("Type State "); state = br.readLine(); Input and Output Classes 269 // write the data to the file dous.writeBytes(name); dous.writeBytes(adrs1); dous.writeBytes(adrs2); dous.writeBytes(pin); dous.writeBytes(state); System.out.print("Want to input another ? (y/n) "); choice = br.readLine(); if (choice.equals("n") || choice.equals("N")) more = false; }while (more); dous.close(); } catch (FileNotFoundException e) { System.out.println("\n File not found "); } catch (IOException e) { System.out.println("\n I/O problem "); } } } Problem 13.3w Write a program to input the following data through keyboard and store them in a file “height.dat”. Name Amarnath G. Balaji K. Chandar S. David B. Easwari C. Gomathi S. Hariharan D. Magesh S. Kumar S. Ramesh K. Ramya S. Sex m m m m f f m m m m f Height 175.2 172.4 165.0 178.0 160.0 163.0 168.5 172.0 175.5 166.0 155.5 Weight 62.5 60.5 58.4 70.3 55.0 60.0 61.5 55.2 60.5 55.5 45.0 270 Programming in JAVA2 Progra m 13.3w /*-------------------------------------------------------------This program reads the keyboard and writes the data in a DataOutputStream . somasundaramk@yahoo.com ------------------------------------------------------------- */ import java.text.*; import java.io.*; class Prob133 { public static void main(String args []) { File fou = new File("height.dat"); String name, sex; double height, weight; String choice, str; boolean more = true; Number n; DecimalFormat df = new DecimalFormat(); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); DataOutputStream dos = new DataOutputStream(new FileOutputStream(fou)); do { // read the key board System.out.print("Type in your name :"); name = br.readLine(); System.out.print("Type in sex m/f "); sex = br.readLine(); System.out.print("Type your height in cm "); str = br.readLine(); n = df.parse(str); height = n.doubleValue(); System.out.print("Type your weight in kg"); str = br.readLine(); n = df.parse(str); weight = n.doubleValue(); // write the data to the file dos.writeUTF(name); dos.writeUTF(sex); dos.writeDouble(height); dos.writeDouble(weight); Input and Output Classes 271 System.out.print("Want to input another ? (y/n) "); choice = br.readLine(); if (choice.equals("n") || choice.equals("N")) more = false; }while (more); dos.close(); } catch (ParseException pe) { System.out.println("Parsing error"); } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("IO Error"); } } } Problem 13.4w Write a Java program to read the file “height.dat” created in problem 13.3w and print out the names in descending order of height, males and females separately. Program 13.4w /*-------------------------------------------------------------This program reads the data from a data file height.dat, arranges the names in descending order of height and prints the males and females in separate lists somasundaramk@yahoo.com ------------------------------------------------------------- */ import java.io.*; class Prob134 { public static void main(String args []) { File fin = new File("height.dat"); String [] name = new String[50]; String [] sex = new String[50]; int [] age = new int[50]; double [] height = new double[50]; 272 Programming in JAVA2 double [] weight = new double[50]; String tname, tsex; int tage; double theight, tweight; int pn = 70; int c; int count = 0; try { PushbackInputStream pbin = new PushbackInputStream(new FileInputStream(fin)); DataInputStream dins = new DataInputStream(pbin); System.out.println("The data read from the file:\n"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("Name \t\t\tSex\tHeight \tWeight in Kg "); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); while (true) { //the following code along with //PushBackInputStream is necessary to //find the end of file position. c is read //and placed back in the same position c = pbin.read(); pbin.unread(c); if (c == -1) break; // read the file name[count] = dins.readUTF(); sex[count] = dins.readUTF(); height[count] = dins.readDouble(); weight[count] = dins.readDouble(); System.out.println(name[count] + " \t" + sex[count] +" " + height[count] + "\t" + weight[count]); count++; } for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); dins.close(); } catch (FileNotFoundException e) { Input and Output Classes 273 System.out.println("File not found"); } catch (IOException e) { System.out.println("IO Error"); } //sort by height for (int i = 0; i < count; i++) for (int j = i + 1; j < count; j++) { if (height[j] > (height[i])) { theight = height[i]; height[i] = height[j]; height[j] = theight; tname = name[i]; name[i] = name[j]; name[j] = tname; tweight = weight[i]; weight[i] = weight[j]; weight[j] = tweight; tsex = sex[i]; sex[i] = sex[j]; sex[j] = tsex; } } System.out.println("Sorted by Height - Male"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("Name \t\t\tSex\tHeight \tWeight in Kg "); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); for (int i = 0; i < count; i++) if (sex[i].equals("m")) System.out.println(name[i] + " \t" + sex[i] + " " + height[i] + "\t" + weight[i]); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("Sorted by Height - Female"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("Name \t\t\tSex\tHeight \tWeight in Kg "); 274 Programming in JAVA2 for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); for (int i = 0; i < count; i++) if (sex[i].equals("f")) System.out.println(name[i] + " \t" + sex[i] + " " + height[i] + "\t" + weight[i]); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: The data read from the file: ---------------------------------------------------------------------Name Sex Height ---------------------------------------------------------------------Amarnath G m 175.2 Balaji K m 172.4 Chandar S m 165.0 David B m 178.0 Easwari C f 160.0 Gomathi S f 163.0 Hariharan D m 168.5 Magesh S m 172.0 Kumar S m 175.5 Ramesh K m 166.0 Ramya S f 155.5 ---------------------------------------------------------------------Sorted by Height - Male ---------------------------------------------------------------------Name Sex Height ---------------------------------------------------------------------David B m 178.0 Kumar S m 175.5 Amarnath G m 175.2 Balaji K m 172.4 Magesh S m 172.0 Hariharan D m 168.5 Ramesh K m 166.0 Chandar S m 165.0 ---------------------------------------------------------------------Sorted by Height - Female ---------------------------------------------------------------------- Weight in Kg 62.5 60.5 58.4 70.3 55.0 60.0 61.5 55.2 60.5 55.5 45.0 Weight in Kg 70.3 60.5 62.5 60.5 55.2 61.5 55.5 58.4 Input and Output Classes Name Sex Height ---------------------------------------------------------------------Gomathi S f 163.0 Easwari C f 160.0 Ramya S f 155.5 ---------------------------------------------------------------------- 275 Weight in Kg 60.0 55.0 45.0 Exercise-13 I. Fill in the blanks: 13.1 All data in Java is treated in __________ and ________ streams. 13.2 The File class can be used to read and write data. (True/False) 13.3 The classes used for disk file handling are ________ and _______. 13.4 For memory-oriented read and write operations _______ and _____ classes are used. 13.5 ________ streams help to convert raw bytes into the basic type of Java. 13.6 The process of converting an object to byte is called ________ . 13.7 Character-oriented I/O process with memory buffer as source/ destination is dealt in the class _________ and _________ . 13.8 The InputStreamReader class converts ________ stream to ______ stream. 13.9 When I/O objects are created, the streams are automatically opened. True/False 13.10 ________ method sends any buffered byte to its destination. II. Write Java programs for the following: 13.11 Write a Java program to list out the files in the given directory. 13.12 Write a Java program that finds the largest file in the given directory. 13.13. Write a Java program to check whether the file given through command line argument exists. If it exists, copy the whole file to another disk file. 13.14. A set of int type values are stored in a file. Read these values into a memory buffer. Arrange the values in descending order and print them out. 276 Programming in JAVA2 13.15. A set of double values are stored in two different files f1.dat and f2.dat. Write a Java program to read these files and find the average of the values. 13.16. A list containing the following details is given: Name : String Regno : int Mark1 : int Mark2 : int Write a class to describe the above fields. Create objects for 5 sets of values and store the data in a file. Use object outputstream class. 13.17. A random access file contains int type data. Write a Java program to read the first, 5th and 9th int values. (Hint: Use seek() method) * * * * * * 277 Chapter 14 STRINGS In this chapter, you will learn about strings. Java supports two types of strings, String and StringBuffer. String type strings are rigid, whereas StringBuffer strings are flexible for manipulation. Methods to handle these two types of strings are dealt in this chapter. In Java language, a string is defined as a sequence of characters. The strings used in Java are handled by two classes, String and StringBuffer. String class deals with string that are not altered after creation. StringBuffer class deals with strings that need alteration after they are created. Strings dealt by String class are more efficient to handle than strings dealt by StringBuffer. Both the classes are available in java.lang package. 14.1 The String Class String objects are created using the following constructors: String() Creates a String object with no character String(char charray[]) Creates a String using the charray String(char charray[], int start, int len) Creates a String from charray, starting at charray[start] with len number of chars 278 Programming in JAVA2 String(String strObject) Creates a String from String object strObject Examples 1. String s1 = new String() Creates s1 with no characters 2. char name[ ] = { ‘R’, ‘a’, ‘m’, ‘a’, ‘n’ }; String s2 = new String (name); Creates a String s2 with string “Raman” 3. char name[ ] = { ‘R’, ‘a’, ‘m’, ‘a’, ‘n’ }; String s3 = new String (name, 2, 3) Creates a String s3 with string “man” 4. String s4 = new String (s2); Creates a String s4 with string “Raman” It is also possible to use byte array as parameters in constructors used in examples 2 and 3 above to handle the 8-bit ASCII characters. When constructors of String class are used to create objects, each time the new operator is called, an instance of the String is created. Each object takes up a memory space. Suppose, two objects contain identical strings, even then they occupy two separate memory locations. In the above examples 2 and 4, the objects s2 and s4, though contains identical strings, take up two separate memory locations. This can be avoided and memory can be saved if strings are created from String literals. Consider the following examples: 5. 6. String s5 = “Raman”; String s6 = “Raman”; In this method, the string objects s5 and s6 contain identical strings “Raman”. In this case Java does not store two objects, but only one. The same reference, where the object is stored, is given to s5 and s6. Fig. 14.1 illustrates this. Strings Object s2 279 Object “Raman” s4 “Raman” (a) Object s5 s6 “Raman” (b) Fig.14.1(a) Separate memory is allocated when string objects are created using new operator even if strings are identical. (b) Same memory is allocated when string objects are created using String literal with identical strings. Therefore, using String literals to create String objects with identical strings is memory-efficient. When an object reference variable, say s6, is copied to another String variable (say s7), a copy of the object reference is copied to the new variable (s7) and no object is created. Both variables s6 and s7 will refer to the same object. 14.1.1 Equality (= =) Operator and equals Method We have already come across the use of the equality operator, = =, and equals method. Equality operator (==) checks whether the contents of object reference variables are equal, while the equals method checks whether the contents of the objects are equal. s6 Content of Object Reference Variable 3B4F Object Reference Variable “Raman” Object Fig.14.2 Object and Object Reference Variable Content of Object 280 Programming in JAVA2 Referring to fig. 14.1 (a), it is obvious that: (s2 ==s4) --> false s2.equals(s4) --> true Similarly, referring to fig. 14.1(b), the following result will be obtained: (s5 == s6) --> true s5.equals(s6) --> true Creation of String and the use of == operator and equals method are illustrated in the program 14.1. Program 14.1 /* This program demonstrates creation of strings using constructor of String and String literal. The Strings created are tested using == operator and equals method. */ class Stringcompare { public static void main(String args []) { String s1, s2, s3, s4, s5, s6, s7; char name [] ={‘R’,‘a’,‘m’,‘a’,‘n’}; s1 = new String(); s2 = new String(name); s3 = new String(name, 2, 3); s4 = new String(s2); s5 = “Raman”; s6 = “Raman”; s7 = s2; System.out.println(“\n s1 = “ + s1); System.out.println(“\n s2 = “ + s2); System.out.println(“\n s3 = “ + s3); System.out.println(“\n s4 = “ + s4); System.out.println(“\n s5 = “ + s5); System.out.println(“\n s6 = “ + s6); System.out.println(“\n s7 = “ + s7); System.out.println(“\n is( s2==s4) ? : “ + (s2 == s4)); System.out.println(“\n is(s2.equals(s4)) ? : “ + s2.equals(s4)); System.out.println(“\n is(s5.equals(s4) ? : “ + s5.equals(s4)); System.out.println(“\n is(s5==s4) ? : “ + (s5 == s4)); System.out.println(“\n is(s5.equals(s6)) ? : “ + s5.equals(s6)); System.out.println(“\n is(s5 == s6) ? : “ + (s5 == s6)); Strings 281 System.out.println(“\n is(s2.equals(s7)) ? : “ + s2.equals(s7)); System.out.println(“\n is(s2 == s7) ? : “ + (s2 == s7)); } } The above program gives the following output: s1 = s2 = Raman s3 = man s4 = Raman s5 = Raman s6 = Raman s7 = Raman is( s2==s4) ? : false is(s2.equals(s4)) ? : true is(s5.equals(s4) ? : true is(s5==s4) ? : false is(s5.equals(s6)) ? : true is(s5 == s6) ? : true is(s2.equals(s7)) ? : true is(s2 == s7) ? : true 14.1.2 String Concatenation With + There are different ways of concatenation of strings. One way is using + operator. In Java, when + operator is used for strings, it concatenates the operand strings. Examples: 1. 2. String s1 = “this is demo” + “text”; The String s1 will take up s1 = “This is a demo text”. int mark = 75; String s2 = “Your mark is “ + mark; System.out.println(s2); The above will give : Your mark is 75 The + operator can be used with string and numerical variables. In such cases, the numerical values are converted to String type and appended to the preceding String object. Following are further examples for String concatenation: 3. String s1 = “Do it”; String s2 = “by yourself”; 282 Programming in JAVA2 String s3 = s1 + s2; System.out.println(s3) The above statements will give the following result: Do it by yourself. 4. System.out.println (“Sum of 3 and 5 is “ + 3+5): This statement will give the following result: Sum of 3 and 5 is 35 5. System.out.println (“Sum of 3 and 5 is” + (3+5)); This statement will give the following result: Sum of 3 and 5 is 8 As it can be seen from the above examples 4 and 5, the operator precedence is to be observed while concatenating String with numerical types. There are several useful methods for String objects and some of them are given in table 14.1. Table 14.1 Methods in String Class Method Purpose of the Method Character Extraction 1. char charAt(int index) Returns the character at the index position of the invoking String object; the index is counted as 0 for the first character. 2. void getChars(int sourceBegin, Copies characters from Object String int sourceEnd, char target[ ], starting at sourceBegin up to and int targetBegin) inclusive of sourceEnd -1 characters into the target, starting at targetBegin 3. byte[ ] getBytes() Returns an array of characters as bytes from the String object String Comparison 4. boolean equals(Object str) 5. boolean equalsIgnoreCase(String str) Returns true if str contains the same string as that in the invoking object, otherwise false Returns true if str contains the same string as in the invoking object by ignoring the case, otherwise false Strings 283 6. boolean regionMatches Compares a region of the invoking object (int startIndex, String s2, starting at startIndex with String s2 int s2startIndex, int numchars) starting at s2startIndex for numchars; returns true if the region compared is equal, otherwise false 7. boolean regionMatches (boolean ignorecase, int startIndex, String s2 int s2startIndex, int numchars) Compares a region of the invoking object starting at startIndex with String s2 starting at s2startIndex for numchars; if ignoreCase is true, then the case of characters are ignored for comparison. Returns true if the region compared is equal, otherwise false 8. boolean endsWith(String str) Returns true if the invoking String object ends with str, otherwise false 9. boolean startsWith(String str) Returns true if the invoking String object starts with str, otherwise false int compareTo(String str) Compares the invoking String object with str; returns a negative value if the String object is less than str, zero if both are equal and positive if String object is greater than str 10. Searching Substrings 11. int indexOf(int ch) Returns the index of the first occurrence of the character ch in the invoking String object 12. int lastIndexOf(int ch) Returns the index of the last occurrence of the character ch in the invoking String object 13. int indexOf(String str) Returns the index of the first occurrence of the string str in the invoking String object 14. int lastIndexOf(Sring str) Returns the index of the last occurrence of the string str in the invoking String object 15. int indexOf(int ch, int startIndex) Searches for the character ch starting at startIndex of the invoking String object till the end of the string; returns the index of the first occurrence of the character ch 284 Programming in JAVA2 16. int lastIndexOf(int ch, int endIndex) Searches for the character ch from the zero index till the endIndex of the invoking String object; returns the index of the last occurrence of the character ch. 17. int indexOf(String str, int startIndex) Searches for the substring str starting at startIndex till the end of the invoking String object; returns the index of the first occurrence of the string str 18. int lastIndexOf(String str, int endIndex) Searches for the substring str starting at 0 index till the endIndex of the invoking String Object; returns the index of the last occurrence of the string str String Modification 19. String substring(int startIndex) Returns a substring starting at startIndex till the end of the invoking String object 20. String substring(int startIndex, Returns a substring starting at startIndex int endIndex) up to endIndex, but excluding the endIndex character of the invoking string object 21. String concat(String str) Returns a new String after appending the str to the invoking String object 22. String replace(char existingChar, char newChar) Returns a new String created by replacing existingChar with newChar 23. String trim() Returns a new String after removing the leading and trailing white spaces of the invoking String object Case Conversion 24. String toLowerCase() Converts the uppercase characters invoking String object to lowercase of 25. String toUpperCase() Converts the lowercase characters of the invoking String object to uppercase Other Method 26. int length() Returns the number of characters in the invoking String object Strings 285 Program 14.2. shows methods used for character extraction. Program 14.2 // This program illustrates the use of character extraction // methods of String class class Stringextract { public static void main(String args []) { char test [] = new char[10]; String s1 = “This is a demo text”; s1.getChars(8, 14, test, 0); System.out.println(test); byte bytebuf [] = s1.getBytes(); int count = bytebuf.length; System.out.println(); // new line for (int i = 0; i < count; i++) System.out.print((char)bytebuf[i]); } } The above program gives the following output: a demo This is a demo text Program 14.3 compareTo method. sorts the given strings in alphabetical order Program 14.3 /*This program illustrates the use of compareTo method to sort the strings in alphabetical order. */ class Stringsort { public static void main(String args []) { String name [] = { “Zahir Khan”, “Raman”, “Magesh”, “Kumar”, “Sathish” }; String temp; using 286 Programming in JAVA2 int count = name.length; System.out.println(“\nThe given names\n”); for (int i = 0; i < count; i++) System.out.println(name[i]); System.out.println(“\nSorted names\n”); for (int i = 0; i < count; i++) for (int j = i + 1; j < count; j++) if (name[i].compareTo(name[j]) > 0) { temp = name[i]; name[i] = name[j]; name[j] = temp; } for (int i = 0; i < count; i++) System.out.println(name[i]); } } The above program gives the following output: The given names Zahir Khan Raman Magesh Kumar Sathish Sorted names Kumar Magesh Raman Sathish Zahir Khan The toString() method When an object is created using new operator, a reference to the object is created. A default toString() method in the super Object converts this reference to a human readable string form and stores it in the object reference. This string can be printed out using the println method. Program 14.4 shows the printing of the object reference of a class. Program 14.4 // Program to illustrate the use of default // method in the super Object. class Democlass { int x, y; Democlass(int a, int b) toString Strings 287 { x = a; y = b; } } class DefaulttoString { public static void main(String args []) { Democlass dc = new Democlass(15, 45); System.out.println(dc); } } The above program gives the following output: Democlass@7a27c51c This toString() method can be overridden by an user to get other messages needed about the object. Program 14.5 shows the overriding toString() method to generate the message about the initial values assigned to the instance variables. Program 14.5 // Program to illustrate the use of overridden toString // method class Democlass { int x, y; Democlass(int a, int b) { x = a; y = b; } public String toString() { return “Object created with x = “ + x + “ and y = “ + y; } } class toStringDemo { public static void main(String args []) { Democlass dc = new Democlass(15, 45); System.out.println(dc); } } 288 Programming in JAVA2 The above program gives the following output: Object created with x = 15 and y = 45 14.2 The StringBuffer Class Strings that need modification are handled by StringBuffer class. After creating a StringBuffer, new strings can be inserted or appended to it. The size of the StringBuffer can grow whenever needed. StringBuffer objects can be dynamically altered. When a StringBuffer is created, space for 16 more characters is always appended with it. This helps the StringBuffer object to grow by 16 more characters without any other process. That is, the size of the StringBuffer is the number of characters in that string plus 16. When the string grows beyond the free 16 character space, the StringBuffer is relocated to a new memory space with the required size. So, memory management for handling StringBuffer will not be as efficient as that of the fixed-length string objects. The constructors in StringBuffer class help to create StringBuffer objects. The constructors are : StringBuffer() Creates an empty StringBuffer Object; it has 16-character space. StringBuffer(int size) Creates a StringBuffer object with a buffer of size capacity StringBuffer(String str) Creates a StringBuffer object with the string str plus space for 16 more characters The equals() method defined in String class is also available in StringBuffer class. The equals() method can be used to compare the same type of string objects and not to be mixed. That is, a String object cannot be compared with StringBuffer Object. N The equals() method should not be used to compare objects of different types. Methods defined in StringBuffer class are given in table 14.2. Strings Table 14.2 289 Methods Defined in StringBuffer Class Method Purpose of the Method 1. int length() Returns the total number of characters in the invoking object 2. int capacity() Returns the total allocated capacity for the invoking object 3. void ensureCapacity (int capacity) Sets the capacity of the buffer of the invoking object to the desired capacity 4. void setLength(int len) Sets the length of the StringBuffer object to len characters; if len is larger than the length of the object, empty spaces will be created. If len is less than the length of the object, characters after len will be lost. 5. char charAt(int index) Returns a character at the index position of the invoking object 6. void setCharAt(int index, char ch) Sets the character ch at the index position of the invoking object 7. void getChars(int sourceBegin, Copies characters from object starting at int sourceEnd, char target[], sourceBegin up to and inclusive of int targetBegin) sourceEnd -1 characters into the target, starting at targetBegin 8. StringBuffer append(String str) Returns a StringBuffer after appending str to the invoking object 9. StringBuffer append(int num) Returns a StringBuffer after appending the num to the invoking object 10. StringBuffer append(object obj) Returns a StringBuffer after appending obj to the invoking object 11. StringBuffer insert(int index, String str) Returns a StringBuffer after inserting str at index position of the invoking object 12. StringBuffer reverse() Returns a StringBuffer after reversing the characters in the string of the invoking object 13. StringBuffer delete (int startIndex, int endIndex) Returns a StringBuffer after deleting characters from startIndex to endIndex of the invoking object 290 Programming in JAVA2 14. StringBuffer deleteCharAt (int index) Returns a StringBuffer after deleting a character at the index position of the invoking object 15. StringBuffer replace (int startIndex, int endIndex, String str) Returns a StringBuffer after replacing the characters included in the range startIndex to endIndex of the invoking object by str 16. String substring(int startIndex) Returns a String starting at startIndex to the end of the invoking StringBuffer object 17. String substring(int startIndex, Returns a String included in the range int endIndex) startIndex to the endIndex of the invoking StringBuffer object 18. String toString() Returns a String after freezing the buffer size of the invoking StringBuffer object Program 14.6 illustrates the use of some of the methods in StringBuffer class. Program 14.6 // This program illustrates some of the methods in // StringBuffer class. class StringBuf { public static void main(String args []) { StringBuffer name = new StringBuffer(“Somasundaram”); int count = name.length(); System.out.println(“Name = “ + name); System.out.println(“Length of name = “ + count); System.out.println(“Capacity of name = “ + name.capacity()); System.out.println(“Substring of name from 5th character = “ + name.substring(4)); System.out.println(“Name after inserting initial = “ + name.insert(0, “K. “)); System.out.println(“Name after appending the degree = “ + name.append(“ Ph.D”)); System.out.println(“Reversed name = “ + name.reverse()); } } Strings 291 The above program gives the following output: Name = Somasundaram Length of name = 12 Capacity of name = 28 Substring of name from 5th character = sundaram Name after inserting initial = K. Somasundaram Name after appending the degree = K. Somasundaram Ph.D Reversed name = D.hP maradnusamoS .K After reading this chapter, you should have learned the following: Ü Java supports two types of strings, String and StringBuffer. Ü String type is rigid to manipulate, whereas the StringBuffer type is more flexible for manipulation. In the next chapter, you will learn about threads. Worked Out Problems-14 Problem 14.1w Write a program to read the following list through keyboard entry, arrange the names in alphabetical order and print out. Name Ramasamy K. Mahesh S. Kumar S. Charles B. Parvathi M. Cindrela U. Ramesh K. Gomathi S. Balan N. Sex m m m m f f m f m Program 14.1w /*-----------------------------------------------------------This program reads the data from keyborad, arrange the names in alphabetical order and prints out the list. somasundaramk@yahoo.com ------------------------------------------------------------- */ 292 Programming in JAVA2 import java.io.*; class Prob141 { public static void main(String args []) { String [] name = new String[50]; String [] sex = new String[50]; String tname, tsex; int pn = 50; String choice; int count = 0; try { // Read the keyboard to get the input InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); while (true) { System.out.println("Type the name"); name[count] = br.readLine(); System.out.print("Type the sex (m/f) : "); sex[count] = br.readLine(); System.out.print("Any more (y/n) : "); count++; choice = br.readLine(); if (choice.equals("n")) break; } } catch (IOException ie) { System.out.println("IO Error"); } System.out.println("The data read from the keyboard\n"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("Name\t\tSex"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); for (int i = 0; i < count; i++) System.out.println(name[i] + "\t\t" + sex[i]); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); //sort by alphabetical order for (int i = 0; i < count; i++) for (int j = i + 1; j < count; j++) Strings 293 { if (name[j].compareTo(name[i]) < 0) { tname = name[i]; name[i] = name[j]; name[j] = tname; tsex = sex[i]; sex[i] = sex[j]; sex[j] = tsex; } } System.out.println("Sorted List"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("Name \t\tSex "); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); for (int i = 0; i < count; i++) System.out.println(name[i] + "\t\t" + sex[i]); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); } } The above program when executed and data when fed through the key board gives the following output: The data read from the keyboard -------------------------------------------------Name Sex -------------------------------------------------Ramasamy K m Magesh S m Kumar S m Charles B m Parvathi M f Cindrela U f Ramesh m Gomathi S f Balan N m -------------------------------------------------- 294 Programming in JAVA2 Sorted List -------------------------------------------------Name Sex -------------------------------------------------Balan N m Charles B m Cindrela U f Gomathi S f Kumar S m Magesh S m Parvathi M f Ramasamy K m Ramesh m -------------------------------------------------- Problem 14.2w Write a program to count the number of characters, words and lines in a given file. The file name is to be given through the command line argument. Program 14.2w /*-----------------------------------------------------------This program reads a file and counts the number of characters, no of words, no of lines. The file name is fed through the command line argument. somasundaramk@yahoo.com ------------------------------------------------------------- */ import java.io.*; class Prob142 { public static void main(String args []) { int lines = 0; int words = 0; int chars = 0; if (args.length == 0) { System.out.println("Give a file name in the command line"); System.exit(0); } File f = new File(args[0]); try { int chr; Strings 295 FileInputStream fins = new FileInputStream(f); InputStreamReader insr = new InputStreamReader(fins); while ((chr = insr.read()) != -1) { chars++; switch ((char)chr) { case '\t': case ' ': words++; break; case '\n': //case '\r': words++; lines++; } } } catch (IOException ioe) { System.out.println("IO Problem"); } System.out.println(args[0] + " file contains\n" + chars + " chars\n" + words + " words\n " + lines + " lines"); } } The above program gives the following output: Prob142.java file contains 1063 chars 120 words 42 lines Problem 14.3w Write a program to read a text file, “story.txt”, and replace all “his” words with another word “her” in it. Program 14.3w /*-----------------------------------------------------------This program reads a file, finds the word his and replaces it with her. somasundaramk@yahoo.com ------------------------------------------------------------- */ 296 Programming in JAVA2 import java.io.*; class Prob143 { public static void main(String args []) { String find = "his"; String replace = "her"; String ureplace = "Her"; String word = ""; char chr; int rcount = 0; int c; File f = new File("story.txt"); try { FileInputStream fins = new FileInputStream(f); InputStreamReader insr = new InputStreamReader(fins); System.out.println("The given text\n"); while ((c = insr.read()) != -1) System.out.print((char)c); insr.close(); } catch (IOException ioe) { System.out.println("IO Problem"); } System.out.println("\n"); System.out.println("Replaced text\n"); try { FileInputStream fins = new FileInputStream(f); InputStreamReader insr = new InputStreamReader(fins); while ((c = insr.read()) != -1) { chr = (char)c; switch (chr) { case '\t': case '\n': case ' ': word = word + chr; if(word.trim()).equalsIgnoreCase(find)) { rcount++; if Character.isUpperCase(word.charAt(0))) System.out.print(ureplace + " "); else System.out.print(replace + " "); Strings } else System.out.print(word); word = ""; break; default: word = word + chr; } } System.out.print(word); System.out.println("\n"); if (rcount > 0) System.out.println(rcount + " words are replaced"); else System.out.println(" No word is replaced"); insr.close(); } catch (IOException ioe) { System.out.println("IO Problem"); } } } The above program gives the following output: The given text Once upon a time, there lived a king called Cholan. He used to go around the country to know whether his citizens are well. Whenever he went around, he always chose to go by walk. This made it possible for all the people of his country to meet him easily. His services were appreciated by his citizens. Replaced text Once upon a time, there lived a king called Cholan. He used to go around the country to know whether her citizens are well. Whenever he went around, he always chose to go by walk. This made it possible for all the people of her country to meet him easily. Her services were appreciated by her citizens. 4 words are replaced 297 298 Programming in JAVA2 Exercise-14 I. Fill in the blanks 14.1. The string that does not need any modification is to be dealt by ______ class. 14.2. The string that needs modification while processing is dealt by _____ class. 14.3. The classes for handling string are available in the _______ package. 14.4. When a String object is copied into another String object reference, a copy of the original object __________ created. 14.5. To compare the contents of two objects, _________ method is used. 14.6. The number of extra character width available in a StringBuffer is _____ . 14.7. The length of the StringBuffer is defined as _____________. 14.8. The capacity of the StringBuffer is given by ____________ . 14.9. When toString method is applied to a StringBuffer, the buffer size is ____ and the StringBuffer is converted to _______ . II. Write Java programs for the following: 14.10. Write a program to read a line of text from the console. Find the position of the first and last occurrence of the string “the”. Copy all the characters enclosed between the two positions to another String and print it out. 14.11. Write a program to read a line of text from the console. Print out only the vowels (a, e, i, o, u) and their position of occurrence. 14.12. A set of 10 names is given. Write a program to delete the first three characters of the names and arrange the resulting names in alphabetical order and print them out. 14.13. Read in a line of text from the keyboard. Adjust the white space between words so that the whole line is aligned left and right in a line width of 60 characters and print it out. 14.14. A set of 5 words is given. Write a program to reverse each word and arrange the resulting words in alphabetical order. 14.15. Write a program to read a line of text from the console. Change the first character of each word to uppercase letter and print out the resulting string. * * * * * * 299 Chapter 15 THREADS In this chapter, you will learn about multithreaded programming in Java. A single task can be divided into a number of small sub-tasks. Each sub-task can be executed as an independent process. Such a process is known as a thread. In this chapter, creation of multiple threads and managing them are discussed. 15.1 Multitasking Before starting the thread concept, let us begin with a known multitasking process. When more than one task is processed by a computer, it is called multitasking. This is being done to utilize the idle time of a CPU more effectively. Each task (heavy-weight process) has its own set of variables and separate memory location for them. A multitasking process is shown in fig.15.1. Task1 Task2 Task3 CPU Fig.15.1 The Multitasking Process Taskn 300 Programming in JAVA2 The underlying operating system does the multitasking process by bringing tasks to the CPU and executing them by using appropriate schedule. Multithreading In many real-life situations, a single task (heavy-weight process) may comprise of many sub-tasks (light-weight process), such as reading an input stream, processing data, drawing graphics on screen, etc. Each sub-task is carried out one after another. But certain sub-tasks, like reading an input stream, may have to keep waiting till a byte is read. In such occasions, the CPU will be idling without doing any work. This idling time of the CPU can be utilized if some other sub-task, say drawing a graphic on a screen, can be executed in the CPU. Java language provides a mechanism by which each sub-task can be treated as a separate process. Several such processes originating from a single task, can be simultaneously started and handled by Java. This mechanism of treating a single task as several independent processes simultaneously is called multithreading. Each independent process is called a thread. Each thread is executed one at a time in the CPU. Fig. 15.2 shows the multithreading process. Task Sub-Task1 Thread1 Sub-Task2 Thread2 Sub-Task3 Thread3 CPU Fig.15.2 The Multithreaded Process In multithreading, same set of variables and memory space is shared by the threads. When a thread dealing with a sub-task, say reading an input stream, has to wait for the arrival of a byte, such a thread will exit the CPU and another thread, say drawing a graphic on a screen, may enter the CPU and continue its task. Thus Java’s thread provides a mechanism to utilize the CPU time more optimally. Multithreading finds use in variety of applications. The Threads threading mechanism is supported by Java’s java.lang package. 301 Thread class contained in 15.2. Creating a Thread A Java thread can be created in two different ways. They are: i) ii) By extending Thread class By implementing Runnable interface Though both methods can be used to create a thread, implementing Runnable interface has certain advantages, like subclassing an existing class. This method is recommended for creating a Thread. Some of the methods defined in a Thread class to create and execute a thread are given in table 15.1. Table 15.1 Some of the Methods Defined in a Thread Class Method Purpose of the Method 1. String getName() Returns the name of the invoking Thread object 2. boolean isAlive() Returns true if the thread has started and has not yet terminated 3. void join() Waits for a thread to terminate 4. void run() Contains the statements that are to be executed in a thread 5. void start() Starts a thread by calling the run() method 6. void sleep(long ms) Makes the currently executing thread to sleep for ms milli seconds Let us see how to create a thread from a Thread class. Create a subclass of the Thread class. Write a run() method and place all the statements that are to be executed by a thread. Write a constructor for the class and create an instance of the Thread class by passing the run() method as a parameter. This is done through the use of this keyword. Optionally, a name for the thread can also be assigned by placing a String as a second parameter for the Thread instance. Start the thread by calling the start() method of the Thread class. Program 15.1 is an illustration for creating a thread by this way. The program finds the sum of the natural numbers from 1 up to n, with n varying from 1 to 5. 302 Programming in JAVA2 Program 15.1 // Creation of a Thread by extending the Thread class // The thread is created and started in the constructor. class Sumthread extends Thread { int i, sum = 0; Thread th; Sumthread() { th = new Thread(this, “My thread1”); System.out.println(“\n The thread created is : “ + th.getName()); th.start(); } public void run() { for (i = 1; i <= 5; i++) { sum += i; System.out.println(“\n Sum of numbers from 1 up to “ + i + “ = “ + sum); } } } class Threadcreate1 { public static void main(String args []) { new Sumthread(); } } The above program gives the following output: The thread created is : My thread1 Sum of numbers from 1 up to 1 = 1 Sum of numbers from 1 up to 2 = 3 Sum of numbers from 1 up to 3 = 6 Sum of numbers from 1 up to 4 = 10 Sum of numbers from 1 up to 5 = 15 In the above program 15.1, the run() method is executed by its own class object. The run() method is not directly called. When the start() method is called, the run() method is automatically called. It is also possible that the run() method can be executed by some other Thread object. Program 15.2 shows how a run() method is executed by an object other than by its own object, where the run() method is defined. The problem dealt in this program 15.2 is the same as that of program 15.1. Threads 303 Program 15.2 // Creation of a Thread by extending the Thread class // The thread is created and started in main method of // another class. class Sumthread extends Thread { int i, sum = 0; public void run() { for (i = 1; i <= 5; i++) { sum += i; System.out.println(“\n Sum of numbers from 1 up to “ + i + “ = “ + sum); } } } class Threadcreate2 { public static void main(String args []) { Sumthread st = new Sumthread(); Thread th = new Thread(st, “My thread2”); System.out.println(“\n The thread created is : “ + th.getName()); th.start(); } } The above program gives the following output: The thread created is : My thread2 Sum of numbers from 1 up to 1 = 1 Sum of numbers from 1 up to 2 = 3 Sum of numbers from 1 up to 3 = 6 Sum of numbers from 1 up to 4 = 10 Sum of numbers from 1 up to 5 = 15 Now, let us see the second way to create a thread by implementing the interface Runnable. Here also, the run() method is placed inside the class implementing Runnable. A constructor is used to create a Thread object and start it. One advantage of implementing a Runnable interface is that a thread can be created in a subclass of an existing class. This enables to write several threads for the same superclass. Program 15.3 shows the creation of a thread by implementing the interface Runnable. Another method, isAlive(), is also used to know the status of the thread. 304 Programming in JAVA2 Program 15.3 // Creation of a Thread by implementing the interface // Runnable // The thread is created and started by the constructor of // the same class. class Sumthread implements Runnable { int i, sum = 0; Thread th; Sumthread() { th = new Thread(this, “My thread3”); System.out.println(“\n The thread created is : “ + th.getName()); System.out.println(“\n Before starting the thread\n Is the thread alive? :” + th.isAlive()); th.start(); System.out.println(“\n After starting the thread\n Is the thread alive? :” + th.isAlive()); } public void run() { for (i = 1; i <= 5; i++) { sum += i; System.out.println(“\n Sum of numbers from 1 up to “ + i + “ = “ + sum); } } } class Threadcreate3 { public static void main(String args []) { new Sumthread(); } } The above program gives the following output: The thread created is : My thread3 Before starting the thread Is the thread alive? :false After starting the thread Is the thread alive? :true Sum of numbers from 1 up to 1 = 1 Sum of numbers from 1 up to 2 = 3 Sum of numbers from 1 up to 3 = 6 Sum of numbers from 1 up to 4 = 10 Sum of numbers from 1 up to 5 = 15 Threads 305 We write another program in which the run() method is executed by another Thread object. Program 15.4 shows the second form of executing the run() method using Runnable interface. G The codes that are to be executed in a thread are to be placed in the run() method. Program 15.4 // // // Creation of a Thread by implementing the interface Runnable. The thread is created in one class and started in another class class Sumthread implements Runnable { int i, sum = 0; public void run() { for (i = 1; i <= 5; i++) { sum += i; System.out.println(“\n Sum of numbers from 1 up to “ + i + “ = “ + sum); } } } class Threadcreate4 { public static void main(String args []) { Sumthread st = new Sumthread(); Thread th = new Thread(st, “My thread4”); System.out.println(“\n The thread created is : “ + th.getName()); System.out.println(“\n Before starting the thread\n Is the thread alive? :” + th.isAlive()); th.start(); System.out.println(“\n After starting the thread\n Is the thread alive? :” + th.isAlive()); } } The above program 15.4 gives the same result as that of program 15.3. 306 Programming in JAVA2 15.3 States of a Thread When a thread is created, it goes to different states before it completes its task and is dead. The different states are: · new · runnable · running · blocked · dead new threads When a thread is created, it is in a new state. In this state the thread will not be executed. runnable threads When the start() method is called on the thread object, the thread is in runnable state. A runnable thread not necessarily be executed by the CPU. A runnable thread joins the collection of threads that are ready for execution. Which runnable thread takes up the CPU is determined by the underlying operating system. running threads A thread currently being executed by the CPU is in a running state. blocked threads A running thread may go to a blocked state due to any of the following conditions. · wait method is called by the thread · the thread performs I/O operation · sleep method is called by the thread Fig. 15.3 shows the different states of a thread. Threads 307 new wake from sleep runnable I/O complete notify blocked wait running I/O sleep dead Fig.15.3 The Different States of a Thread When a blocked thread is unblocked, it goes to runnable state and not to running state. Among the runnable threads, the one which has higher priority (set by the programmer) will go to the running state. This scheduling is done by the operating system. G When a blocked thread is unblocked, it goes to a runnable state and not to a running state. dead thread A thread becomes dead on two occasions. In the first case, a thread completes its task, exits the running state and becomes dead. In the other case, the run method is aborted, due to the occurrence of an exception and the thread becomes dead. 15.4 Multithreaded Programming In earlier examples, we have seen programs with only one thread. Now, we will see how to write a multithreaded program. When a program is started, a thread is automatically created. It is called the main thread. The main thread 308 Programming in JAVA2 can be accessed using the currentThread() method of the Thread class. Program 15.5 illustrates the creation of two child threads, one finds the sum of natural numbers and the other finds the factorial of numbers. Program 15.5 // This program creates two threads. class Sumthread implements Runnable { int i, sum = 0; public void run() { for (i = 1; i <= 5; i++) { sum += i; System.out.println(“ Sum of numbers from 1 up to “ + i + “ = “ + sum); if (i == 4) Thread.yield(); } } } class Factthread implements Runnable { int i, n, fact = 1; public void run() { for (i = 1; i <= 5; i++) { fact *= i; System.out.println(“ Factorial of “ + i + “ = “ + fact); } } } class Twothread { public static void main(String args []) { Thread ct = Thread.currentThread(); System.out.println(“\n The main thread is : “ + ct.getName()); Sumthread st = new Sumthread(); Factthread ft = new Factthread(); Thread sumt = new Thread(st, “Sum thread”); Thread factt = new Thread(ft, “Factorial thread”); Threads 309 sumt.start(); System.out.println(“\n The thread created is : “ + sumt.getName()); factt.start(); System.out.println(“\n The thread created is : “ + factt.getName()); } } The above program gives the following output: The main thread is : main The thread created is : Sum thread The thread created is : Factorial thread Sum of numbers from 1 up to 1 = 1 Sum of numbers from 1 up to 2 = 3 Sum of numbers from 1 up to 3 = 6 Sum of numbers from 1 up to 4 = 10 Sum of numbers from 1 up to 5 = 15 Factorial of 1 = 1 Factorial of 2 = 2 Factorial of 3 = 6 Factorial of 4 = 24 Factorial of 5 = 120 When you repeatedly run the above program 15.5, you may get the results interleaved or in a different order. It is due to the fact that when threads are created a default priority is allotted to each of the thread. Since both sum thread and factorial thread take equal priorities, the CPU time is allotted equally to each thread. Hence, results may be interleaved. 15.5 Thread Priorities Threads can be assigned priorities. The priorities are used by the operating system to find out which runnable thread is to be given the CPU time. Priorities are given by priority numbers ranging from 1 to 10. A thread with higher priority number will be given preference over the threads with lower priority numbers. The priority of a thread can be set using the method: setPriority(int pri-numb) There are three pre-defined priorities. MIN_PRIORITY with a value 1, NORM_PRIORITY with a value 5 and MAX_PRIORITY with a value 10. When a thread is created, a default priority NORM_PRIORITY is given. To obtain the priority of a thread, the int getPriority() method can be used. When two threads have equal priorities, the underlying 310 Programming in JAVA2 operating system decides which thread is to be given the CPU. The scheduling of threads to running state depends on the OS. It is not guaranteed that threads of equal priorities are given equal CPU time. Program 15.6 shows the creation of two threads and assigning them priorities. Program 15.6 // This program sets priorities for the threads created. class Sumthread implements Runnable { int i, sum = 0; public void run() { for (i = 1; i <= 5; i++) { sum += i; System.out.println(“\n Sum of numbers from 1 up to “ + i + “ = “ + sum); } } } class Factthread implements Runnable { int i, n, fact = 1; public void run() { for (i = 1; i <= 5; i++) { fact *= i; System.out.println(“\n Factorial of “ + i + “ = “ + fact); } } } class Threadpriority { public static void main(String args []) { Sumthread st = new Sumthread(); Factthread ft = new Factthread(); Thread sumt = new Thread(st, “Sum thread”); Thread factt = new Thread(ft, “Factorial thread”); sumt.setPriority(Thread.NORM_PRIORITY - 2); factt.setPriority(Thread.NORM_PRIORITY + 2); System.out.println(“\n The thread created is : “ + sumt.getName()); Threads 311 System.out.println(“\n The thread created is : “ + factt.getName()); System.out.println(“\n The priority value of “ + sumt.getName() + “ is = “ + sumt.getPriority()); System.out.println(“\n The priority value of “ + factt.getName() + “ is = “ + factt.getPriority()); sumt.start(); factt.start(); } } The above program gives the following output: The thread created is : Sum thread The thread created is : Factorial thread The priority value of Sum thread is = 3 The priority value of Factorial thread is = 7 Factorial of 1 = 1 Factorial of 2 = 2 Factorial of 3 = 6 Factorial of 4 = 24 Factorial of 5 = 120 Sum of numbers from 1 up to 1 = 1 Sum of numbers from 1 up to 2 = 3 Sum of numbers from 1 up to 3 = 6 Sum of numbers from 1 up to 4 = 10 Sum of numbers from 1 up to 5 = 15 In the above program 15.6, the Factthread is executed first because it has been assigned higher priority 7, than the Sumthread. You will get the same result in the same order if the program is executed any number of times. This is in contrast to the result for the program 15.5. 15.6 Waiting for a thread-join Method In some problems, it may be required to wait for a particular thread to complete its task before another thread to proceed with. In such occasions, the join method of Thread class can be used. When join method is called on a thread object, the control waits for the thread to complete its task and becomes a dead thread. Then the control proceeds with the normal course of execution. In program 15.7, two threads are created. One thread is started and the join method is called on it. Until the thread completes its task, the control waits at that point. As soon as the corresponding thread comes to dead state, the control proceeds with the execution of the other statements. 312 Programming in JAVA2 Program 15.7 // This program sets priorities for the threads created. // An indirect wait is made till the other thread proceeds // using the join methods. class Sumthread implements Runnable { int i, sum = 0; public void run() { for (i = 1; i <= 5; i++) { sum += i; System.out.println(“\n Sum of numbers from 1 up to “ + i + “ = “ + sum); } } } class Factthread implements Runnable { int i, n, fact = 1; public void run() { for (i = 1; i <= 5; i++) { fact *= i; System.out.println(“\n Factorial of “ + i + “ = “ + fact); } } } class Threadjoin { public static void main(String args []) { Sumthread st = new Sumthread(); Factthread ft = new Factthread(); Thread sumt = new Thread(st, “Sum thread”); Thread factt = new Thread(ft, “Factorial thread”); sumt.setPriority(Thread.NORM_PRIORITY - 2); factt.setPriority(Thread.NORM_PRIORITY + 2); System.out.println(“\n The priority value of “ + sumt.getName() + “ is = “ + sumt.getPriority()); System.out.println(“\n The priority value of “ + factt.getName() + “ is = “ + factt.getPriority()); Threads 313 sumt.start(); System.out.println(“\n The thread created is : “ + sumt.getName()); try { sumt.join(); } catch (InterruptedException e) { ; } factt.start(); System.out.println(“\n The thread created is : “ + factt.getName()); } } The above program gives the following output: The priority value of Sum thread is = 3 The priority value of Factorial thread is = 7 The thread created is : Sum thread Sum of numbers from 1 up to 1 = 1 Sum of numbers from 1 up to 2 = 3 Sum of numbers from 1 up to 3 = 6 Sum of numbers from 1 up to 4 = 10 Sum of numbers from 1 up to 5 = 15 The thread created is : Factorial thread Factorial of 1 = 1 Factorial of 2 = 2 Factorial of 3 = 6 Factorial of 4 = 24 Factorial of 5 = 120 You will observe from the result that when the Sum thread is started and called with join method, the control waits till the Sum thread completes its task. After that the Factorial thread is started. 15.7 Controlling the Threads The objective of multithreading is to deal with sub-tasks independent of each other and to utilize the CPU time optimally. In a multithreaded program, if a particular thread is assigned a higher priority and if it needs longer time to complete its task, then the other runnable threads have to keep waiting. No benefit will be derived if one thread is allowed to consume much of CPU time and keep other threads waiting. Fair chances are to be given to every thread in a program. In any multithread program, a few of the threads in their course of action, such as doing I/O operation, may go from running state to blocked state, 314 Programming in JAVA2 thereby creating opportunities for other threads to enter running state. In the absence of any such natural event, the programmer must find ways to make a CPU-hungry thread to give way for other threads to enter the CPU. Java has two methods which can change the running state of a thread to blocked state. These methods are given in table 15.2. Table 15.2. Methods that Control the Thread Method Purpose of the Method 1. static void sleep(long ms) Makes the milliseconds thread to sleep for ms 2. static void yield() Causes the running thread to yield to other runnable thread The sleep method makes the thread to sleep (lying idle) for a specified amount of time. Once a thread calls a sleep method, it goes from running state to blocked state. It remains sleeping (blocked) till the specified amount of time, wakes up and goes to runnable state. This is one way of making a thread to give way for other runnable thread to enter the running state. Program 15.8 shows the use of sleep method. In this program, two child threads, Sum thread and Factorial thread are created in addition to the main thread. Each of the child thread is made to sleep 25 milliseconds after two or three calculations. Program 15.8 // This program illustrates the use of sleep method. class Sumthread implements Runnable { int i, sum = 0; public void run() { for (i = 1; i <= 5; i++) { sum += i; try { if (i % 2 == 0) Thread.sleep(25); } catch (InterruptedException e) { ; } System.out.println(“\n Sum of numbers from 1 up to “ + i + “ = “ + sum); Threads 315 } } } class Factthread implements Runnable { int i, n, fact = 1; public void run() { for (i = 1; i <= 5; i++) { fact *= i; try { if (i % 3 == 0) Thread.sleep(25); } catch (InterruptedException e) { ; } System.out.println(“\n Factorial of “ + i + “ = “ + fact); } } } class Threadsleep { public static void main(String args []) { Thread ct = Thread.currentThread(); System.out.println(“\n The main thread is : “ + ct.getName()); Sumthread st = new Sumthread(); Factthread ft = new Factthread(); Thread sumt = new Thread(st, “Sum thread”); Thread factt = new Thread(ft, “Factorial thread”); System.out.println(“\n The main thread priority is : “ + ct.getPriority()); System.out.println(“\n The Sum thread priority is : “ + sumt.getPriority()); System.out.println(“\n The Factorial thread priority is : “ + factt.getPriority()); sumt.start(); factt.start(); } } 316 Programming in JAVA2 The above program gives the following output: The main thread is : main The main thread priority is : 5 The Sum thread priority is : 5 The Factorial thread priority is : 5 Sum of numbers from 1 up to 1 = 1 Factorial of 1 = 1 Factorial of 2 = 2 Sum of numbers from 1 up to 2 = 3 Sum of numbers from 1 up to 3 = 6 Factorial of 3 = 6 Factorial of 4 = 24 Factorial of 5 = 120 Sum of numbers from 1 up to 4 = 10 Sum of numbers from 1 up to 5 = 15 In the above program, three threads, main, Sum and Factorial threads, are created. All the three threads take up priority 5. The first four-line outputs are done by the main thread. Thereafterwards, only the two child threads, Sum and Factorial, with equal priority compete for the CPU. The Sum thread is made to sleep for 25 milliseconds whenever even numbers are encountered and the Factorial thread is made to sleep whenever the processing number is divisible by 3. Thus the Sum thread and Factorial thread alternatively provide opportunity to each other (with equal priority) to enter the running state. G When a program is executed, a thread is created in the main() method implicitly. This thread is called main thread. A reference can be obtained to this thread using currentThread() method. The yield method makes the running thread to yield to other runnable threads. If there are runnable threads which have the same or higher priority of the yielding thread, one of them will be scheduled to run in the CPU. The yielding thread will be in runnable state until it gets its next turn. If there are no runnable threads with the same or higher priority, the yielding thread will again come back to running state and continue to run in the CPU. The program 15.9 illustrates the use of yield method. The problem dealt is the same as that for program 15.8. Program 15.9 // This program illustrates the use of yield method. class Sumthread implements Runnable { int i, sum = 0; Threads 317 public void run() { for (i = 1; i <= 5; i++) { sum += i; if (i % 2 == 0) Thread.yield(); System.out.println(“\n Sum of numbers from 1 up to “ + i + “ = “ + sum); } } } class Factthread implements Runnable { int i, n, fact = 1; public void run() { for (i = 1; i <= 5; i++) { fact *= i; if (i % 3 == 0) Thread.yield(); System.out.println(“\n Factorial of “ + i + “ = “ + fact); } } } class Threadyield { public static void main(String args []) { Thread ct = Thread.currentThread(); System.out.println(“\n The main thread is : “ + ct.getName()); Sumthread st = new Sumthread(); Factthread ft = new Factthread(); Thread sumt = new Thread(st, “Sum thread”); Thread factt = new Thread(ft, “Factorial thread”); System.out.println(“\n The main thread priority is : “ + ct.getPriority()); System.out.println(“\n The Sum thread priority is : “ + sumt.getPriority()); System.out.println(“\n The Factorial thread priority is : “ + factt.getPriority()); sumt.start(); factt.start(); } } 318 Programming in JAVA2 The above program gives the following output: The main thread is : main The main thread priority is : 5 The Sum thread priority is : 5 The Factorial thread priority is : 5 Sum of numbers from 1 up to 1 = 1 Factorial of 1 = 1 Factorial of 2 = 2 Sum of numbers from 1 up to 2 = 3 Sum of numbers from 1 up to 3 = 6 Factorial of 3 = 6 Factorial of 4 = 24 Factorial of 5 = 120 Sum of numbers from 1 up to 4 = 10 Sum of numbers from 1 up to 5 = 15 In the above program, three threads main, Sum and Factorial are created. All the three have the same priority 5. As in the previous program 15.8, the Sum thread is made to yield whenever the number processed is even and the Factorial thread is made to yield whenever the processed number is divisible by 3. The result obtained is the same as the previous program. It is to be noted that when the program is repeated many times, the sequence of the output may be different from the one shown above. It is due to the fact that scheduling the thread is carried out by the underlying OS. Hence, with different OS the interleaving sequence of output may differ. G In multithread program, if there are threads that have no chance of being blocked and have a higher priority, such threads should be sent to blocked state by calling sleep or yield method. Only then other threads will have a chance to enter CPU. 15.8 Synchronizing Methods Classes can be defined with methods which can do generalized tasks such as sorting a given set of numbers, calculating the compound interest, etc. Objects of such classes can be created and be used as a common resource. Threads can make use of such objects for carrying out their tasks. When two or more threads use the same object to do their task, it is likely that the task of one thread is mixed with the task of other thread and gives incorrect results. This may happen due to any of the following situations: Threads 319 · Threads using the common object may have same priority and, therefore, the CPU may switch from one thread to another thread before the method completes the task in the running thread. · A thread using the common object may have a higher priority than another thread which is also using the common object and may preempt the lower priority thread, in which the method has not yet completed the task. · A thread using the common object may go to a blocked state before the method completes the task and another thread using the same object may start executing its task. Program 15.10 illustrates the use of a common object by three threads and the resulting interleaved output for the threads. This program has a class Printing with a method printnumber that prints numbers from the given number down to 1, by decrementing one in each step. Halfway through, the process is made to sleep for 100 milliseconds (to simulate a blocked state) and then to complete the remaining task. Another class Threadserve is used to create a thread. This class has a constructor, through which an object of type Printing and an int type number is passed as parameter. The run() method makes use of the printnumber method of the object. In the main method, an object of the type Printing is created. Three instances of the Threadserve are created to which the same object of type Printing is passed as parameter with int number 16 for the first, 8 for the second and 10 for the third. These three objects create threads and are supposed to print from 16 to 1 by the first, 8 to 1 by the second and 10 to 1 by the third. Program 15.10 // This program illustrates the use of unsynchronized method. class Printing { void printnumber(int n) { System.out.println(“ Start”); for (int j = n; j > 0; j—) { try { if (j == n / 2) Thread.sleep(100); } catch (InterruptedException e) { ; } 320 Programming in JAVA2 System.out.print(“ “ + j); } System.out.println(“ End”); } } class Threadserve implements Runnable { int n; Printing pt; Thread th; Threadserve(Printing p, int x) { n = x; pt = p; th = new Thread(this); th.start(); } public void run() { pt.printnumber(n); } } class Threadsynchro { public static void main(String args []) { Printing p = new Printing(); Threadserve ts1 = new Threadserve(p, 16); Threadserve ts2 = new Threadserve(p, 8); Threadserve ts3 = new Threadserve(p, 10); } } The above program gives the following output: Start 16 15 14 13 12 11 10 9 Start 8 7 6 5 Start 10 9 8 7 6 8 7 6 5 4 3 2 1 End 4 3 2 1 End 5 4 3 2 1 End From the above results, it can be seen that printnumber method used by the first thread prints from 16 to 9, jumps to the second thread and prints from 8 to 5, then jumps to the third thread and prints from 10 to 6, goes back to first thread and prints from 8 to 1 and completes the task, then switches to second thread, prints from 4 to 1 and completes the task and comes to the third thread, prints from 5 to 1 and completes the printing. As it can be seen, the results are mixed up, contrary to our expectations. There should be a way out to eliminate this problem. Threads 321 To avoid methods serving many threads to leave in the middle before completing the task, Java provides a mechanism called synchronization. To do this, the keyword synchronized is used. A synchronized method, once having taken up a task, cannot be accessed by other threads until it completes the task. G To prevent a method to serve many simultaneously, declare it as synchronized. threads The synchronization is achieved through the monitor concept. When a method is declared as synchronized, the object to which it is a member is supposed to have a lock and key. When the method is not accessed by any thread, the key is available to any thread. When a thread wants to make use of the method, it takes the key and locks the object. While the method is doing its task, no other thread can access the method. Once the task is over, the thread releases the object and leaves the key free. The keyword synchronized is used in two forms. In the first form, synchronized word is used while declaring the method itself. synchronized return-type methodname (para-list) { ... ... method body } In the second form, the declaration is done as follows: synchronized (object) { statements for synchronization; } While an object is locked, other threads cannot access only the synchronized method, but can access the other methods. An object can have any number of synchronized methods. When such an object is locked by one thread for want of one synchronized method, all other synchronized methods of the object cannot be accessed by other threads. When one thread owns the lock, it can access all synchronized methods of that object. G When an object having more than one synchronized method is locked, all synchronized methods cannot be accessed by other threads. However, other nonsynchronized methods of that object can be accessed. 322 Programming in JAVA2 Program 15.11 shows the use of synchronized method, modified form of program 15.10. which is a Program 15.11 // This program illustrates the use of synchronized method. class Printing { synchronized void printnumber(int n) { System.out.println(“Start”); for (int j = n; j > 0; j—) { try { if (j == n / 2) Thread.sleep(100); } catch (InterruptedException e) { ; } System.out.print(“ “ + j); } System.out.println(“End”); } } class Threadserve implements Runnable { int n; Printing pt; Thread th; Threadserve(Printing p, int x) { n = x; pt = p; th = new Thread(this); th.start(); } public void run() { pt.printnumber(n); } } class Threadsynchro1 { public static void main(String args []) { Threads 323 Printing p = new Printing(); Threadserve ts1 = new Threadserve(p, 16); Threadserve ts2 = new Threadserve(p, 8); Threadserve ts3 = new Threadserve(p, 10); } } The above program gives the following output: Start 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 End Start 8 7 6 5 4 3 2 1 End Start 10 9 8 7 6 5 4 3 2 1 End You will observe from the above result that the printing of numbers, once started in a thread by the synchronized method, will not be left halfway by the thread without completing it. In this program, the synchronized keyword is used in the declaration of the method itself. Alternatively, it can be written in the following form also: . . . class Printing { void printnumber(int n) { . . . public void run() { synchronized(pt) { pt.printnumber(n); } } . . . The above modification in program 15.11 will give the same result as that for 15.11. 15.9 Inter-Thread Communication Threads are created to carry out light-weight process independently. In certain problems, two or more threads may use an object as a common resource. In order to avoid a mix-up of the task of one thread with that of another thread, 324 Programming in JAVA2 the resource object is synchronized. When one thread is using the synchronized object, the monitor is locked and another thread needing to use this object has to keep waiting. A synchronized object may have more than one synchronized method. One thread may need to use one synchronized method, while another thread may need another synchronized method of the same object. But when a synchronized object is used by one thread, it cannot be accessed by any other thread, even if a different method of the shared object is needed. It may happen that only after an action has taken place in one thread, the other thread can proceed. If the currently running thread can proceed only after an action in another non-running thread, the running thread has to keep waiting infinitely. To avoid such problem, Java provides inter-thread communication methods, which can send messages from one thread to another thread, which uses the same object. The methods used for inter-thread communication are : 1. wait() This method makes the calling thread to give up monitor and go to sleep until some other thread wakes it up. 2. notify() This method wakes up the first thread which called wait() on the same object. 3. notifyAll() This method wakes up all the threads that called wait() method on the same object. All the three methods can be called only inside a synchronized code and are applicable to threads that share the same object. To illustrate the inter-thread communication, consider a problem of handling a message. It is needed to receive a message from a keyboard and then print it out. It is obvious that the message can be printed only after receiving a message. To start with, we develop a simple program to handle this problem and show that unsynchronized shared object cannot meet our requirement. Program 15.12 illustrates this. The class Message contains two methods Readmesg and Printmesg. Readmesg reads the keyboard and stores the message and Printmesg prints the stored message. To deal with the read process, the thread Receive is developed and another thread Print is developed to deal with the printing process. Both share the same object of the class Message. The two threads are invoked, three times in the main method. Threads 325 Program 15.12 /* This program reads a message from a keyboard and prints it on the screen. Unsynchronized object is used. */ import java.io.*; class Message { String mesg; void Readmesg() { try { InputStreamReader ins = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ins); System.out.print(“Type in a message: “); mesg = br.readLine(); } catch (IOException e) { System.out.println(“IO Error”); } } void Printmesg() { System.out.println(“The received message is :” + mesg); } } class Receive implements Runnable { Message ms; Thread th; Receive(Message ms) { this.ms = ms; th = new Thread(this); th.start(); } public void run() { ms.Readmesg(); } } class Print implements Runnable { 326 Programming in JAVA2 Message ms; Thread th; Print(Message ms) { this.ms = ms; th = new Thread(this); th.start(); } public void run() { ms.Printmesg(); } } class Threadcomm1 { public static void main(String args []) { Message mymsg = new Message(); for (int i = 0; i < 3; i++) { new Print(mymsg); new Receive(mymsg); } } } The output and the input typed in for the above program are given below: The received message is :null Type in a message: The received message is :null Type in a message: The received message is :null Type in a message: hello how are In the output, the words, hello, how and are, are typed separately on the keyboard. The result shows that the Receive thread did not wait for key press nor the Print thread waited for the receipt of the message. Both threads executed their process without waiting for the message. The message printed is a default null value. Only after both threads completed their task, the three words are sensed at the keyboard. The Print thread is called first and the Receive thread is placed second. This is done purposely to show the need for inter-thread communication. To improve this, the methods Readmesg and Printmesg of the class Message is declared as synchronized. . . synchronized void Readmesg() { Threads 327 . . } synchronized void Printmesg() { . . } With the above modification in program 15.12 the output obtained is : The received message is :null Type in a message: hello The received message is :hello Type in a message: how The received message is :how Type in a message: are The output shows the first printing is with “null”. The Receive thread is waiting for the keyboard press, as the thread uses a synchronized object. Though the Receive thread worked properly, the Print thread did not. It prints the previously received message and not the current message. Now, we make use of wait and notify methods. Program 15.13 shows the program with wait and notify methods. The thread containing Readmesg method is made to wait (gives up monitor lock so that another thread can make use of the synchronized object) when a message is already received from the keyboard. If no fresh message is received, it reads the keyboard and calls the notify method to inform the other thread that there is a message to print. The thread using Printmesg method is made to wait when there is no message for printing. If there is a message, it prints the message and calls the notify method to inform the other thread that the message has been printed and new message can be received. You will notice that the message is received from the keyboard first and printed out. This is the expected result. Program 15.13 /* This program reads a message from a keyboard and prints it on the screen. Synchronized object with wait and notify method is used. */ import java.io.*; class Message { String mesg; boolean received = false; synchronized void Readmesg() { 328 Programming in JAVA2 try { while (received) wait(); } catch (InterruptedException e) { System.out.println(“Thread interrupted while waiting”); } try { InputStreamReader ins = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ins); System.out.print(“Type in a message: “); mesg = br.readLine(); } catch (IOException e) { System.out.println(“IO Problem”); } received = true; notify(); } synchronized void Printmesg() { try { while (!received) wait(); } catch (InterruptedException e) { System.out.println(“Thread interrupted while waiting”); } System.out.println(“The received message is :” + mesg); received = false; notify(); } } class Receive implements Runnable { Message ms; Thread th; Receive(Message ms) Threads { this.ms = ms; th = new Thread(this); th.start(); } public void run() { ms.Readmesg(); } } class Print implements Runnable { Message ms; Thread th; Print(Message ms) { this.ms = ms; th = new Thread(this); th.start(); } public void run() { ms.Printmesg(); } } class Threadcomm { public static void main(String args []) { Message mymsg = new Message(); for (int i = 0; i < 3; i++) { new Print(mymsg); new Receive(mymsg); } } } The above program gives the following output: Type in a message: hello The received message is :hello Type in a message: how The received message is :how Type in a message: are The received message is :are 329 330 Programming in JAVA2 G The wait(), notify(), notifyAll() methods can be called only inside synchronized method. After reading this chapter, you should have learned the following: Ü Thread is an individual subtask running independently. Ü A program may contain many threads to perform various subtasks. Ü Threads can communicate with other threads. In the next chapter, you will learn about applets. Worked Out Problems–15 Problem 15.1w Write a Java program to compute the Sine and Cosine values, using the formula given in problem 5.1w. Use one thread to compute Sine function and another thread to compute Cosine function. Program 15.1w /* ------------------------------------------------------------This program calculates the sin(x) and cos(x) functions by computing the sin series and cos series functions using thread technique. somasundaramk@yahoo.com ------------------------------------------------------------- */ class Trigno { double x; int i, n = 5; long factn; Trigno(double x) { this.x = x; } long Factfun(int nmax) { long fact = 1; for (i = 2; i <= nmax; i++) Threads 331 fact *= i; return fact; } synchronized double Sinfun() { double six = x; for (int k = 1; k <= n; k++) { factn = Factfun(2 * k + 1); six = six + Math.pow(-1, k) * Math.pow(x, (2 * k + 1)) / factn; } return six; } synchronized double Cosfun() { double cox = 1; for (int k = 1; k <= n; k++) { factn = Factfun(2 * k); cox = cox + Math.pow(-1, k) * Math.pow(x,2* k)/factn; } return cox; } } class Sine implements Runnable { double sinval; Trigno trgno; double Sincomp(Trigno trg) { trgno = trg; Thread th = new Thread(this); th.start(); try { th.sleep(50); } catch (InterruptedException ie) { ; } return sinval; } public void run() { sinval = trgno.Sinfun(); } } class Cosine implements Runnable 332 Programming in JAVA2 { double cosval; Trigno trgno; double Coscomp(Trigno trg) { trgno = trg; Thread th = new Thread(this); th.start(); try { th.sleep(50); } catch (InterruptedException ie) { ; } return cosval; } public void run() { cosval = trgno.Cosfun(); } } class Prob151 { public static void main(String args []) { int pn = 80; double x, sinx, cosx, jsx, jcx; Trigno trg; Sine sino; Cosine coso; for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); System.out.println("x \t my sinx \t Java sinx \t my cosx \t Java cosx\n"); for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); for (x = 0; x < 1.6; ) { trg = new Trigno(x); sino = new Sine(); coso = new Cosine(); sinx = sino.Sincomp(trg); cosx = coso.Coscomp(trg); // Reduce the fractional digits for display double sx = (int)(sinx * 1000); double cx = (int)(cosx * 1000); sinx = sx / 1000; cosx = cx / 1000; Threads 333 jsx = (int)(Math.sin(x) * 1000); jcx = (int)(Math.cos(x) * 1000); jsx = jsx / 1000; jcx = jcx / 1000; System.out.println(x + "\t" + sinx + "\t\t" + jsx + "\t\t" + cosx + "\t\t" + jcx); x = x + 0.5; } for (int i = 0; i < pn; i++) System.out.print("-"); System.out.println("\n"); } } The above program gives the following output: -------------------------------------------------------------------------------x my sinx Java sinx my cosx Java cosx -------------------------------------------------------------------------------0.0 0.0 0.0 1.0 0.5 0.479 0.479 0.877 1.0 0.841 0.841 0.54 1.5 0.997 0.997 0.07 -------------------------------------------------------------------------------- 1.0 0.877 0.54 0.07 Problem 15.2w Write a Java program to make two player number game. Each player has to feed an integer when his/her turn comes (to keep the players interacting with the progam). A random number will be generated in the range 0 to 200. player who gets a larger number is the winner. A A winner gets points equal to the difference in the random numbers. Program 15.2w /* ------------------------------------------------------------This program makes two player number game. Players are to feed in an integer number which is not used in the program, but keeps the player engaged in the game. For each player, a random number is generated. The player who gets higher number is the winner. The winner gets points equal to the difference between the two random numbers. somasundaramk@yahoo.com ------------------------------------------------------------- */ 334 Programming in JAVA2 import java.util.*; import java.io.*; import java.text.*; class Game { int sn1, rand1; int sn2, rand2; Random r1, r2; boolean played = false; DecimalFormat df = new DecimalFormat(); Number n1, n2; String str; synchronized int Play1() { try { while (played) wait(); } catch (InterruptedException e) { System.out.println("Thread interrupted while waiting"); } try { InputStreamReader ins = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ins); System.out.print("Player 1: Type in an integer number "); str = br.readLine(); n1 = df.parse(str); sn1 = n1.intValue(); // genarate random number r1 = new Random(); // get random numbers from 0 to 200 rand1 = r1.nextInt(200); } catch (IOException e) { System.out.println("IO Problem"); } catch (ParseException pe) { System.out.println("Parsing error"); } played = true; notify(); return rand1; Threads } synchronized int Play2() { // keep waiting till the other player has played try { while (!played) wait(); } catch (InterruptedException e) { System.out.println("Thread interrupted while waiting"); } try { InputStreamReader ins = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ins); System.out.print("Player 2: Type in an integer number "); str = br.readLine(); n2 = df.parse(str); sn2 = n2.intValue(); // genarate random number r2 = new Random(); // get random numbers from 0 to 200 rand2 = r2.nextInt(200); } catch (IOException e) { System.out.println("IO Problem"); } catch (ParseException pe) { System.out.println("Parsing error"); } played = false; notify(); return rand2; } } class Player1 implements Runnable { Game gm; int score; Thread th; int Play(Game gme) { 335 336 Programming in JAVA2 gm = gme; th = new Thread(this); th.start(); try { th.join(); } catch (InterruptedException ie) { ; } return score; } public void run() { score = gm.Play1(); } } class Player2 implements Runnable { Game gm; int score; Thread th; int Play(Game gme) { gm = gme; th = new Thread(this); th.start(); try { th.join(); } catch (InterruptedException ie) { ; } return score; } public void run() { score = gm.Play2(); } } class Prob152 { public static void main(String args []) { Threads 337 Game gam = new Game(); Player1 p1; Player2 p2; int points1 = 0; int points2 = 0; int score1, score2; int gamecount = 0; while (true) { p1 = new Player1(); score1 = p1.Play(gam); p2 = new Player2(); score2 = p2.Play(gam); points1 += ((score1 > score2) ? score1 - score2 : 0); points2 += ((score2 > score1) ? score2 - score1 : 0); gamecount++; System.out.println("\nThis game:\n Player 1 score : " + score1 + "\n Player 2 score : " + score2); if (score1 > score2) System.out.println("\nPlayer1 wins"); else System.out.println("\nPlayer2 wins"); System.out.println("\nTotal Points after " + gamecount + " games"); System.out.println("\n Player 1 : " + points1 + " points" + "\n Player 2 : " + points2 + " points"); try { InputStreamReader ins = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ins); System.out.print("\nDo you want to continue another (y/n): "); String str = br.readLine(); if (str.equals("n")) break; } catch (IOException e) { System.out.println("IO Problem"); } } } } 338 Programming in JAVA2 The above program gives the following output: Player 1: Type in an integer number 33 Player 2: Type in an integer number 55 This game: Player 1 score : 70 Player 2 score : 99 Player2 wins Total Points after 1 games Player 1 : 0 points Player 2 : 29 points Do you want to continue another (y/n):y Player 1: Type in an integer number 79 Player 2: Type in an integer number 0 This game: Player 1 score : 157 Player 2 score : 190 Player2 wins Total Points after 2 games Player 1 : 0 points Player 2 : 62 points Do you want to continue another (y/n):y Player 1: Type in an integer number 1234 Player 2: Type in an integer number 965 This game: Player 1 score : 175 Player 2 score : 137 Player1 wins Total Points after 3 games Player 1 : 38 points Player 2 : 62 points Do you want to continue another (y/n): y Player 1: Type in an integer number 654 Player 2: Type in an integer number 67 Threads This game: Player 1 score : 85 Player 2 score : 25 Player1 wins Total Points after 4 games Player 1 : 98 points Player 2 : 62 points Do you want to continue another (y/n): y Player 1: Type in an integer number 89 Player 2: Type in an integer number 432 This game: Player 1 score : 154 Player 2 score : 126 Player1 wins Total Points after 5 games Player 1 : 126 points Player 2 : 62 points Do you want to continue another (y/n): y Player 1: Type in an integer number 45 Player 2: Type in an integer number 99 This game: Player 1 score : 55 Player 2 score : 20 Player1 wins Total Points after 6 games Player 1 : 161 points Player 2 : 62 points Do you want to continue another (y/n): n 339 340 Programming in JAVA2 Exercise-15 I. Fill in the blanks 15.1. When several tasks are handled by a single CPU, it is called _____________ . 15.2. When several sub-tasks of one task is handled in a CPU, it is called _____________ . 15.3. Threads can be created by extending __________ class. 15.4. Threads can be created by implementing _________ interface. 15.5. All codes that are to be executed in a thread are to be placed inside the ___________ method. 15.6. When a thread is created using new operator, the thread is in _______ state. 15.7. To bring a thread to a runnable state, the __________ method is to be called. 15.8. When a thread is waiting for an action (like I/O operation) it is said to be in _______ state. 15.9. At any one instance of time ____________ thread(s) will be in running state. 15.10. When an object is used as a common resource, the object is to be _________ to avoid mix-up of tasks. 15.11. wait() and notify() methods can be used only inside a ___________ code. 15.12. The decision, which thread is to enter the CPU, is made by the ________ . 15.13. A thread with lower priority value will be given __________ priority than a thread with higher priority value. II. Write Java program for the following: 15.14. Write a Java program to convert the sequence of characters AB*CD/+ representing the Polish notation to the original expression A*B+C/D. Use two threads to perform the evaluation. 15.15. Write a Java program to compute the first 25 prime numbers. Also compute the first 50 Fibonacci numbers given by f n =f n-1 +f n-2 , with Threads 341 f1=f2=1. Create two threads to compute each one of them. Set the priority of thread that computes Fibonacci number to 8 and the other to 5. After calculating 50 Fibonacci numbers, make that thread to sleep and take up the prime number computation. After computing the 25 prime numbers continue the Fibonacci number computing. 15.16. A bank account is operated by a father and his son. opened with an initial deposit of Rs. 600. The account is Thereafter, the father deposits a random amount between Re 1 and Rs 200 each time, until the account balance crosses Rs. 2,000. The son can start withdrawing the amount only if the balance exceeds Rs. 2,000. son withdraws random amount between Re 1 and Thereafter, the Rs 150, until the balance goes below Rs. 500. Once the balance becomes less than Rs 500, the father deposits amount till it crosses Rs. 2,000 and the process continues. Write a Father and Son thread to carry out the above process. * * * * * * 342 Programming in JAVA2 BLANK 343 Chapter 16 APPLETS In this chapter, you will learn about applets. Applets are a second kind of program supported by Java language. Applets are programs that travel across a network as bytecodes, load automatically in the local machine and are executed by web browsers. The architecture of an applet, how to create and embed them in an HTML document are discussed in this chapter. 16.1 Applet Basics Applets are a second kind of programs that Java supports. Applets are programs that can be downloaded from a foreign machine through a network and executed in a local machine. Applets are not controlled by the local operating system. Applets are split into small packets called bytecodes and travel across the network. These bytecodes are reassembled by the Java Virtual Machine (JVM) in the receiving machine and are executed by the browser. Applets cannot access the local resources like hard disk and floppy. Applets cannot be executed directly. An applet can only be an element of an HTML page. Therefore, an applet can be executed only by executing an HTML page. These HTML pages, as usual, are executed by web browsers. For testing purpose, the applet element of an HTML page can be executed by appletviewer provided in the JDK. 344 Programming in JAVA2 Applets do not use main() method and System.out.println() method. Applets use only graphics methods for output. They generate window-based output. Therefore, they need graphics support. To draw graphics output, they make use of Java’s Abstract Window Tool kit(AWT). Applets are defined in Applet class. Therefore, to write an applet program, the java.applet and java.awt packages are to be imported. The Applet class hierarchy is shown in fig.16.1. The JApplet is defined in Swing. Object Ú Component Ú Container Ú Panel Ú Applet Ú JApplet Fig.16.1 Class Hierarchy of Applet Class A simple applet program is given in program 16.1. Program 16.1 // This is a simple applet. import java.applet.*; import java.awt.*; public class Myapplet extends Applet { public void paint(Graphics g) { g.drawString(“Welcome to Applet World”, 20, 40); } } Compile this program as has been done for application program as below: C>javac Myapplet.java Applets Then create test1.htm file with the following applet element. simplest form, the applet element is: <applet code = Myapplet width = 200 height = 150 > <\applet> Then execute the htm file with appletviewer as : C>appletviewer test1.htm The output of this program is given below: Fig.16.2 Output Screen for Program 16.1 When Executed With Aappletviewer The same test1.htm viewed through the Internet Explorer is given below: Fig.16.3 Output Screen of Program 16.1 When Viewed With Internet Explorer 345 In the 346 Programming in JAVA2 In the above program, the applet window has a width of 200 pixel and height of 150 pixel. The String “Welcome to Applet World” is displayed at the x,y co-ordinate 20,40 of the display area. Instead of creating two programs, an applet program and another htm file, to execute the applet, the applet element of htm file can be embedded within the applet program itself as a comment. By this method, the htm and applet program can be combined and executed as a single program. The combined applet is given in program 16.2. Program 16.2 import java.applet.*; import java.awt.*; /* <applet code = applet1 width = 200 height = 150> </applet> */ // This is a simple applet public class applet1 extends Applet { public void paint(Graphics g) { g.drawString(“Welcome to Applet World”, 20, 40); } } First compile the program 16.2 using javac compiler. Then execute the program using appletviewer and specifying the applet’s source file. C>appletviewer applet1.java The result of the above program 16.2 is the same as that of program 16.1. Applets rely for input and output on AWT. applet is event-driven, such as mouse click. compose an applet can be understood only after handling, which is discussed in chapter 18. In the of applet are given. G All user interactivity with the Therefore, all elements that knowing the details of event following sections more basics Applets can only be a part of HTML page and are executed by web browsers. However, during the development stage, applets can be executed directly using appletviewer. Applets 347 16.2 Methods of Building an Applet Applets are created, executed, stopped and destroyed by appropriate methods provided in Applet class. All these activities are carried out by the following methods. These methods are called by AWT automatically. Appropriate methods can be overridden to meet the users requirement. a) init() This method is used to initialize the variables of the applet. the method called first. This is called only once. This is b) start() This method is called automatically after the init() method. It is also called whenever a user returns to the page containing the applet after going to a different page. start() method can be called repeatedly while the init() method is called only once, when the applet is loaded. It is in this method that a thread is restarted. c) paint() This method is called automatically after the start() method. The user screen is drawn using the paint() method. This method has an argument of type Graphics defined in AWT. The paint() method is called when the applet begins execution. d) stop() This method is called automatically when a user leaves the page containing the applet. Hence, it can be called repeatedly. This helps the suspension of the activity when the user is not using the applet. Otherwise, it will slow down the system performance. e) destroy() This method is called automatically when the browser ends the activity. This method helps to release the resources used by the applet. A user has to put all the codes required to wind up the final activities when the applet is removed from the memory of the system. The stop() method is called automatically before destroy() method. Program 16.3 gives an illustration to write an init, start, stop and destroy methods. The strings mesg1 to mesg4 are not assigned initial values. They are assigned string literals when the respective methods are executed. The string mesg3 is assigned a text inside the destroy() method. Statements inside stop and destroy methods will be executed only when the applet is stopped and destroyed. This can be done by restarting the applet. 348 Programming in JAVA2 Program 16.3 // This program illustrates the basic methods of applet. import java.applet.*; import java.awt.*; /* <applet code = Allmethod width = 250 height = 200> </applet> */ public class Allmethod extends Applet { String mesg1, mesg2, mesg3, mesg4; public void init() { mesg1 = “message from init method”; } public void start() { mesg2 = “message from start method”; } public void stop() { mesg3 = “message from stop method”; } public void destroy() { mesg4 = “system is destroying your applet”; } public void paint(Graphics gp) { gp.drawString(“Demo for basic methods of applet”, 20, 40); if (mesg1 != null) gp.drawString(mesg1, 20, 80); if (mesg2 != null) gp.drawString(mesg2, 20, 100); if (mesg3 != null) gp.drawString(mesg3, 20, 120); if (mesg4 != null) gp.drawString(mesg4, 20, 140); } } The applet when executed gives the following output screen: Applets 349 Fig.16.4 Output Screen for Program 16.3 In the output window, select Applet and click Restart. This will destroy the applet and start again. As a result, mesg3 and mesg4 are assigned values and displayed in the new screen as shown below: Fig.16.5 Output Screen for Program 16.3 After Restart 350 Programming in JAVA2 The use of init() method to set background and foreground colors of a window is given in program16.4: Program 16.4 // This program illustrates the init method. import java.applet.*; import java.awt.*; /* <applet code = Appinit width = 200 height = 200> </applet> */ public class Appinit extends Applet { public void init() { setBackground(Color.green); setForeground(Color.red); } public void paint(Graphics gp) { gp.drawString(“init method illustration”, 20, 40); } } The above program gives the following output screen. The window area is in green background and the foreground text is in red color. Fig.16.6 Output Screen for Program 16.4 Applets 16.3 351 Some General Methods of Applet Some of the general methods defined in Applet class are given in table 16.1. Table 16.1 Some General Methods Defined in Applet Class Method Purpose of the Method 1. String getAppletInfo() Returns the string that describes the applet 2. URL getCodeBase() Returns applet 3. URL getDocumentBase() Returns the URL of the HTML page that contains the applet 4. String getParameter(String pname) Returns the string associated with the parameter pname 5. String[][] getParameterInfo() Returns a string table that is defined in the applet 6. boolean isActive() Returns true if the applet has been started; returns false if the applet has been stopped 7. void resize(int width, int height) Resizes the window according to width and height 8. void showStatus(String s) Displays the String s in the status window of the browser the URL associated with the 16.4 Displaying Text in Status Bar Text in the status bar of the browser window can be displayed using the showStatus() method. Program 16.5 shows the use of this method and isActive method. Program 16.5 // This program illustrates the use of isActive and // showStatus methods. /* <applet code = StatusBar width = 300 height = 100> </applet> */ import java.applet.*; import java.awt.*; public class StatusBar 352 Programming in JAVA2 extends Applet { public String state() { if (isActive()) return “ applet is alive”; else return “applet is dead”; } public void paint(Graphics gp) { gp.drawString(“ status bar demo”, 80, 40); gp.drawString(state(), 80, 60); showStatus(“Text for the status bar”); } } The output screen for the above program is given below: Fig.16.7 Output Screen for Program 16.5 16.5 Embedding Applet Information Information or description about the applet can be defined in the getAppletInfo method and can be used in the user window. This method along with resize is given in program 16.6. Program 16.6 // This program illustrates the getAppletInfo method. import java.applet.*; import java.awt.*; /* <applet code = Appinfo width = 200 height = 200> </applet> */ public class Appinfo extends Applet { Applets 353 public String getAppletInfo() { return “ Author :Dr.K.Somasundaram”; } public void paint(Graphics gp) { gp.drawString(getAppletInfo(), 20, 40); try { Thread.currentThread().sleep(3000); } catch (InterruptedException e) { ; } resize(200, 100); gp.drawString(“after resize”, 20, 80); } } The output screen for the above program before and after resize are given below: (b) (a) Fig.16.8 16.6 Output Screen for Program 16.6. (a) Before Resize b) After Resize The HTML Applet Tag An applet can be an element of an HTML page. The applet statement itself has its own structure and is called applet tag. The individual components define behaviors and properties of an applet. The general structure of an applet tag is given below. Those written with [...] are optional and the other entries are mandatory for an applet. 354 Programming in JAVA2 <APPLET [CODEBASE = codebase URL] CODE = appletName [archive = archivefile] [ALT = alternateText] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [USPACE = pixels] [HSPACE = pixels] > [ <PARAM NAME = attributeName VALUE = value>] [ <PARAM NAME = attributeName VALUE = value>] . . [text to be displayed in the absence of non-java browser] </APPLET> CODEBASE It defines the URL that contains the applet code. defined, the URL of the HTML document is used. If CODEBASE is not CODE It specifies the name of the class file of the applet. It is a mandatory requirement. This file is relative to the code base URL of the HTML document or as specified by CODEBASE. ARCHIVE It specifies the archive (JAR) file name. files are needed for applet execution. It can be used when a group of ALT It specifies the text that is to be displayed if the browser could understand the applet tag but could not execute the applet. It is an optional attribute. NAME It specifies the name for the applet instance. Names help one applet to find another applet on the same page to communicate with them. It is an optional attribute. WIDTH and HEIGHT This specifies the width and height of the applet display area. in pixels and they are integer numbers. It is given Applets 355 ALIGN It specifies the alignment of the applet in the web page. The predefined values are LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE and ABSBOTTOM. PARAMNAME and VALUE Parameters can be defined, given a name and a value. PARAM declares it is a parameter, NAME declares the name of the parameter and VALUE specifies the value that the variable defined by NAME can take. The value can be passed into the applet using getParameter() method. It is an optional attribute. VSPACE and HSPACE VPSACE specifies the space above and below the applet in pixels and HSPACE specifies the space on the left and right side of the applet in pixels. G Using HTML applet tag, applet codes stored in a remote URL server can be brought to local machines and executed using web browsers. 16.7 Reading Parameters into Applets Applets can read data defined in the applet tag using PARAM attribute. It is one of the ways to bring data into the applet. The getParameter() returns a String type. Therefore, if numeric values are defined, they are to be converted from String to numeric types. Program 16.7 shows the use of getParameter() method. Program 16.7 // This program illustrates the getParameter() method. import java.applet.*; import java.awt.*; /* <applet code = Param width = 250 height = 200> <param name = author value = “Dr.K.Somasundram”> <param name = age value = “50”> <param name = designation value = “Professor”> <param name = institute value = “Gandhigram Rural Institute”> </applet> */ 356 Programming in JAVA2 public class Param extends Applet { public void paint(Graphics gp) { String au = getParameter(“author”); String ag = getParameter(“age”); int balance = 62 - Integer.parseInt(ag); String desg = getParameter(“designation”); String inst = getParameter(“institute”); gp.drawString(“Author : “ + au, 20, 40); gp.drawString(“Age : “ + ag, 20, 60); gp.drawString(“Designation: “ + desg, 20, 80); gp.drawString(“Affliation : “ + inst, 20, 100); gp.drawString(“Will retire after : “ + balance + “ years”, 20, 120); showStatus(“Parameter method”); } } The output screen for the above program is given below: Fig.16.9 Output Screen for Program 16.7 16.8 Colors in Applet The background and foreground colors of an applet can be set using the values defined in Color class. The color values defined in Color class are : Color.black Color.darkGray Color.lightGray Color.red Color.blue Color.gray Color.magenta Color.white Color.cyan Color.green Color.pink Color.yellow The methods used for setting the foreground and background colors are defined in Component and are given below: Applets i) ii) 357 void setBackground(Color colorvalue) void setForeground(Color colorvalue) where, the colorvalue specifies color values defined in the Color class. Program 16.4 given earlier illustrates the above two methods. It is also possible to detect the colors used in an applet window. methods are : i) Color getBackground() ii) Color getForeground() 16.9 The Getting Documentbase and Codebase The URL that contains the applet code is called codebase. The URL that contains the HTML page is called documentbase. These two URLs can be obtained using getCodeBase() and getDocumentBase() methods as defined in table 16.1. The program 16.8 illustrates the use of the above two methods: Program 16.8 // This program illustrates the getDocumentBase() // and getCodeBase() methods. import java.applet.*; import java.awt.*; import java.net.*; // needed to obtain URL values /* <applet code = Docbase width = 350 height = 100> </applet> */ public class Docbase extends Applet { public String getAppletInfo() { return “ Author :Dr.K.Somasundaram”; } public void paint(Graphics gp) { URL docb = getDocumentBase(); URL codb = getCodeBase(); gp.drawString(“Documentbase : “ + docb, 20, 40); gp.drawString(“Codebase : “ + codb, 20, 60); showStatus(getAppletInfo()); } } 358 Programming in JAVA2 The above program gives the following screen output: Fig.16.10 Output Screen for Program 16.8 16.10 Interfaces in Applet Applet package has three interfaces AppletContext, AppletStub and AudioClip. The AppletContext interface contains methods which can be used to get information about the applet’s environment. The AppletStub contains methods which can serve as interface between browsers. The AudioClip interface has methods to control audio clips. 16.11 Multimedia in Applet The multimedia elements sound and image can be brought into the applets. Methods defined in Applet class to handle sound, image and related methods are given in table 16.2. Table 16.2 Multimedia Methods Defined in Applet class Method Purpose of the Method 1. AudioClip getAudioClip (URL url) Returns the AudioClip object located at the site url 2. AudioClip getAudioClip (URL url, String fname) Returns the AudioClip object located at the site url with name fname 3. static final AudioClip newAudioClip(URL, url) Returns an AudioClip specified at the location url 4. void play(URL url) Plays an AudioClip found at the location url 5. void play(URL url, String clipName) Plays the audio clip clipName found at the location url 6. Image getImage(URL url) Returns an Image object found at the location url 7. Image getImage(URL url, String imageName) Returns an Image object imageName found at the location url Applets 359 16.11.1 Playing Audio Clips Java applet supports audio clips of formats au, aiff, midi, wav and rmf. Audio clips can be played directly by calling the play() method and specifying the URL and the audio clip name. Program 16.9 shows the use of play() method to play an audio clip. Program 16.9 // This program illustrates the play() method. import java.applet.*; import java.awt.*; import java.net.*; // needed to obtain URL values /* <applet code = Appaudio1 width = 200 height = 100> </applet> */ public class Appaudio1 extends Applet { public String getAppletInfo() { return “ Author :Dr.K.Somasundaram”; } public void paint(Graphics gp) { gp.drawString(“Playing music “, 20, 40); URL codb = getCodeBase(); play(codb, “shore.aif”); showStatus(getAppletInfo()); } } The output of the above program is given below: Fig.16.11 Output Screen for Program 16.9 360 Programming in JAVA2 The AudioClip interface has three methods to control the audio clip. They are: i) void play() Starts playing this audio clip ii) void loop() Starts playing this audio clip in loop iii) void stop() Stops playing this audio clip Multiple audio clips can be played at the same time. The resulting sound is a mixture of all the clips. The following program 16.10 plays one audio clip using the loop() and getAudioClip() methods. Program 16.10 // This program illustrates the getAudioClip() and loop() // methods. import java.applet.*; import java.awt.*; import java.net.*; // needed to obtain URL values /* <applet code = Appaudio2 width = 200 height = 100> </applet> */ public class Appaudio2 extends Applet { URL codb; AudioClip music; public void init() { codb = getCodeBase(); music = getAudioClip(codb, “bird.au”); music.loop(); } public void stop() { music.stop(); } public void paint(Graphics gp) { gp.drawString(“Playing music “, 20, 40); showStatus(“getAudioClip() and loop() methods”); } } The output screen for the above program is given below: Applets Fig.16.12 361 Output Screen for Program 16.10 16.11.2 Images in Applet Still images from a specified URL can be obtained using getImage() method. Images of format JPEG and GIF are supported for images. The images can be drawn inside an applet using drawImage() method defined in Graphics class. The following program 16.11 shows how to bring in a still image in JPG format. Program 16.11 // This program illustrates the getImage() method. import java.applet.*; import java.awt.*; import java.net.*; // needed to obtain URL values /* <applet code = Appimage2 width = 400 height = 400> </applet> */ public class Appimage2 extends Applet { URL codb; Image picture; public void init() { codb = getCodeBase(); picture = getImage(codb, “magesh.jpg”); } public void start() { } public void paint(Graphics gp) { gp.drawImage(picture, 10, 10, this); showStatus(“ S.Magesh”); } } The above program gives the following output: 362 Programming in JAVA2 Fig.16.13 Output Screen for Program 16.11 Animated GIF images can also be handled in the applet. shows a way to handle an animated GIF image. Program 16.12 Program 16.12 // This program illustrates the getImage() method. import java.applet.*; import java.awt.*; import java.net.*; // needed to obtain URL values /* <applet code = Appimage1 width = 200 height = 150> </applet> */ public class Appimage1 extends Applet { URL codb; AudioClip music; Image picture1; public void init() { setBackground(Color.green); codb = getCodeBase(); picture1 = getImage(codb, “sample1.gif”); music = getAudioClip(codb, “instrument.mid”); music.loop(); } public void paint(Graphics gp) Applets 363 { gp.drawImage(picture1, 10, 10, this); showStatus(“getImage() and drawImage methods”); } } The above program gives the following output: Fig.16.14 Output Screen for Program 16.12 G Multimedia elements sound and image can be included in applets and controlled. 16.11.3 Applet Showing Other HTML Pages One applet can bring another valid HTML document to view using showDocument() method. This method is defined in the AppletContext interface. There are two forms of this method. They are: i) void showDocument(URL url) Shows the document specified by the URL; this method does not work with appletviewer. It works only with browsers. ii) void showDocument(URL url, String location) Shows the document specified by the URL at the location specified by the String; does not work with appletviewer; needs a browser The predefined locations on the browser window are: “_self” “_parent” “_top” “_blank” - show show show show the the the the document document document document in in in in the current frame the parent window the topmost frame a new top level window 364 Programming in JAVA2 Other String - show the document in the frame with that name; if no such named frame exists, show it in a frame with that name. Program 16.13 shows the use of showDocument method. Program 16.13 // This program illustrates the showDocument() method. import java.applet.*; import java.awt.*; import java.net.*; // needed to obtain URL values public class Showdoc extends Applet { URL codb; AppletContext ac; Image image1; public void init() { ac = getAppletContext(); codb = getCodeBase(); image1 = getImage(codb, “sample1.gif”); try { ac.showDocument(new URL(codb + “Appaudio2.htm”), “_blank”); } catch (MalformedURLException e) { showStatus(“URL not found”); } } public void paint(Graphics gp) { gp.drawImage(image1, 0, 0, this); } } Write the following HTML document with a file name showdoc.htm : <html> <head> <h1> Demo for ShowDocument method</h1> </head> <body> <applet code = "Showdoc.class" width = 300 height = 300> </applet> </body> </html> Applets Then view the showdoc.htm using a web browser. using Internet Explorer is given below: Fig.16.15 365 The screen output Output Screens for Program 16.13 First is the parent window and the second is the result of showDocument() method. After reading this chapter, you should have learned the following: Ü Applets are programs that can be accessed from a remote server and executed in a local machine, using a web browser. Ü Appelts can only be a part of HTML page. Ü Multimedia elements like text, sound and image can be handled in an applet. Ü Applets are designed for network application. In the next chapter, you will learn about graphics. 366 Programming in JAVA2 Worked Out Problem-16 Problem 16.1w Write an applet to display the date and time. The time is to be shown like a digital clock. Program 16.1w /* ------------------------------------------------------------This program displays the date and time like a real clock. somasundaramk@yahoo.com ------------------------------------------------------------- */ import java.util.*; import java.applet.*; import java.awt.*; /* <applet code = Prob161 </applet> */ width = 480 height = 200> public class Prob161 extends Applet { String date; String time; int month, day, year; Font ft; int msec, sec, min, hr; GregorianCalendar calendr; public void init() { setBackground(Color.green); setForeground(Color.black); //set font size and type ft = new Font("Courier", Font.PLAIN, 70); setFont(ft); } public void paint(Graphics gp) { // creating current date calendr = new GregorianCalendar(); day = calendr.get(Calendar.DATE); month = calendr.get(Calendar.MONTH); month += 1; // January is 0 hence this conversion year = calendr.get(Calendar.YEAR); date = " " + day + "-" + month + "-" + year; msec = calendr.get(Calendar.MILLISECOND); Applets sec = calendr.get(Calendar.SECOND); min = calendr.get(Calendar.MINUTE); hr = calendr.get(Calendar.HOUR); time = " " + hr + ":" + min + ":" + sec; gp.drawRect(5, 5, 470, 190); gp.drawString(date, 20, 80); gp.drawString(time, 20, 170); try { Thread.currentThread().sleep(500); } catch (InterruptedException ie) { ; } repaint(); showStatus("Clock Display"); } } The above program gives the following output: Fig.16.16 Output Screen for the Program 16.1w * * * * * * 367 368 Programming in JAVA2 Exercise-16 I. Fill in the following: 16.1. Java language supports two types of programs _______ and ______ . 16.2. Applets travel in the network as _________ . 16.3. The applet is constructed and executed by _____________ . 16.4. Applet is defined in ___________ class. 16.5. Applets need methods defined in __________ for their output. 16.6. An applet does not need _______ method as in the application program. 16.7. An applet can be executed only by placing the _______ tag in ______ page. 16.8. Any variable in an applet can be initialized using _______ method. 16.9. _____ method is called automatically before the destroy() method is called. 16.10. ________ method removes the applet from the memory. 16.11. The URL of the HTML page that contains the applet code is called ______ . 16.12. The URL that contains the applet class is called __________ . II. Write applets for the following problems: 16.13. Write an applet that displays your address on the screen. Run it using a browser (after writing an HTML tag) and appletviewer. 16.14. Write an applet for the problem in question 16.13 by taking the address values from parameter. 16.15. Write an applet to play an audio clip in wav format. 16.16. Write an applet to get an image using getImage() method. image and also play an audio clip in a loop. * * * * * * Draw the 369 Chapter 17 GRAPHICS In this chapter, you will learn about graphics and methods used for drawing lines and regular shapes like rectangle, oval, polygon and polyline. Some basic methods used for handling fonts are also given. Java provides a variety of tools for designing graphics and graphical user interface. All such tools are provided in Abstract Window Toolkit(AWT) package. This package contains a large number of classes. The Swing classes, which have better capability than AWT, are discussed in Chapter 19. In this chapter, we will see the graphics methods to generate shapes, different fonts and colors. Generally, a window is created first and graphic objects are drawn on it. One way to create a window is by using an applet. An applet creates a window on which graphics objects can be drawn. Applet window is a closable one, i.e. by clicking the close icon(x) on the window, the window can be closed. Another way to create a window is by using the frame created in Frame class. A frame window is not closable by clicking the close icon(x) on the window. An appropriate method is to be used to close it, which we will see in the next chapter. Graphics tools are available in java.awt.Graphics class. The applet is obtained from java.applet.Applet class. The frame window is obtained from java.awt.Frame class. Since Graphics class is an abstract class, a graphics context is obtained indirectly. One way to get Graphics context is by passing Graphics as a parameter to the paint() or update() methods. In the examples to follow, applet windows are used to draw the graphic objects. A few examples are also given using Frame window. 370 Programming in JAVA2 G To draw graphics objects, a window is needed. One way to obtain a window is by creating an applet which automatically creates Panel type window. Alternatively, a Frame Window can also be used. 17.1 Drawing Lines Lines are drawn using the following method: public void drawLine(int x 1, int y 1 , int x 2, int y 2 ) draws a line in the current color, from the point (x 1, y 1) to (x 2, y 2 ) The following program 17.1 shows the drawLine() method: Program 17.1 // This program illustrates the drawLine() method. /* <applet code = Line </applet> */ width = 300 height =300 > import java.applet.Applet; import java.awt.Graphics; public class Line extends Applet { public void paint(Graphics gp) { int x1 = 10, y1 = 25; int x2 = 200, y2 = 230; gp.drawLine(x1, y1, x2, y2); gp.drawString(“Line”, 20, 270); } } The above program gives the following output: Graphics 371 Fig.17.1 Output Screen for Program 17.1 17.2 Drawing Rectangles The parameters specifying a rectangle is given in fig 17.2 Window x, y Width Height Fig.17.2 Parameters Specifying a Rectangle Rectangles of different styles can be drawn using the following methods: public void drawRect(int x, int y, int width, int height) draws a rectangle with top left corner at (x, y) with the specified width and height in the current color. public void drawRoundRect(int x, int y, int width, int height, int arcw, int arch) Draws a round cornered rectangle with top left corner at (x, y) with the specified width and height in the current color; arcw is the horizontal diameter of the arc at the four corners and arch is the vertical diameter of the arc. 372 Programming in JAVA2 public void draw3DRect(int x, int y, int width, int height, boolean raised) Draws a 3-d rectangle with top left corner at (x,y) with the specified width and height in the current color; if the raised is true, the rectangle appears to be raised above the surface, otherwise it is sunk into the surface. public void fillRect(int x, int y, int width, int height) Draws a filled rectangle public void fillRoundRect(int x, int y, int width, int height, int arcw, int arch) Draws a filled round cornered rectangle public void fill3DRect(int x, int y, int width, int height, boolean raised) Draws a filled 3D rectangle public void clearRect(int x, int y, int width, int height) Clears a rectangular area with top left corner at (x,y) with the specified width and height; the cleared area is filled with the background color. The following program 17.2 shows the use of various rectangle drawing methods: Program 17.2 // This program illustrates the drawRect() method. // Graphics objects are drawn on the Applet window. /* <applet code = Rectangle width =300 height =350 > </applet> */ import java.applet.Applet; import java.awt.Graphics; public class Rectangle extends Applet { public void paint(Graphics gp) { int x = 10, y = 25; int width = 100, height = 130; gp.drawRect(x, y, width, height); gp.drawString(“Rectangle”, 10, 170); gp.fillRect(160, 25, 100, 130); gp.drawString(“Filled Rectangle”, 160, 170); gp.drawRoundRect(10, 180, 100, 130, 20, 20); gp.drawString(“Rounded Rectangle”, 10, 330); gp.fill3DRect(160, 180, 100, 130, false); gp.drawString(“Filled 3D Rectangle”, 160, 330); showStatus(“Applet with rectangles”); } } Graphics 373 The above program gives the following output: Fig.17.3 Output Screen for Program 17.2 These rectangles can also be drawn on a frame window. To create a frame window, the Frame class is used. A frame window is created by inheriting the Frame in a class and creating an instance of that class. The paint() method is used to obtain a Graphics context and call drawing methods. The following program 17.3 shows the use of a frame window to draw the graphics objects. This is an application program. Program 17.3 // This program illustrates the drawRect() method. // The graphics objects are drawn on the Frame window. import java.awt.Graphics; import java.awt.Frame; class Myframe extends Frame { Myframe(String title) { super(title); setSize(300, 350); } 374 Programming in JAVA2 public void paint(Graphics gp) { int x1 = 10, y1 = 25; int x2 = 100, y2 = 130; gp.drawRect(x1, y1, x2, y2); gp.drawString(“Rectangle”, 10, 170); gp.fillRect(160, 25, 100, 130); gp.drawString(“Filled Rectangle”, 160, 170); gp.drawRoundRect(10, 180, 100, 130, 20, 20); gp.drawString(“Rounded Rectangle”, 10, 330); gp.fill3DRect(160, 180, 100, 130, false); gp.drawString(“Filled 3D Rectangle”, 160, 330); } } public class FRectangle { public static void main(String args []) { Myframe mframe = new Myframe(“Frame with Rectangles”); mframe.show(); } } The above program gives the following output: Fig.17.4 Output Screen for Program 17.3 Graphics G 375 Graphics methods are called on Graphics object. The graphics object is obtained by calling the paint() method with Graphics object as parameter. 17.3 Drawing Ovals and Circles Ovals (ellipse) can be drawn using the following methods. Special case of oval becomes circle. Methods used for drawing ovals are: public void drawOval(int x, int y, int width, int height) Draws an oval bounded by a rectangle with its top left corner at (x, y) with the specified width and height public void fillOval(int x, int y, int width, int height) Draws a filled oval The following program 17.4 illustrates the use of drawOval method to draw ellipses and circles: Program 17.4 // This program illustrates the drawOval() method. /* <applet code = Oval width =300 height =350 > </applet> */ import java.applet.Applet; import java.awt.Graphics; public class Oval extends Applet { public void paint(Graphics gp) { int x = 10, y = 25; int width = 100, height = 130; gp.drawOval(x, y, width, height); gp.drawString(“Oval”, 10, 170); gp.fillOval(140, 25, 160, 100); gp.drawString(“Filled Oval”, 160, 170); gp.drawOval(10, 200, 100, 100); gp.drawString(“Circle”, 10, 330); gp.fillOval(160, 200, 100, 100); gp.drawString(“Filled Circle”, 160, 330); showStatus(“Applet with ovals and circles”); } } The above program gives the following output: 376 Programming in JAVA2 Fig.17.5 Output Screen for Program 17.4 17.4 Drawing Arcs The co-ordinates to draw an arc are specified as in fig. 17.6. (x, y) width arc start height Fig.17.6 Parameters Specifying an Arc Arcs are drawn using the following methods: public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draws an arc bounded by a rectangle having its top left corner at (x, y) with specified width and height; the arc starts at startAngle and sweeps an angle arcAngle. public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draws a filled arc The following program 17.5 shows the use of drawArc() method. Graphics Program 17.5 // This program illustrates the drawArc() method. /* <applet code = Arc width =300 height =350 > </applet> */ import java.applet.Applet; import java.awt.Graphics; public class Arc extends Applet { public void paint(Graphics gp) { int x = 10, y = 25; int width = 100, height = 130; gp.drawArc(x, y, width, height, 10, 110); gp.drawString(“Arc”, 10, 130); gp.fillArc(160, 25, 100, 130, 10, 110); gp.drawString(“Filled Arc”, 160, 130); gp.drawArc(10, 180, 100, 130, 20, 260); gp.drawString(“Abtuse Arc”, 10, 330); gp.fillArc(160, 180, 100, 130, 20, 260); gp.drawString(“Filled Arc”, 160, 330); showStatus(“Applet with Arcs”); } } The above program gives the following output: Fig.17.7 Output Screen for Program 17.5 377 378 Programming in JAVA2 17.5 Drawing Polygons Polygons with many corners are drawn using the following methods. Each method takes two int type arrays, one for all the x co-ordinates and another for all the y co-ordinates, that forms the polygon. All polygons drawn using these methods are closed. public void drawPolygon(int xPoints[], int yPoints[], int nPoints) Draws a closed polygon defined by the arrays xPoints and yPoints; nPoints represent the number of (x,y) pairs. Usually, the starting and ending x and y points are to be the same. If the user does not give the ending point as the same as starting point, this method closes the line at the starting point. public void fillPolygon(int xPoints[], int yPoints[], int nPoints) Draws a filled closed polygon specified by the arrays xPoints and yPoints and nPoints public void drawPolygon(Polygon p) Draws the outline of a polygon defined by the Polygon object P The following program 17.6 illustrates the use of two of the polygon drawing methods: Program 17.6 // This program illustrates the drawPolygon() method. /* <applet code = Polygon width =300 height =350 > </applet> */ import java.applet.Applet; import java.awt.Graphics; public class Polygon extends Applet { public void paint(Graphics gp) { int x [] = {110,60,10,10,60,110,160,210,210,160, 110,110}; int y [] = {60,10,60,160,210,160,210,160,60,10, 60,160}; int fx [] ={110,90,90,110,130,150,150,130,110}; int fy [] = {250,270,290,310,310,290,270,250,250}; int n = 12; int fn = 9; gp.drawPolygon(x, y, n); gp.drawString(“Polygon”, 90, 210); Graphics 379 gp.fillPolygon(fx, fy, fn); gp.drawString(“Filled Polygon”, 160, 300); showStatus(“Applet with Polygons”); } } The above program gives the following output: Fig.17.8 Output Screen for Program 17.6 17.6 Drawing Polyline The drawPolygon() method always draw a closed polygon. There is no way to draw an open-ended polygon. This is achieved through a drawPolyline() method. This method draws a series of connected lines. The method used for drawing such a polyline is : public void drawPolyline(int xPoints[], int yPoints[], int nPoints) Draws a sequence of connected lines, specified by the arrays xPoints and yPoints; each pair (x,y) gives one point. The number of points for the polyline is nPoints. The following program 17.7 shows the use of drawPolyline() method. 380 Programming in JAVA2 Program 17.7 // This program illustrates the drawPolyline() method. /* <applet code = Polyline width =300 height =250 > </applet> */ import java.applet.Applet; import java.awt.Graphics; public class Polyline extends Applet { public void paint(Graphics gp) { int x [] ={60,10,10,60,110,160,210,210,160}; int y [] ={10,60,160,210,160,210,160,60,10}; int n = 9; gp.drawPolyline(x, y, n); gp.drawString(“Polyline”, 90, 210); showStatus(“Applet with Polylines”); } } The above program gives the following output: Fig.17.9 Output Screen for Program 17.7 G The drawPolygon() method always draws a closed polygon, while the drawPolyline() method draws an open ended polygon. Graphics 381 17.7 Creating a Graphics Clip Once a window is created, its origin is at the point (0,0). For certain applications, you may need to work in a clip inside the original window. This clip may need to have its own origin for drawing objects inside the clip. For this purpose, a create() method is available for creating a new Graphics clip. The syntax of this method is: public Graphics create(int x, int y, int width, int height) Creates a new Graphics clip window having its origin at (x,y) with the specified width and height; the origin for the new clip is (x,y) with reference to the original window. The origin for the clip window created is (0,0). Within this clip, all co-ordinates can be specified relative to this point. Transfer of origin can also be done through translate() method. The following program 17.8, illustrates the use of create() method to create a new clip window: Program 17.8 // This program illustrates the create() method. /* <applet code = Cre width =200 height =220 > </applet> */ import java.applet.Applet; import java.awt.Graphics; public class Cre extends Applet { Graphics gr; public { int int int void paint(Graphics gp) x = 10, y = 10; width = 50, height = 80; xnew = 100, ynew = 50, widthnew = 200, heightnew = 200; gp.drawRect(x, y, width, height); gp.drawString(“Rectangle”, 10, 120); // creates a new clip gr = gp.create(xnew, ynew, widthnew, heightnew); gr.drawRect(x, y, width, height); gr.drawString(“Rectangle”, 10, 120); showStatus(“Rectangle in new Graphics window”); } } 382 Programming in JAVA2 The above program gives the following output: Fig.17.10 Output Screen for Program 17.8 17.8 Colors in Graphics In the previous chapter, we have seen that colors are handled in Color class. In addition to color constants that set fixed colors, methods are available to set arbitrary colors as desired by users. The colors of the window can also be obtained and analyzed. Any color can be generated by suitable combination of the primary colors, red, green and blue. Hence, color generated by this way is called RGB color. Colors can also be represented by hue, saturation and brightness. Color produced by this method is called HSB color. 17.8.1 Constructors for Color Class Colors can be set using the constructors of Color class. constructors are given below: Some of the public Color(int r, int g, int b) Creates an RGB color with the specified r(ed), g(reen) and b(lue) values; r, g and b can take value in the range 0 to 255. Alpha value is 255. public Color(int r, int g, int b, int a) Creates an RGB color with the specified r(ed) g(reen) b(lue) and a(lpha) values; r, g, b and a can take values in the range 0 to 255. public Color(int rgb) Creates an RGB color specified in the combined rgb value; this color consists of red component specified in bits 16 to 23, green component in bits 8 to 15 and blue component in bits 0 to 7. The default alpha value is 255. Graphics 383 public Color(float r, float g, float b) Creates an RGB color with the specified r(ed), g(reen) and b(lue) values; r, g and b can take values in the range 0.0 to 1.0. The alpha value is 255. public Color(float r, float g, float b, float a) Creates an RGB color with the specified r(ed), g(reen), b(lue) and a(lpha) values; r, g, b and a can take values in the range 0.0 to 1.0. The following program 17.9 shows the use of a few constructor methods of Color class: Program 17.9 // This program illustrates the use of color constructor // methods. /* <applet code = Colorcon1 width =200 height =100 > </applet> */ import java.applet.Applet; import java.awt.Graphics; import java.awt.Color; public class Colorcon1 extends Applet { Color bgclr, fgclr; public void init() { bgclr = new Color(10, 150, 250); fgclr = new Color(0.95f, 0.1f, 0.1f); setBackground(bgclr); setForeground(fgclr); } public void paint(Graphics gp) { gp.drawString(“Colorful constructors”, 20, 40); showStatus(“Color constructor”); } } The above program gives the following output: 384 Programming in JAVA2 Fig.17.11 Output Screen for Program 17.9 17.8.2 Color Methods Several methods are available in Color class to obtain, modify and to convert from one color model to another color model. Some of the methods are given in table 17.1. Table 17.1 Some of the Methods Defined in Color Class Method Purpose of the Method 1. public int getRed() Returns an int representing the red component of RGB color in the range 0 to 255 2. public int getGreen() 3. public int getBlue() Returns an int representing the green component of RGB color in the range 0 to 255 Returns an int representing the blue component of RGB color in the range 0 to 255 4. public int getAlpha() Returns an int representing the alpha component of RGB color in the range 0 to 255 5. public int getRGB() Returns an int representing the combined RGB color 6. public Color brighter() Returns a color which version of this RGB color 7. public Color darker() Returns a color which is a darker version of this RGB color 8. public String toString() Returns a string representation of this RGB color is a brighter Graphics 385 9. public static int HSBtoRGB(int h,int s,int b) Returns an int after converting the HSB color specified by h, s, b to its equivalent RGB color 10. public static float[] RGBtoHSB(int r,int g,int b, float[] hsbvals) Converts the RGB color specified by r, g, b to its equivalent components of HSB; returns a float array if the hsbvals argument is null, otherwise put the values into the array hsbvals 11. public static Color getHSBColor(float h, float s, float b) Returns an HSB color as specified by the h, s, b values; h, s and b takes value in the range 0.0 to 1.0. The following program 17.10 illustrates some of the methods of Color class: Program 17.10 // This program illustrates the use of color methods. /* <applet code = Colormeth width =350 height =200 > </applet> */ import java.applet.Applet; import java.awt.Graphics; import java.awt.Color; public class Colormeth extends Applet { String forecolor, backcolor; int rgbval; String rgb; Color bgclr, fgclr; int fgb, bgr; public void init() { bgclr = Color.getHSBColor(0.25f, 0.85f, 0.45f); fgclr = new Color(0.85f, 0.2f, 0.1f); setBackground(bgclr); setForeground(fgclr); } public void paint(Graphics gp) { gp.drawString(“Color methods”, 20, 40); forecolor = fgclr.toString(); backcolor = bgclr.toString(); rgbval = fgclr.getRGB(); 386 Programming in JAVA2 rgb = Integer.toBinaryString(rgbval); fgb = fgclr.getBlue(); bgr = bgclr.getRed(); gp.drawString(“F.g. color : “ + forecolor, 20, 60); gp.drawString(“B.g. color : “ + backcolor, 20, 80); gp.drawString(“F.g. - RGB Value : “ + rgb,20, 100); gp.drawString(“F.g. - Blue Value : “ + fgb, 20, 120); gp.drawString(“B.g. - Red Value : “ + bgr, 20, 140); showStatus(“ in every 3 sec foreground color changes to darker”); try { Thread.currentThread().sleep(3000); fgclr = fgclr.darker(); setForeground(fgclr); } catch (InterruptedException e) { ; } } } The above program gives the following outputs: Fig.17.12(a) Output Screen for the Program 17.10 When Started The output after a few seconds will give the following output: Graphics 387 Fig.17.12 (b) Output Screen After A Few Seconds After the Start of Program 17.10 17.9 Setting Paint Modes The paint mode decides the way the graphics objects are drawn on the window. Generally, when a graphics object is drawn, it overwrites the existing object at that location. If it is needed that all objects drawn at a place be visualized, then XOR mode of paint is to be selected. In this method, when drawing a second graphics object overlapping with an existing graphics object, the first object lying below the second can also be seen. In this method, when pixels of two objects are same at a point, the color, set in the XOR paint mode, is used at those points. This helps to contrast both objects. This is done by the following method in Graphics class: public void setXORMode(Color clr) The color clr is used when pixels of two graphics object at that location are the same. When two colors are different, an unpredictable color is used at that point. To return to the overwrite mode, the following method is used: public void setPaintMode() The following program 17.11 illustrates the use of the paint modes: Program 17.11 // This program illustrates the setPaintMode() and // setXORMode() methods. /* <applet code = Paintmode width =300 height =350 > </applet> */ import java.applet.Applet; import java.awt.Graphics; 388 Programming in JAVA2 import java.awt.Color; public class Paintmode extends Applet { public void paint(Graphics gp) { int x = 10, y = 25; int width = 100, height = 130; gp.drawRect(x, y, width, height); gp.drawString(“Rectangle”, 10, 170); gp.fillRect(80, 45, 70, 80); gp.drawString(“drawn in PaintMode”, 160, 100); gp.drawString(“Filled Rectangle”, 160, 170); gp.drawRoundRect(10, 180, 100, 130, 20, 20); gp.drawString(“Rounded Rectangle”, 10, 330); gp.setXORMode(Color.white); gp.fillRect(60, 140, 100, 130); gp.setPaintMode(); gp.drawString(“drawn in XORMode”, 150, 280); } } The above program gives the following output: Fig.17.13 Output Screen for Program 17.11 Graphics G 389 To visualize overlapping graphics, use XORMode. 17.10 Fonts in Graphics The fonts of text for display can be set according to the need of the user. Fonts loaded in the local computer system can be used for display. Java provides a variety of tools to set new fonts, manipulate their structure, size, style, etc. But only limited features that are needed for ordinary use are discussed in this section. We will see how to set new fonts family, fonts, size and style. To set new fonts, methods in Graphics class are used. The methods to study the fonts currently used are available in Font class. 17.10.1 Determining Fonts Available in the System The fonts family available in the local computer system can be obtained using the following methods defined in GraphicsEnvironment class of java.awt package. The constructors in this class are : abstract String[] getAvailableFontFamilyNames() Returns a String array containing the names of all font families available in the current Graphics Environment static GraphicsEnvironment getLocalGraphicsEnvironment() Returns the local GraphicsEnvironment To make use of the first method given above, one needs a GraphicsEnvironment object. To create a GraphicsEnvironment object, the second method defined above is used. In the following program 17.12, methods to obtain the font family names are illustrated: Program 17.12 // This program finds the font family available in this // system. /* <applet code = Fontfamily width =275 height =225 > </applet> */ import java.applet.Applet; import java.awt.Graphics; import java.awt.GraphicsEnvironment; public class Fontfamily extends Applet { 390 Programming in JAVA2 String fonts[]; public void paint(Graphics gp) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); fonts = ge.getAvailableFontFamilyNames(); showStatus(“Fonts Family in this System”); int size = fonts.length; gp.drawRect(10, 5, 240, 20); gp.drawRect(10, 30, 180, 15); gp.drawString(“The no of fonts family in this system : “ + (size + 1), 20, 20); gp.drawString(“The first ten font families are “, 20, 40); gp.drawRect(10, 45, 170, 160); for (int i = 0; i < 10; i++) gp.drawString(fonts[i], 20, (60 + i * 15)); } } The above program gives the following output: Fig.17.14 Output Screen for Program 17.12 17.10.2 Setting Fonts The Font class has methods to create fonts for drawing text on the screen. The constructor to create new font in Font class is: Font (String name, int style, int size) where name - is the name of the font family, style takes either the int value or the constants given below, Font.PLAIN Graphics 391 Font.BOLD Font.ITALIC Font.ITALIC + Font.BOLD size - is the font size. The logical family names defined in the JDK are: SansSerif Serif MonoSpaced Dialog DialogInput These font names are mapped to the fonts actually available in the local machine. Some of the methods defined in Font class are given in table 17.2. Table 17.2 Some of the Methods Defined in Font Class Method Purpose of the Method 1. public String getFamily() Returns the family name of this font 2. public String getName() Returns the logical name of this font 3. public String getFontName() Returns the font face name of this font Example : Serief.BOLD 4. public int getStyle() Returns the style of the font BOLD, ITALIC, BOLD+ITALIC 5. public int getSize() Returns an int representing the size of the font 6. public boolean isPlain() Returns true, if this font has a PLAIN style, otherwise false 7. public boolean isBold() Returns true if this font has a BOLD style, otherwise false 8. public boolean isItalic() Returns true if this font has a ITALIC style, otherwise false PLAIN, The following method is defined in Graphics class: public void setFont(Font font) Sets this graphics context’s font to the specified font The following program 17.13 illustrates some of the methods defined in Font class: 392 Programming in JAVA2 Program 17.13 // This program illustrates the use of getFont() method // in Graphics class. // setFont() method is from Graphics class // somasundaramk@yahoo.com /* <applet code = Fontmeth width =350 height =350 > </applet> */ import java.applet.Applet; import java.awt.Graphics; import java.awt.Font; public class Fontmeth extends Applet { public void paint(Graphics gp) { Font fnt = new Font(“SansSerif”, Font.BOLD, 20); gp.setFont(fnt); String fname = fnt.getName(); String fontname = fnt.getFontName(); int fsize = fnt.getSize(); int style = fnt.getStyle(); gp.drawString(“Font family used : “ + fname, 20, 20); gp.drawString(“Font used : “ + fontname, 20, 40); gp.drawString(“Font size used : “ + fsize, 20, 60); gp.drawString(“Font style : “ + style, 20, 80); fnt = new Font(“Serif”, Font.ITALIC, 15); gp.setFont(fnt); fname = fnt.getName(); fontname = fnt.getFontName(); fsize = fnt.getSize(); style = fnt.getStyle(); gp.drawString(“Font family used : “ + fname, 20, 100); gp.drawString(“Font used : “ + fontname, 20, 120); gp.drawString(“Font size used : “ + fsize, 20, 140); gp.drawString(“Font style : “ + style, 20, 160); fnt = new Font(“Dialog”, Font.ITALIC + Font.BOLD, 25); gp.setFont(fnt); fname = fnt.getName(); fontname = fnt.getFontName(); fsize = fnt.getSize(); style = fnt.getStyle(); gp.drawString(“Font family used : “ + fname, 20, 200); Graphics 393 gp.drawString(“Font used : “ + fontname, 20, 230); gp.drawString(“Font size used : “ + fsize, 20, 260); gp.drawString(“Font style : “ + style, 20, 290); } } The above program gives the following output: Fig.17.15 Output Screen for Program 17.13 After reading this chapter, you should have learned the following: Ü Graphics methods are defined in Graphics class in AWT package. Ü Graphics objects can be drawn only on a window. Ü There are several methods to draw regular shapes. Ü Background and foreground colors can be set in Graphics method. Ü Font size and type can be handled in Graphics class. In the next chapter, you will learn about event handling. 394 Programming in JAVA2 Worked Out Problems–17 Problem 17.1w Write a Java program to draw lines on a frame by pressing the mouse and dragging to another point like a pen tool in a paint tool. Program 17.1w /* ---------------------------------------------------------This program acts like a pen tool in a paint software. somasundaramk@yahoo.com ------------------------------------------------------------- */ import java.util.*; import java.awt.*; import java.awt.event.*; class Drawframe extends Frame { int mx1 = 0, my1 = 0, mx2 = 20, my2 = 50; Vector px = new Vector(); Vector py = new Vector(); int pointn = 0; int pcount = 0; Integer intg; public Drawframe() { px.insertElementAt(new Integer(mx1), pointn); py.insertElementAt(new Integer(my1), pointn); ++pointn; px.insertElementAt(new Integer(mx2), pointn); py.insertElementAt(new Integer(my2), pointn); addMouseListener(new Madapter(this)); addWindowListener(new Wadapter(this)); } public void paint(Graphics gp) { gp.drawString("Pen tool demo", 20, 40); pcount = px.size(); for (int i = 0; i < pcount - 1; i++) { int tx1 = ((Integer)px.elementAt(i)).intValue(); int tx2 = ((Integer)px.elementAt(i + 1)).intValue(); int ty1 = ((Integer)py.elementAt(i)).intValue(); int ty2 = ((Integer)py.elementAt(i + 1)).intValue(); gp.drawLine(tx1, ty1, tx2, ty2); } Graphics } } class Wadapter extends WindowAdapter { Drawframe df; Wadapter(Drawframe dfram) { df = dfram; } public void windowClosing(WindowEvent we) { System.exit(0); } } class Madapter extends MouseAdapter { Drawframe df; Madapter(Drawframe dfram) { df = dfram; } public void mousePressed(MouseEvent me) { int x1 = me.getX(); int y1 = me.getY(); df.pointn++; (df.px).insertElementAt(new Integer(x1), df.pointn); (df.py).insertElementAt(new Integer(y1), df.pointn); } public void mouseDragged(MouseEvent me) { int x2 = me.getX(); int y2 = me.getY(); df.pointn++; (df.px).insertElementAt(new Integer(x2), df.pointn); (df.py).insertElementAt(new Integer(y2), df.pointn); df.repaint(); } public void mouseReleased(MouseEvent me) { int x2 = me.getX(); int y2 = me.getY(); df.pointn++; (df.px).insertElementAt(new Integer(x2), df.pointn); (df.py).insertElementAt(new Integer(y2), df.pointn); df.repaint(); } 395 396 Programming in JAVA2 } class Prob171 { public static void main(String args []) { Drawframe frm = new Drawframe(); frm.setSize(300, 250); frm.setTitle("Pen Tool Demonstration"); frm.setVisible(true); } } The above program gives the following output: Fig.17.16 Output Screen for Program 17.1w Problem 17.2w Write a Java program to produce a rotating color disc: Program 17.2w /* ------------------------------------------------------------This program makes a rotating color disc. somasundaramk@yahoo.com <applet code = Prob172 width =350 height =200 > </applet> -------------------------------------------------------------*/ import java.applet.Applet; import java.awt.Graphics; import java.awt.Color; Graphics public class Prob172 extends Applet { String forecolor, backcolor; int rgbval; String rgb; Color bgclr, fgclr; int fgb, bgr; Color color [] = {Color.cyan,Color.red,Color.blue, Color.white,Color.orange,Color.pink }; public void init() { setBackground(Color.green); } public void paint(Graphics gp) { int colorn = color.length; gp.drawString(" Rotating Color Disc", 100, 20); int index; while (true) { for (int i = 0; i < colorn; i++) { index = Math.abs(colorn - i); if (index > 5) index = 0; gp.setColor(color[index]); gp.fillArc(20, 20, 150, 150, 0, 60); ++index; if (index > 5) index = 0; gp.setColor(color[index]); gp.fillArc(20, 20, 150, 150, 60, 60); ++index; if (index > 5) index = 0; gp.setColor(color[index]); gp.fillArc(20, 20, 150, 150, 120, 60); ++index; if (index > 5) index = 0; gp.setColor(color[index]); gp.fillArc(20, 20, 150, 150, 180, 60); ++index; if (index > 5) index = 0; gp.setColor(color[index]); gp.fillArc(20, 20, 150, 150, 240, 60); ++index; 397 398 Programming in JAVA2 if (index > 5) index = 0; gp.setColor(color[index]); gp.fillArc(20, 20, 150, 150, 300, 60); try { Thread.sleep(200); } catch (InterruptedException ie) { ; } } } } } The above program gives the following output: Fig.17.17 Output Screen for Program 17.2w Graphics 399 Exercise–17 I. Fill in the blanks 17.1. Graphics object can only be drawn on ________ . 17.2. A window can be created using ________ class or ________ class. 17.3. A ________ window is closable while _______ window is not closable. 17.4. The drawPolygon method always draws a _________ polygon. 17.5. To draw an open-ended polygon the _________ method can be used. 17.6. To visualize two graphics drawn at the same location ________ is to be used. 17.7. The terms BOLD, PLAIN, ITALIC specifies the ______ of a font. II. Write Java program for the following problems: 17.8. Write a program to draw a filled rectangle and expand continuously. 17.9. Write a program to draw a one-handed clock. 17.10. Write a green rectangle and print your address in red color on it. 17.11. Create a font of your choice and print your name in three font styles, each one having a different font size. 17.12. Write a program to simulate a bouncing rubber ball on a hard floor. Show at least 5 bounces. 17.13. Write a program to draw a word in font size 6, expanding to 96 font size and collapsing to initial size repeatedly. 17.14. Draw a polygon with 8 corners. * * * * * * 400 Programming in JAVA2 BLANK 401 Chapter 18 EVENT HANDLING In this chapter, you will learn about event handling. In a GUI environment, events such as mouse click, a key press, press of a button, etc. are to be captured and appropriate actions are to be carried out. Java uses a delegation event model to handle events and they are discussed in this chapter. 18.1 Delegation Event Model In a Graphical User Interface(GUI) environment, actions are initiated by the press of a button, click of a button, a key press, etc. Therefore, appropriate mechanisms are needed to capture such events and to react to the events by executing a piece of code. Java provides such mechanisms. Events in Java are handled by delegation event model. In this model, there is a source, which generates events. There is a listener, which can listen to the happenings of an event and initiate an action (fig. 18.1). 402 Programming in JAVA2 Register Source Event notification Listener Event Action Fig.18.1 Source and Listener of Events A listener has to register with a source. Any number of listeners can register with a source, except in a few cases. A listener can register with many event sources. When an event takes place, it is notified to the listeners, which are registered with the source. The listener then initiates an action. 18.2 Events An event is an object that describes the change of state of a source. For example, a mouse click is an event from the source mouse. The superclass of all events is java.util.EventObject. The superclass of all AWT events is java.util.AWTEvent and is a subclass of EventObject. The class hierarchy is given in fig.18.2. java.lang.Object java.util.EventObject java.awt.AWTEvent Fig.18.2 Class Hierarchy of AWT Event Class AWTEvent class is an abstract class and contains many subclasses, which are concrete and are packaged in java.awt.event. One important method defined in AWTEvent class is getID(), which returns an int representing the type of event. G An event is an object that describes the change of state of a source. Event Handling 403 Some of the classes defined in java.awt.event package are given in table 18.1. All of them are subclasses of AWTEvent class. Table 18.1 Some of the Event Classes Defined in java.awt.event Name of Class Event Dealt 1. ActionEvent This class deals with high-level event. The event occurs when the componentspecific action takes place 2. AdjustmentEvent This class deals with events generated by the adjustable objects like scrollbar 3. ComponentEvent This class deals with the lower-level event. The event occurs when the component is moved, resized or visibility is changed 4. ItemEvent This class deals with the events generated when a check box or list item is clicked 5. KeyEvent This class deals with the events generated by key strokes 6. MouseEvent This class deals with events generated by mouse clicks and movements 7. TextEvent This class deals with events generated by the change of object’s text 8. WindowEvent This class deals with events generated by the change of window status The event class hierarchy is given in fig. 18.3. 404 Programming in JAVA2 java.lang.Object java.util.EventObject java.awt.AWTEvent Action Event Adjustment Event InputMethod Event Container Event Focus Event KeyEvent Component Event Input Event Invocation Event Paint Event Item Event Text Event Window Event MouseEvent Fig.18.3 Event Class Hierarchy 18.2.1 The ActionEvent Class An ActionEvent is generated when a button is pressed or a menu item is selected. This is a high-level or semantic event. This is in contrast to a lowlevel event like mouse click. This class has the following int type constants. ALT_MASK - The alt modifier An indicator that the alt key was held down during the event CTRL_MASK - The control modifier An indicator that the control key was held down during the event META_MASK - The meta modifier An indicator that the meta key was held down during the event SHIFT_MASK - The shift modifier An indicator that the shift key was held down during the event Event Handling 405 Constructors The constructors for ActionEvent class are : ActionEvent (Object src, int id, String cmd) ActionEvent (Object src, int id, String cmd, int modifier) where src is the source object that generated this event, id is an int that identifies the event, cmd is the command associated with the event and modifier indicates which modifier key was pressed when the event was generated. Methods Some of the methods defined in ActionEvent class are : String getActionCommand() Returns the command name for the invoking ActionEvent object int getModifier() Returns an int value that indicates which modifier key was pressed when the event was generated String paramString() Returns a string identifying the event 18.2.2 The AdjustmentEvent Class The adjustment event is generated by a scroll bar. Five types of adjustment events are defined for the adjustment of a scroll bar. Each type is identified by an integer constant. The constants are: BLOCK_DECREMENT - The mouse is clicked inside the scroll bar to decrease its value BLOCK_INCREMENT - The mouse is clicked inside the scroll bar to increase its value TRACK - The slider is dragged UNIT_DECREMENT - The button at the end of the scroll bar is clicked to decrease its value UNIT_INCREMENT - The button at the end of the scroll bar is clicked to increase its value The constants representing the different locations of a scroll bar are shown in fig. 18.4. 406 Programming in JAVA2 Fig.18.4 Constants Representing Different Locations on a Scroll Bar Other integer constant associated with the event is: ADJUSTMENT_VALUE_CHANGED , which represents the adjustment value changed event. Constructor The constructor for this class is: AdjustmentEvent(Adjustable src, int id, int type, int value) where src is the adjustable object where the event originated, id is the event type, type is the adjustment type, value is the current value of the adjustment. Methods The methods defined in this class are : Adjustable getAdjustable() Returns the adjustable object where this event originated int getAdjustableType() Returns the type of adjustment which caused the value changed event Event Handling 407 int getValue() Returns the current value in the adjustment event String paramString() Returns a string representing the state of this event 18.2.3 The ComponentEvent Class A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Buttons, checkboxes and scroll bars are examples for component. Events generated by these components are called component events. An event is generated when a component is moved, changed in size or changed in visibility. It is a low-level event. The event class has the following integer constants, each representing an event: COMPONENT_MOVED - This event indicates position has changed that COMPONENT_RESIZED - This event indicates that the component size has changed COMPONENT_SHOWN - This event indicates was made visible COMPONENT_HIDDEN - This event indicates that the component was made invisible that the the component Constructor This class has the following constructor: ComponentEvent(Component src, int id) where src is the component object that generated event and id indicates the type of event. Methods The methods defined in this class are : Component getComponent() Returns the originator of the event String paramString() Returns the string identifying the event component 408 Programming in JAVA2 18.2.4 The ItemEvent Class A semantic event indicates that an item, like check box or choice is selected or deselected. This is a high-level event. The following integer constants are defined in this class representing an event: DESELECTED This state change value indicates that an item is deselected ITEM_STATE_CHANGED This event indicates that an item’s state has changed SELECTED This state change value indicates that an item is selected Constructor The constructor for this ItemEvent class is : ItemEvent(ItemSelectable src, int id, Object item, int stateChange) where, src is the ItemSelectable object that originated the event, id indicates the type of event, item is an object that is affected by the event, stateChange indicates whether the item was selected or deselected. Methods Methods defined in this class are : ItemSelectable getItemSelectable() Returns the ItemSelectable object that originated the event Object getItem() Returns the item Object that was affected by the event int getStateChange() Returns an integer that indicates whether the item was selected or deselected String paramString() Returns a string identifying the event 18.2.5 The KeyEvent Class The key event is generated when a key is pressed, typed or released. The key typed event is generated only when a character is generated. For example, pressing an Alt key does not produce a character. Java uses Virtual Key code to represent which key on the keyboard has been pressed rather than which character was generated. There are several integer constants defined in this class. Some of them are given below: Event Handling KEY_TYPED KEY_PRESSED KEY_RELEASED VK_0 to VK_9 VK_A to VK_Z This event This event This event Represents Represents is generated when a character is entered. is generated when a key is pushed down. is generated when a key is released. the keys ASCII 0 to ASCII 9 the keys ASCII A to ASCII Z Other Virtual Key (VK) constants which are self explained are : VK_ENTER VK_CANCEL VK_CONTROL VK_SPACE VK_LEFT VK_DOWN VK_DELETE VK_LESS VK_BACK_SPACE VK_CLEAR VK_CAPS_LOCK VK_PAGE_UP VK_UP VK_COMMA VK_F1 to VK_F24 VK_CUT VK_TAB VK_SHIFT VK_ESCAPE VK_PAGE_DOWN VK_RIGHT VK_MINUS VK_AMPERSAND VK_COPY Constructors The constructors defined in this class are: KeyEvent (Component src, int id, long when, int modifier, int keycode, char keyChar) KeyEvent (Component src, int id, long when, int modifier, int keyCode) where, src is the Component that originated the event, id is an integer identifying the event type, when is a long integer which specifies the time at which the event occured, modifier is the modifier key down during the event, keyCode is the integer code for an actual key, keyChar is the Unicode character generated by this event. Methods Methods defined in this class are : int getKeyCode() Returns the integer code for an actual key on the keyboard void setKeyCode(int keyCode) Sets the keyCode value to represent a physical key void setKeyChar(char keyChar) Sets the keychar value to represent a logical character 409 410 Programming in JAVA2 char getKeyChar() Returns the Unicode character defined for this key event; if no valid Unicode character is defined for this event, the character generated is CHAR_UNDEFINED. String getKeyText(int keyCode) Returns a String describing the keyCode such as “HOME”, “F1” or “E” String getKeyModifierText(int modifiers) Returns a String describing the modifier keys such as “Shift” or “shift + ctrl” that were held down during the event boolean isActionKey() Returns true if the key is an action key String paramString() Returns a parameter string identifying this event 18.2.6 The MouseEvent Class A mouse event is generated by mouse action in a component. The following events are generated in a component by a mouse action. Two types of events, mouse event and mouse motion event, are generated by a mouse. Mouse events are generated when a mouse button is pressed, released, clicked, mouse enters a component or mouse exits a component. Mouse motion events are generated when the mouse is moved or dragged. The following integer constants are defined for the mouse events: MOUSE_CLICKED This represents the mouse clicked event. This MouseEvent occurs when a mouse button is pressed and released. MOUSE_ENTERED This represents the mouse entered event. This MouseEvent occurs when a mouse cursor enteres a component’s area. MOUSE_EXITED This represents the mouse exited event. This MouseEvent occurs when a mouse cursor exits a component’s area. MOUSE_PRESSED This represents mouse pressed event. This MouseEvent occurs when a mouse button is pushed down. MOUSE_RELEASED This represents mouse released event. This MouseEvent occurs when a mouse button is released. Event Handling 411 MOUSE_DRAGGED This represents a mouse dragged event. This MouseMotionEvent occurs when a mouse is dragged MOUSE_MOVED This represents a mouse moved event. This MouseMotionEvent is generated when the mouse is moved Constructor The constructor for this class is: MouseEvent(Component src, int id, long when, int modifiers, int x, int y, int clickCount, boolean pupTrig) where src is the Component that originated the event, id identifies the event, when gives the time the event occurred, modifiers is the modifier key down during the event, x is the x co-ordinate of the mouse location, y is the y co-ordinate of the mouse location, clickCount is the number of mouse clicks associated with the event, pupTrig is true, if this event is a trigger for a popup menu. Methods Methods defined in this class are: int getX() Returns an integer representing the x position of the event relative to the component int getY() Returns an integer representing the y position of the event relative to the component void translatePoint(int x, int y) Translates the event’s co-ordinates to a new position by adding x and y to the x and y of the current position int clickCount() Returns the number of clicks associated with this event boolean isPopupTrigger() Returns true, if this event is the popup–menu trigger for this platform String paramString() Returns a string identifying this event 412 Programming in JAVA2 18.2.7 The TextEvent Class A text event is generated when the text of an object is changed. This class has an integer constant TEXT_VALUE_CHANGED, which indicates that the object’s text is changed. Constructor This class has the following constructor: TextEvent(Object src, int id) where src is the text component object that originated the event and id identifies the type of event. Method The method defined in this class is: String paramString() Returns a string identifying this text event 18.2.8 The WindowEvent Class A window event indicates the change in the status of the window. This event is generated when it is opened, closed, about to close, activated, deactivated, iconified or deiconified. This class has integer constants that represent different window events. Some of them are given below: WINDOW_ACTIVATED WINDOW_CLOSED WINDOW_CLOSING WINDOW_DEICONIFIED WINDOW_ICONIFIED WINDOW_OPENED This represents a window activated-event. This event occurs when the window becomes the user’s active window. This represents a window-closed event. This event occurs after the window has been closed. This represents a window is closing event. This event occurs when the user attempts to close the window from the windows system menu. This represents a window-deiconified event. This event occurs when the window has been changed from a minimized state to a normal state. This represents a window iconified event. This event occurs when the window has been changed from a normal state to a minimized state. This represents a window-opened event. This event occurs when the window is made visible. Event Handling 413 Constructor The constructor for this class is: WindowEvent(Window src, int id) where, src is the Window object that originated the event and id indicates the type of event. Method The method defined in this class is: Window getWindow() Returns the Window object that originated the event 18.3 Event Listeners As mentioned earlier, when events occur they are notified to listeners, which are registered with the source. An event listener has to initiate some action when the happening of an event is notified to it. What action is to be taken depends on the problem handled by the programmer. Therefore, the methods designed to handle events are to be open. Several interfaces are designed for listeners with event as a type signature. The listener interfaces are defined in java.awt.event package. Some of the listener interfaces are given in table 18.2. Table 18.2 Some Listener Interfaces and Methods Defined in Them Name of Interface Interface Methods 1. ActionListener void actionPerformed(ActionEvent ae) 2. AdjustmentListener void adjustmentValueChanged (AdjustmentEvent ae) 3. ComponentListener void void void void 4. ItemListener void itemStateChanged(ItemEvent ie) 5. KeyListener void keyPressed(KeyEvent ke) void keyReleased(KeyEvent ke) void keyTyped(KeyEvent ke) componentHidden(ComponentEvent ce) componentMoved(ComponentEvent ce) componentResized(ComponentEvent ce) componentShown(ComponentEvent ce) 414 Programming in JAVA2 6. MouseListener void void void void void mouseClicked(MouseEvent me) mouseEntered(MouseEvent me) mouseExited(MouseEvent me) mousePressed(MouseEvent me) mouseReleased(MouseEvent me) 7. MouseMotionListener void mouseDragged(MouseEvent me) void mouseMoved(MouseEvent me) 8. TextListener void textValueChanged(TextEvent te) 9. WindowListener void void void void void void void windowActivated(WindowEvent we) windowClosed(WindowEvent we) windowClosing(WindowEvent we) windowDeactivated(WindowEvent we) windowDeiconified(WindowEvent we) windowIconified(WindowEvent we) windowOpened(WindowEvent we) 18.4 Registering Listeners with Source Listeners have to register with the event source to get event notification. add methods are used for registering. All types of listeners have the same syntax for the add method. The general form of add method is : public void addTypeListener(TypeListener el) where type indicates the type of event and el is the event listener. For example, for mouse motion event, addMouseMotionListener() is used. The add methods defined in various classes are given in table 18.3. Table 18.3 Some of the add/remove Methods Defined in Component Class Method 1. 2. 3. 4. 5. 6. 7. 8. 9. addComponentListener(ComponentListener cl) addKeyListener(KeyListener kl) addMouseMotionListener(MouseMotionListener ml) addMouseListener(MouseListener ml) removeKeyListener(KeyListener kl) removeMouseMotionListener(MouseMotionListener ml) removeMouseListener(MouseListener ml) addWindowListener(WindowListener wl) removeWindowListener(WindowListener wl) Class Component Component Component Component Component Component Component Window Window Event Handling 10. addActionListener(ActionListener al) Button, List, MenuItem, TextField 11. removeActionListener(ActionListener al) TextField 12. addAdjustmentListener(AdjustmentListener al) Scrollbar 13. addItemListener(ItemListener il) G 18.5 415 Check box CheckboxMenuItem Choice, List Listeners listen to the occurrence of an event and take appropriate action. Listeners have to register with an event source. add methods are used for registering with the source. Example Programs Having seen what an event is, how it is generated and how to listen to such events, we will see how to write programs to handle the events. 18.5.1 Mouse Event Handling To listen to an event, all the methods in the corresponding listener interface are to be implemented. There are five MouseEvent and two MouseMotionEvent. To handle them, MouseEventListener and MouseMotionListener interfaces are to be implemented. Further, to register the listener with the event source, addMouseEventListener and addMouseMotionListener methods are to be used. The following program 18.1 illustrates the use of mouse handling methods: Program 18.1 // This program illustrates the use of MouseEvent // and MouseMotionEvent methods. /* <applet code = Mouse1 width = 200 height =100 > </applet> */ import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; 416 Programming in JAVA2 import java.awt.event.*; public class Mouse1 extends Applet implements MouseListener, MouseMotionListener { String txt = “ Nothing”; int x = 10, y = 30; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { txt = “Mouse Clicked”; repaint(); } public void mouseEntered(MouseEvent me) { txt = “Mouse Entered”; repaint(); } public void mouseExited(MouseEvent me) { txt = “Mouse Exited”; repaint(); } public void mousePressed(MouseEvent me) { txt = “Mouse Pressed”; setForeground(Color.cyan); repaint(); } public void mouseReleased(MouseEvent me) { txt = “Mouse Released”; setForeground(Color.magenta); repaint(); } public void mouseDragged(MouseEvent me) { txt = “Mouse Dragged”; setForeground(Color.red); repaint(); } public void mouseMoved(MouseEvent me) { txt = “Mouse Moved”; setForeground(Color.green); repaint(); Event Handling 417 } public void paint(Graphics gp) { gp.drawString(txt, 20, 40); showStatus(“Mouse event handling”); } } The above program gives the following outputs for various mouse events: Fig.18.5 Output Screens for Program 18.1 (Six Screens) 18.5.2 Key Event Handling The following program 18.2 illustrates the use of KeyEventListener and KeyEvent methods: 418 Programming in JAVA2 Program 18.2 // This program illustrates the use of KeyEvent /* <applet code = Key width = 200 height =100 > </applet> */ import java.applet.Applet; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class Key extends Applet implements KeyListener { String txt = “ “; String txt1 = “ “; String txt2 = “ “; String txt3 = “ “; int kcode; char ch; int drawnnumber; public void init() { addKeyListener(this); requestFocus(); } public void keyTyped(KeyEvent ke) { ch = ke.getKeyChar(); txt1 += ch; if (txt1.length() > 25) txt1 = “ “; txt = “Key Typed “; repaint(); } public void keyPressed(KeyEvent ke) { kcode = ke.getKeyCode(); if (kcode == ke.VK_F1) txt2 = “You have typed F1 key”; if (kcode == ke.VK_SHIFT) txt3 = “You have typed Shift key”; txt = “Key Pressed”; repaint(); } public void keyReleased(KeyEvent ke) { txt = “Key released”; repaint(); methods. Event Handling 419 } public void paint(Graphics gp) { gp.drawString(txt, 20, 20); gp.drawString(txt1, 20, 40); gp.drawString(txt2, 20, 60); gp.drawString(txt3, 20, 80); showStatus(“Key events”); } } The above program gives the following output: Fig.18.6 Output Screen for Program 18.2 In program 18.2, the method requestFocus() is required to receive the key strokes. 18.5.3 Window Event Handling The following program 18.3 illustrates the use of methods in WindowListener interface and WindowEvent class. For handling window events, there are seven interface methods. All methods of the interface are to be implemented whether they are used in the program or not. In the following program, window is created using Frame class. A window created from Frame does not have a default window closing method. Hence, window closing event is captured and System.exit(0) is called to close the window. Program 18.3 /* This program illustrates the use of methods in the WIndowListener interface. The window is closed by capturing the WindowClosing event. Whether you need one or all methods, you must implement all interface methods. */ import java.awt.Graphics; import java.awt.Frame; import java.awt.event.WindowEvent; 420 Programming in JAVA2 import java.awt.event.WindowListener; class Myframe extends Frame implements WindowListener { String txt1 = “ “; String txt2 = “ “; String txt3 = “ “; Myframe(String title) { super(title); setSize(200, 150); addWindowListener(this); } public void windowActivated(WindowEvent we) { txt1 = “Window activated”; } public void windowClosed(WindowEvent we) { ; } public void windowClosing(WindowEvent we) { System.exit(0); } public void windowDeactivated(WindowEvent we) { txt2 = “Window deactivated”; } public void windowDeiconified(WindowEvent we) { txt3 = “Window deiconified”; } public void windowIconified(WindowEvent we) { ; } public void windowOpened(WindowEvent we) { ; } public void paint(Graphics gp) { gp.drawRoundRect(15, 25, 90, 20, 10, 5); gp.drawString(“Window Event”, 20, 40); gp.drawString(“Click X in the window to close”, 20, 60); gp.drawString(txt1, 20, 80); gp.drawString(txt2, 20, 100); Event Handling 421 gp.drawString(txt3, 20, 120); } } public class Winevent { public static void main(String args []) { Myframe mframe = new Myframe(“Window Events”); mframe.setVisible(true); } } The above program gives the following screen output: Fig.18.7 Output Screen for Program 18.3 G Frame window does not have the conventional window closing method. Hence, manual coding is to be used (like system.exit(0)) to close the window. 18.6 Adapter Classes In the previous section, we have seen that interface listeners are used to handle various types of events. Each interface has one or more methods. To use any one method in the interface, all methods are to be implemented. In many occasions, one or two methods may be needed out of several methods in an interface. For example, to use a windowClosing method in windowListener interface, all other six methods are to be implemented with null statements. This is a cumbersome process. To solve this problem, classes have been designed which implement all the methods of an interface, each method with a do-nothing code. Such classes are called Adapter classes. All interfaces that have more than one method have a campanion Adapter class. Subclasses of these Adapter classes can be created, in which the required method can be implemented. Subclasses of Adapter classes can implement one or more methods of the interface method, but not all of them. 422 Programming in JAVA2 G An adapter class implements all the methods of an interface with do-nothing codes. When a few out of several interface methods are needed in an application, the adapter classes can be subclassed. This avoids implementing all unwanted interface methods. Interfaces having two or more methods have corresponding adapter classes. The following program 18.4, illustrates the use of WindowAdapter of the windowListener interface: Program 18.4 /* This program illustrates the use of WindowAdapter. Adapter class helps to reduce the burden of implementing all interface methods other than the required ones. */ import java.awt.Graphics; import java.awt.Frame; import java.awt.event.WindowEvent; import java.awt.event.WindowAdapter; class winclose extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } class Myframe extends Frame { Myframe(String title) { super(title); setSize(200, 150); winclose wc = new winclose(); addWindowListener(wc); } public void paint(Graphics gp) { gp.drawRoundRect(15, 25, 150, 20, 10, 5); gp.drawString(“WindowAdapter demo”, 20, 40); gp.drawString(“Click x in the window to close”, 20, 60); Event Handling 423 } } public class Winadapt { public static void main(String args []) { Myframe mframe = new Myframe(“Window Events”); mframe.setVisible(true); } } The above program gives the following screen output: Fig.18.8 Output Screen for Program 18.4 After reading this chapter, you should have learned the following: Ü Events are change of state of a source. Ü Mouse, keyboard, buttons, checkboxes, scroll bar, text field act as source of events. Ü Methods in listener interfaces can be used to capture events and take appropriate action. Ü An adapter class implements all methods of an interface with a do-nothing code. Ü Adapter classes provide an alternative and short-cut method to implement interfaces. In the next chapter, you will learn about Swing and GUI components. 424 Programming in JAVA2 Worked Out Problem–18 Problem 18.1w Write an applet that will accept a text from a keyboard and display it on the screen as a moving text from right to left. Use key event to input the text. Program 18.1w /* ------------------------------------------------------------This program accepts the keys typed on the keyboard, makes a string and displays it as a moving text. somasundaramk@yahoo.com <applet code = Prob181 width = 500 height =100 > </applet> ------------------------------------------------------------- */ import java.applet.*; import java.awt.*; import java.awt.event.*; public class Prob181 extends Applet implements KeyListener, Runnable { String msg = " "; String submsg = " "; char fchr; int kcode; char ch; Font ft; boolean bigsize = false; boolean thstart = false; Thread th; public void init() { ft = new Font("Serif", Font.PLAIN, 65); addKeyListener(this); requestFocus(); } public void keyTyped(KeyEvent ke) { ch = ke.getKeyChar(); msg += ch; if (msg.length() > 45) msg = " "; repaint(); } Event Handling public void keyPressed(KeyEvent ke) { kcode = ke.getKeyCode(); if (kcode == ke.VK_ENTER) { bigsize = true; thstart = true; repaint(); } } public void start() { th = new Thread(this); } public void run() { while (true) { fchr = msg.charAt(0); submsg = msg.substring(1); msg = submsg + fchr; try { Thread.currentThread().sleep(300); } catch (InterruptedException ie) { System.out.println("Interrupt error"); } repaint(); } } public void keyReleased(KeyEvent ke) { repaint(); } public void paint(Graphics gp) { gp.drawString("Type a text for display and Press Enter Key", 20, 90); if (bigsize) { gp.setFont(ft); } if (thstart) { th.start(); thstart = false; } 425 426 Programming in JAVA2 gp.drawString(msg, 20, 60); showStatus("Moving Text"); } } The above program gives the following output: (a) (b) Fig.18.9 Output Screens for Program 18.1w Event Handling 427 Exercise-18 I. Fill in the blanks: 18.1. Pressing a button of a mouse causes _________ event. 18.2. An event is generated by a ________ . 18.3. Java implements _______ model to handle events. 18.4. ________ is a consumer of events. 18.5. To get an event notification, a listener has to ________ with the _____. 18.6. To receive key strokes, the ________ method is to be called. 18.7. A class with do-nothing methods as an alternative to listener interface is called ______ class. 18.8. A user can implement (override) one or more number of methods of an adapter class but not ________ . 18.9. The general form of the method to register a listener with the event source is _______ . II. Write a Java program for the following: 18.10. Write a program in which a sound clip is played when mouse is dragged. 18.11. Write a program to capture key events. When a (or A) is typed, APPLE is to be displayed on the applet window. 18.12. Write a program to implement MouseAdapter Class. * * * * * * mouseClicked method using 428 Programming in JAVA2 BLANK 429 Chapter 19 SWING AND GUI COMPONENTS In this chapter, creation of Graphical User Interface (GUI) screens using graphical components like buttons, labels, checkboxes defined in Swing classes are explained. 19.1 The Origin of Swing Creation of a user-interface screen is an important feature of any modern computer language. Initially, Java introduced a package called Abstract Window ToolKit(AWT). This package contained a large number of classes and interfaces that supported the creation of Graphical User Interface(GUI) components on user-interface screens. As the goal of Java developers was to create platformindependent programs, the AWT classes made use of the native methods of the respective machines. That is, the AWT made use of graphical methods defined for Windows OS for Windows machines, made use of graphical methods defined for Mac OS for Macintosh machines. As a result, the appearance (look and feel) of the screen was different for different platforms. Therefore, to have the same appearance of the screen called pluggable look and feel (pl and f) in all platforms, new classes were added in the new versions of Java.(versions after JDK 1.1). These new classes are packed in Swing. Java2 contains Swing. The Swing classes are a part of the Java Foundation Classes(JFC). The Swing classes are contained in a Java extension package called javax.swing. The methods in the Swing classes do not use the native graphical methods directly, but use them as interfaces. Methods in Swing classes are written purely in Java. The methods in Swing classes can be used to create screens with the same look and feel of the screens in different platforms. Swing classes have methods, which are far superior in capabilities than those in the corresponding AWT classes. 430 Programming in JAVA2 The Swing classes are subclasses of java.awt.Container and java.awt.Component. The name of the Swing class starts with the letter J. The top-level class of Swing is JComponent. JComponent is both a container and a component. GUI components like button, label, checkbox, panel, text, etc., are handled in JComponent class. GUI components can be added on a panel window or a frame window. The frame in Swing is handled in JFrame class. The JComponent class and AWT class hierarchy is shown in fig.19.1. Object java.awt.Component java.awt.Container JComponent Window Frame JFrame Fig.19.1 Class Hierarchy of AWT, JComponent and JFrame 19.1.1 JComponent The JComponent class is a subclass of Container. This class contains a large number of subclasses, which define components like JButton, JLabel, which act as user-interface components. The subclasses of JComponent are given in fig.19.2. Swing and GUI Components JComponent AbstractButton JButton JMenuIem JCheckBoxMenuItem JMenu JRadioButtonMenuItem JToggleButton JCheckBox JRadioButton JComboBox JInternalFrame JLabel DefaultTableCellRenderer JLayeredPane JDesktopPane JList JMenuBar JOptionPane JPanel ColorChooserPanel JPopupMenu JProgressBar JRootPane JScrollPane JSeparator JSlider JSplitPane JTabledPane JTable JTableHeader JTextComponent JEditorPane JTextPane JTextArea JTextField JPassWordField JToolBar JToolTip JTree JViewport Fig.19.2 Subclasses of JComponent 431 432 Programming in JAVA2 19.2 Creating Windows in Swing A conventional window is created in Swing in a top-level window. The top-level window is supported by JFrame, JApplet, JDialog and JWindow classes. They are called root containers. These root containers have several panes, JRootPane, JMenuBar, JLayeredPane, ContentPane and GlassPane, as shown in fig. 19.3. JFrame _ JRootPane JRootPane JMenuBar JLayeredPane ContentPane Glass pane Fig.19.3 Structure of Root Containers The above container model is implemented in JRootPane class. The root container classes have methods that forward requests to the JRootPane. These methods are defined in the RootPaneContainer interface. The most frequently used method to get the content pane is: getContentPane() which returns a container object In Swing, user-interface components like button, checkbox and setting out layout managers must be done on a content pane. The components are added to the content pane using add() method. Therefore to create a user-interface window, the following steps are to be followed: Create a root container using JFrame or JApplet or JDialog or JWindow. — Get the container using getContentPane method. — Create components. — Attach the components to a container using add() method. — Swing and GUI Components 433 In the following sections, we will see how different user-interface screens with different components are created. As Swing is an extension of AWT, some of the classes defined in AWT are still used. G All user-interface components are to be drawn only on a content pane. 19.2.1 Creating JFrame Windows A JFrame window is a standard style window. JFrame is a subclass of Frame class. When a JFrame window is created, its size is (0,0) and is invisible. A JFrame window, though containing Iconify, Minimize and Close icons, the Close option, just sets the window invisible and does not close the window. A JFrame generates the following window events: windowOpened windowClosed windowDeiconified windowDeactivated windowClosing windowIconified windowActivated These window events are handled in java.awt.event package. Constructors A JFrame window is created with the following constructors: JFrame() Creates an invisible window without a title JFrame(String title) Creates an invisible window with a title given by the String title Methods The JFrame class has numerous inherited methods and some of its own. Some of them are : String getTitle() Returns a string representing the title of the frame void setTitle(String title) Sets the title of the frame to this string void setVisible(boolean b) Shows or hides this frame window If b is true, it shows the window, otherwise it hides it. 434 Programming in JAVA2 void setSize(int width, int height) Sets the size of the window to the specified width and height in pixels void setLayout(LayoutManager mgr) Sets the layout manager for this container int getX() Returns the X component of the window location int getY() Returns the Y component of the window location void setLocation(int x, int y) Moves the frame window to a new location on the screen; corner of the window is specified by x and y. the top left int getHeight() Returns the current height of the window int getWidth() Returns the current width of the window Once a JFrame window is created, there is no way to close it. The simplest manual method is to press CTRL + C in DOS mode to close the window. The other method is to capture the windowClosing event through WindowListener and call the System.exit(0) method. The following program 19.1 illustrates the creation of a JFrame window: Program 19.1 // This program creates a blank JFrame window. // somasundaramk@yahoo.com import javax.swing.JFrame; class JFrame1 { public static void main(String args []) { JFrame f = new JFrame(“Blank JFrame”); f.setSize(200, 200); f.setVisible(true); } } The above program gives the following output screen: Swing and GUI Components 435 Fig.19.4 Output Screen for Program 19.1 If you try to close this window using close window icon, the window will disappear from the screen, but will not be closed. In DOS mode, press the CTRL+C key to close the window. In order to close the window, we include methods to capture window closing event and call System.exit(0). In the following program 19.2, we show how to close the JFrame window by trapping window closing event. Program 19.2 // This program creates a blank JFrame window. // This JFrame window can be closed. // somasundaramk@yahoo.com import javax.swing.JFrame; import java.awt.event.WindowAdapter; import java.awt.event.*; // class to handle windowclosing event class winclose extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } class JFrame2 { public static void main(String args []) { JFrame f = new JFrame(); winclose wc = new winclose(); f.addWindowListener(wc); f.setTitle(“Closable JFrame”); f.setSize(200, 200); f.setVisible(true); 436 Programming in JAVA2 f.setLocation(50, 100); } } The above program gives the following output: Fig.19.5 Output Screen for Program 19.2 In program 19.2, the winclose class handles the windowClosing event. The window events are handled in java.awt.event package and hence it is imported. Initially, the frame window is created without a title. The title “Closable JFrame” is set using the setTitle() method. This title appears on the window border. The size of the window created is 200 x 200 pixel size. By default, this window will appear at (0,0) position of the screen. The setVisible(true) method makes the window visible. The window created is shifted to the new location (50,100) on the screen by the setLocation() method. In the following program 19.3, the window closing event is handled in an anonymous inner class and is an improved version of program 19.2. Program 19.3 // This program creates closable blank JFrame window // using an anonymous inner class. // somasundaramk@yahoo.com import javax.swing.JFrame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; class JFrame4 extends JFrame { JFrame4(String title) { super(title); // using anonymous inner class Swing and GUI Components 437 addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setSize(200, 200); setVisible(true); setLocation(50, 100); } public static void main(String args []) { new JFrame4(“Closable JFrame”); } } Program 19.3 gives the same output as that of program 19.2. 19.3 JButton The JButton is a concrete subclass of AbstractButton, which is a subclass of JComponent. The counterpart of JButton in AWT is Button. The JButton class is used to create labeled button components. When a button is clicked, an ActionEvent is created. Both mouse press and mouse release events can be processed separately. If an application wants to perform some action based on the button being pressed and released, it should implement the interface ActionListener and register the listener to receive events from the button. One of the advanced features of JButton is that an image can be used as a button. 19.3.1 Creating JButtons Constructors used for creating a JButton component are: JButton() Constructs a button with no label JButton(String label) Constructs a button with a specified label JButton(Icon i) Constructs a button with the icon i as button JButton(String label, Icon i) Constructs a button with the icon i as button and the string as label 438 Programming in JAVA2 Methods Some of the methods defined in a JButton class are : void addActionListener(ActionListener al) Adds the specified action listener to receive action event from this button String getActionCommand() Returns the command name of the action event fired by this button void removeActionListener(ActionListener al) Removes the action listener al so that it no longer receives action events from this button void processActionEvent(ActionEvent ae) Processes the action events occurring on this button by dispatching them to any action listener object void setText(String label) Sets the button’s label to the specified string void getText() Returns the label of the button Icon getIcon() Returns the icon of the button void setIcon(Icon i) Sets the icon for this button void setRolloverIcon(Icon i) Sets the icon i as the rollover icon for this button 19.3.2 Creating JButtons on JFrame As we have seen in the earlier section, JFrame is a top-level container. All the components can be added only on the content pane of JFrame. To get the content pane getContentPane() method is used, which returns a Container type object defined in java.awt package. The following program 19.4 shows how to add a JButton on a JFrame: Program 19.4 // This program illustrates the use of JButton class. // The Jbuttons are placed on JFrame window. // somasundaramk@yahoo.com import java.awt.*; import java.awt.event.*; import javax.swing.*; Swing and GUI Components 439 class JFrmb1 extends JFrame { JButton b1, b2, b3; Container con; JFrmb1(String s) { super(s); setSize(250, 150); con = getContentPane(); b1 = new JButton(“ZERO”); b2 = new JButton(“ONE”); b3 = new JButton(“TWO”); con.add(b1); con.add(b2); con.add(b3); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class JFrmbut1 { public static void main(String args []) { JFrame fb = new JFrmb1(“JFrame with JButton”); fb.setVisible(true); } } The above program gives the following output: Fig.19.6 Output Screen for Program 19.4 The output screen in fig.19.6 for program 19.4 shows only one button, the last one, with label TWO displayed and not the first two buttons. It is because the default layout manager for JFrame is a border layout. A border layout 440 Programming in JAVA2 manager stacks one component over the other and hence only the last button is seen. To solve this problem, a layout manager, which arranges the components on the content pane, is to be set. Program 19.5 shows a flow layout manager set for the content pane. The components are arranged automatically in the window like the word flow in a text. Program 19.5 // // // // This program illustrates the use of JButton class. The Jbuttons are placed on a JFrame window. The JFrame is set with a FlowLayout manager. somasundaramk@yahoo.com import import import import java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.event.*; class JFrmb2 extends JFrame { JButton b1, b2, b3; Container con; JFrmb2(String s) { super(s); setSize(250, 150); con = getContentPane(); con.setLayout(new FlowLayout(FlowLayout.LEFT)); b1 = new JButton(“ZERO”); b2 = new JButton(“ONE”); b3 = new JButton(); b3.setText(“TWO”); con.add(b1); con.add(b2); con.add(b3); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class JFrmbut2 { public static void main(String args []) { Swing and GUI Components 441 JFrame fb = new JFrmb2(“JFrame with JButton”); fb.setVisible(true); } } The output screen for the above program is given below: Fig.19.7 Output Screen for Program 19.5 JButtons are added on to the content pane in the order in which they are added using add(JComponent comp). However, this order can be changed using the method add(JComponent comp, int position). The following program 19.6 shows how to add the buttons in a different order: Program 19.6 // // // // // This program illustrates the use of JButton class. The JButtons are placed on a JFrame window in a different order. The JFrame is set with a FlowLayout manager. somasundaramk@yahoo.com import java.awt.*; import java.awt.event.*; import javax.swing.*; class JFrmb3 extends JFrame { JButton b1, b2, b3; Container con; JFrmb3(String s) { super(s); setSize(250, 150); con = getContentPane(); con.setLayout(new FlowLayout(FlowLayout.LEFT)); b1 = new JButton(“ZERO”); b2 = new JButton(“ONE”); b3 = new JButton(); 442 Programming in JAVA2 b3.setText(“TWO”); con.add(b1); con.add(b2, 0); con.add(b3, 1); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class JFrmbut3 { public static void main(String args []) { JFrame fb = new JFrmb3(“JFrame with JButton”); fb.setVisible(true); } } The above program gives the following output screen: Fig.19.8 Output Screen for Program 19.6 Appearence of the JButtons. Note the Order of Creating Icons as JButtons JButton class has constructors to use images as buttons. An Icon type object is created using the ImageIcon class. The constructors of this class are: ImageIcon (String filename) Creates an Icon object with the image specified by the filename ImageIcon(URL url) Creates an Icon object with the image specified in the URL Swing and GUI Components 443 The following program 19.7 illustrates the use of Icon and JButton: Program 19.7 // // // // This program illustrates the use of JButton with Icon. The JButtons are placed on a JFrame window. The JFrame is set with a FlowLayout manager. somasundaramk@yahoo.com import java.awt.*; import java.awt.event.*; import javax.swing.*; class JFrmimage extends JFrame { JButton b1, b2, b3; Icon mag, right; Container con; JFrmimage(String s) { super(s); setSize(350, 150); con = getContentPane(); con.setLayout(new FlowLayout(FlowLayout.LEFT)); mag = new ImageIcon(“mag65.jpg”); right = new ImageIcon(“RIGHTt2.jpg”); b1 = new JButton(“Right”, right); b2 = new JButton(“ONE”); b3 = new JButton(“Magesh”, mag); con.add(b1); con.add(b2); con.add(b3); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class JFrmim { public static void main(String args []) { JFrame fb = new JFrmimage(“JFrame with Icon”); fb.setVisible(true); } } 444 Programming in JAVA2 The above program gives the following output: Fig.19.9 19.3.3 Output Screen for Program 19.7 Creating JButtons on JApplet The JApplet class provides a top-level container on which buttons can be added in the same way as that on a JFrame window. In JApplet also the Container’s content pane is to be obtained using getContentPane() method and JComponents added to it. The following program 19.8 shows the creation of JButtons on a JApplet window: Program 19.8 // This program illustrates the use of a JButton class. // The buttons are placed on a JApplet window. // somasundaramk@yahoo.com /* <applet code = JApbut1 width = 300 height = 150> </applet> */ import java.awt.*; import java.awt.FlowLayout; import javax.swing.*; public class JApbut1 extends JApplet { JButton b1, b2, b3; Container con; Icon right; public void init() { con = getContentPane(); con.setLayout(new FlowLayout()); right = new ImageIcon(“rightt2.jpg”); b1 = new JButton(“Right”, right); b2 = new JButton(“TWO”); b3 = new JButton(“THREE”); con.add(b1); Swing and GUI Components 445 con.add(b2); con.add(b3); } } The above program gives the following output: Fig.19.10 Output Screen for Program 19.8 19.3.4 Using JButton Buttons buttons when program being JButtons in an act as an interface between the program and the user. The pressed are supposed to initiate some process related to the developed. In the following program 19.9, we show how to use application. Two buttons with labels Circle and Rectangle are created and added on to a JPanel. JPanel is both a container and a component. JPanel is a window without border and title. Graphics object can be drawn on this JPanel using paintComponent() method. To draw any graphics, one must call the superclass method super.paintComponent(). JPanel implements a default FlowLayout manager. Action listeners are added to the two buttons. When a button is pressed, the action is caught and processed in the ActionPerformed() method. The getActionCommand() method fetches the label of the button being pressed. When the button with label Circle is pressed, a circle is drawn and when the button with label Rectangle is pressed, a rectangle is drawn. The JPanel is then attached to the content pane of a JFrame of the class Upbut1. The main method of the class Juspbut1 creates the object that displays the user interface. 446 Programming in JAVA2 Program 19.9 // // // // // This program illustrates how to use JButtons in applications. The JButtons are placed on a JPanel component. The JPanel is then added to a JFrame window. somasundaramk@yahoo.com import java.awt.*; import java.awt.event.*; import javax.swing.*; class JPbut extends JPanel implements ActionListener { JButton b1, b2; String cmd = null; JPbut() { setLayout(new FlowLayout(FlowLayout.LEFT)); b1 = new JButton(“Circle”); b2 = new JButton(“Rectangle”); b1.addActionListener(this); b2.addActionListener(this); add(b1); add(b2); } public void actionPerformed(ActionEvent ae) { cmd = ae.getActionCommand(); repaint(); } public void paintComponent(Graphics gp) { super.paintComponent(gp); if (cmd == “Circle”) gp.drawOval(20, 60, 75, 75); else if (cmd == “Rectangle”) gp.drawRect(150, 60, 75, 75); } } class Upbut1 extends JFrame { Container con; Swing and GUI Components 447 Upbut1(String title) { super(title); con = getContentPane(); setSize(250, 200); con.add(new JPbut()); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class Juspbut1 { public static void main(String args []) { Upbut1 ufb = new Upbut1(“Using JButton”); ufb.setVisible(true); } } The above program gives the following output: Fig.19.11 Output Screen for Program 19.9 19.4 JLabel The object is a single line application JLabel class is a concrete subclass of JComponent. A JLabel component for placing text or an icon or both. A JLabel displays a of read only text in a container. The text can be changed by the and not by the user. The JLabel has the following int type constants that indicate the alignment of the labels content: 448 Programming in JAVA2 JLabel.CENTER JLabel.LEFT JLabel.RIGHT 19.4.1 JLabel.TOP JLabel.BOTTOM Creating JLabel The labels are created using the following constructors: JLabel() Creates an empty label JLabel(Icon i) Creates a label using the icon i JLabel(Icon i, int alignment) Creates a label using the icon i; alignment. Possible values JLabel.RIGHT. the icon is aligned as specified in the are JLabel.CENTER, JLabel.LEFT, JLabel(String str) Creates a label with the specified string str JLabel(String str, Icon i, int alignment) Creates a label using the icon i, the label is set to the specified string str and with the specified alignment JLabel(String str, int alignment) Creates a label with the specified string str and with the specified alignment Methods The JLabel class has a number of methods. Some of them are: int getHorizontalAlignment() Returns the horizontal alignment for the label’s content Icon getIcon() Returns the icon of the label String getText() Returns the text of the label int getVerticalAlignment() Returns the vertical alignment for the label’s content void setFont(Font font) Sets the font for the label’s text Swing and GUI Components 449 void setHorizontalAlignment(int alignment) Sets the horizontal alignment for the label’s content void setIcon(Icon i) Sets the specified icon as the label’s content void setText(String str) Sets the specified string str as the label’s content void setVerticalAlignment(int alignment) Sets the vertical alignment for the label’s content 19.4.2 Creating JLabel on JFrame The following program 19.10 illustrates the creation of a JLabel on a JFrame: Program 19.10 // This program illustrates the use of JLabel class. // The JLabels are placed on JFrame window. // somasundaramk@yahoo.com import java.awt.*; import java.awt.event.*; import javax.swing.*; class Labelframe extends JFrame { JLabel lbl1, lbl2, lbl3, lblicon; Labelframe(String s) { super(s); setSize(250, 150); Container con = getContentPane(); con.setLayout(new FlowLayout(FlowLayout.LEFT)); lbl1 = new JLabel(“ZERO”); lbl2 = new JLabel(“ONE”); lbl3 = new JLabel(“TWO”); Icon frut = new ImageIcon(“fruits.jpg”); lblicon = new JLabel(“Fruits”, frut, JLabel.LEFT); con.add(lbl1); con.add(lbl2); con.add(lbl3); con.add(lblicon); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) 450 Programming in JAVA2 { System.exit(0); } }); } } class JFrmlbl { public static void main(String args []) { JFrame fb = new Labelframe(“JFrame with JLabel”); fb.setVisible(true); } } The above program gives the following output: Fig.19.12 Output Screen for Program 19.10 19.5 JToggleButton The JToggleButton is a concrete subclass of AbstractButton. It is a superclass for JCheckBox and JRadioButton classes. Toggle buttons are twostate graphical components. They will be in selected(true) or deselected(false) state. The toggle buttons generate ActionEvent, ChangeEvent and ItemEvent. 19.5.1 Creating JToggleButton The toggle buttons are created using the following constructors: JToggleButton() Creates a toggle button without a label; deselected state. the toggle button is set to JToggleButton(Icon i) Creates a toggle button using the icon; deselected state. the toggle button is set to Swing and GUI Components 451 JToggleButton(Icon i, boolean state) Creates a toggle button using the icon i and is set to the specified state. JToggleButton(String label) Creates a toggle button with the specified to deselected state. label; the toggle button is set JToggleButton(String label, boolean state) Creates a toggle button with the specified label and is set to the specified state. JToggleButton(String label, Icon i) Creates a toggle button with the specified label using the icon; the toggle button is set to deselected state. JToggleButton(String label, Icon i, boolean state) Creates a toggle button with the specified label using the icon i and is set to the specified state. 19.5.2 Adding JToggleButton on JApplet The toggle buttons can be added in the JApplet in the same way as in JFrame. The following program 19.11 shows the creation of toggle buttons on a JApplet: Program 19.11 // This program creates JToggleButtons and are // added on to the JApplet. // somasundaramk@yahoo.com /* <applet code = Togbutap width =200 height =200 > </applet> */ import javax.swing.*; import java.awt.*; public class Togbutap extends JApplet { JToggleButton jtb1, jtb2, jtb3, jtbicon; Container conpan; public void init() { conpan = getContentPane(); conpan.setLayout(new FlowLayout(FlowLayout.LEFT)); Icon frut = new ImageIcon(“fruits.jpg”); jtb1 = new JToggleButton(“Mango”); jtb2 = new JToggleButton(“Apple”, true); jtb3 = new JToggleButton(“Banana”); 452 Programming in JAVA2 jtbicon = new JToggleButton(“Fruits”, frut, true); conpan.add(jtb1); conpan.add(jtb2); conpan.add(jtb3); conpan.add(jtbicon); } } The above program gives the following output screen: Fig.19.13 Output Screen for Program 19.11 Darkened buttons indicate that they are in selected state. 19.6 JCheckBox JCheckBox is a subclass of JToggleButton, which is again a subclass of AbstractButton. A check box is a two-state graphical component that will be in either a selected (true) or a deselected (false) state. Unlike toggle button, a check box has visual display of the selected or deselected state. A selected state is indicated by a tick (P ) mark in a box and the deselected state by a an empty box. A check box, when clicked, generates ActionEvent, ChangeEvent and ItemEvent. 19.6.1 Creating JCheckBox The JCheckBox has the following constructors for creating check boxes: JCheckBox() Creates a check box with a blank label; deselected state. JCheckBox(Icon i) Creates a check box using the specified icon; deselected state. the check box is set to the check box is set to Swing and GUI Components JCheckBox(Icon i, boolean state) Creates a check box using the specified icon; specified state. 453 the check box is set to the JCheckBox(String str) Creates a check box with the label str; deselected state. the check box is set to the JCheckBox(String str, boolean state) Creates a check box with the label str; specified state. the check box is set to the JCheckBox(String str, Icon i) Creates a check box using the icon i with the label str; the check box is set to deselected state. JCheckBox(String str, Icon i, boolean state) Creates a check box using the icon i with the label str; set to the specified state. the check box is Methods The JCheckBox class has many methods. below: Some of them are given String getText() Returns the label of the check box void setText(String str) Sets the label of the check box to str Icon getIcon() Returns the icon of the check box void setIcon(Icon i) Sets the specified icon i as the check box boolean isSelected() Returns the state of the check box void setSelected(boolean state) Sets the check box to the specified state 19.6.2 Creating JCheckBox on JFrame The following program 19.12 illustrates the creation of JCheckBox and adding them on a JFrame. Three JCheckBoxes with labels Mango, Apple and Banana are created and added on the content pane of the JFrame. The fourth one is a check box with an image and label Fruits. 454 Programming in JAVA2 Program 19.12 // This program creates JCheckBoxes and are // added on the JFrame. // somasundaramk@yahoo.com import javax.swing.*; import java.awt.event.*; import java.awt.*; class JChkbox extends JFrame { Container con; JCheckBox jbx1, jbx2, jbx3, jbxicon; JChkbox(String title) { super(title); // using anonymous inner class addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setSize(250, 150); Icon frut = new ImageIcon(“fruits.jpg”); jbx1 = new JCheckBox(“Mango”); jbx2 = new JCheckBox(“Apple”); jbx3 = new JCheckBox(“Banana”); jbxicon = new JCheckBox(“Fruits”, frut); con = getContentPane(); con.setLayout(new FlowLayout(FlowLayout.LEFT)); con.add(jbx1); con.add(jbx2); con.add(jbx3); con.add(jbxicon); setVisible(true); } } class JCkbox1 { public static void main(String args []) { new JChkbox(“JCheckBox on JFrame”); } } Swing and GUI Components 455 The above program gives the following output: Fig.19.14 Output Screen for Program 19.12 19.6.3 Creating JCheckBox on JPanel The check boxes can be added on a JPanel component, which is also a container. The JPanel is then added on to a JFrame. The following program 19.13 shows the creation of check boxes on the JPanel: Program 19.13 // // // // This program creates JCheckBoxes and they are added on to the JPanel. The JPanel is then added on to a JFrame. somasundaramk@yahoo.com import javax.swing.*; import java.awt.event.*; import java.awt.*; class JChkbox3 extends JPanel { JCheckBox jbx1, jbx2, jbx3, jbxicon; JChkbox3() { Icon frut = new ImageIcon(“fruits.jpg”); jbx1 = new JCheckBox(“Mango”); jbx2 = new JCheckBox(“Apple”, true); jbx3 = new JCheckBox(“Banana”); jbxicon = new JCheckBox(“Fruits”, frut, true); setLayout(new FlowLayout(FlowLayout.LEFT)); add(jbx1); add(jbx2); add(jbx3); add(jbxicon); } } class JPchkbox 456 Programming in JAVA2 extends JFrame { Container con; JPchkbox(String title) { super(title); con = getContentPane(); con.add(new JChkbox3()); setSize(250, 150); setVisible(true); // using anonymous inner class addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class JCkbox3 { public static void main(String args []) { new JPchkbox(“JCheckBox on JPanel”); } } The above program gives the following output: Fig.19.15 Output Screen for Program 19.13 19.6.4 Using JCheckBox The check boxes can be used for any kind of application, in which a user is given an option to select any number of options out of several options given. In the following program 19.14, three choices are provided as check boxes. The JLabel is used to display the selections. The check boxes and label are created and are added on a JFrame. Swing and GUI Components Program 19.14 // This program creates JCheckBoxes and are // added on to the JFrame. // somasundaramk@yahoo.com import javax.swing.*; import java.awt.event.*; import java.awt.*; class JChkbox2 extends JFrame implements ActionListener { Container con; JCheckBox jbx1, jbx2, jbx3; JLabel answer; boolean select1, select2, select3, select4; String cmd, selection; JChkbox2(String title) { super(title); // using anonymous inner class addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setSize(250, 150); jbx1 = new JCheckBox(“Mango”); jbx2 = new JCheckBox(“Apple”); jbx3 = new JCheckBox(); answer = new JLabel(“Nothing Selected”); jbx3.setText(“Banana”); jbx1.addActionListener(this); jbx2.addActionListener(this); jbx3.addActionListener(this); con = getContentPane(); con.setLayout(new FlowLayout(FlowLayout.LEFT)); con.add(jbx1); con.add(jbx2); con.add(jbx3); con.add(answer); setVisible(true); } public void actionPerformed(ActionEvent ae) { 457 458 Programming in JAVA2 select1 = jbx1.isSelected(); select2 = jbx2.isSelected(); select3 = jbx3.isSelected(); if (select1 | select2 | select3) { selection = “”; if (select1) selection = “Mango”; cmd = ae.getActionCommand(); if (select2) selection = selection + “, Apple”; if (select3) selection = selection + “, } Banana”; if (selection != null) { answer.setText(selection.trim() + “Selected”); selection = null; } else answer.setText(“Nothing Selected”); } } class JCkbox2 { public static void main(String args []) { new JChkbox2(“JCheckBox on JFrame”); } } The above program gives the following output: Fig.19.16 Output Screens for Program 19.14 The first window shows the intial display and the second on the right shows the screen after the check boxes are selected. Swing and GUI Components G 459 JToggleButton and JCheckBox are two-state buttons. A visual rectangle box with P mark indicates that a JCheckBox is in a selected state. A blank box indicates that it is in a deselected state. 19.7 JRadioButton Radio buttons are like check boxes. In a radio button, the selection is displayed in a round graphics. Radio buttons are generally used to represent a collection of mutually exclusive options. That is, out of several options, only one will be in selected (true) state and all the remaining are in deselected (false) state. The radio buttons are created using JRadioButton class, which is a subclass of JToggleButton. The JRadioButton must be placed in a button group. The button group is created using the ButtonGroup class, which has no argument constructor. After creating JRadioButton, the radio buttons are to be added to the ButtonGroup using add() method. JRadioButton generates ActionEvent, ItemEvent and ChangeEvent. If the radio buttons are not grouped using ButtonGroup, then each radio button will be behave exactly like JCheckBox. 19.7.1 Creating JRadioButton The radio buttons are created using the following constructors: JRadioButton() Creates a radio button without any label; deselected state. the radio button is set to JRadioButton(Icon i) Creates a radio button using the icon i; deselected state. the radio button is set to JRadioButton(Icon i, boolean state) Creates a radio button using the icon i; specified state. the radio button is set to the JRadioButton(String str) Creates a radio button with the string str as label; the radio button is set to deselected state. JRadioButton(String str, boolean state) Creates a radio button with the string str as label; the radio button is set to the specified state. 460 Programming in JAVA2 JRadioButton(String str, Icon i) Creates a radio button using the icon i with the string str as label JRadioButton(String str, Icon i, boolean state) Creates a radio button using the icon i with the string str set as label; the radio button is set to the specified state. 19.7.2 Creating JRadioButton on JFrame The radio buttons can be created using constructors and added to a container. In the following program 19.15, radio buttons are created and added to a JFrame. The radio buttons are grouped using the ButtonGroup class. Program 19.15 // This program creates JRadioButtons and they are added on // to the JFrame. All the radio buttons are grouped to bg. // somasundaramk@yahoo.com import javax.swing.*; import java.awt.event.*; import java.awt.*; class Radioframe extends JFrame { Container conpan; JRadioButton rbut1, rbut2, rbut3, rbuticon; Radioframe(String title) { super(title); // using anonymous inner class addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setSize(250, 150); Icon frut = new ImageIcon(“fruits.jpg”); rbut1 = new JRadioButton(“Mango”); rbut2 = new JRadioButton(“Apple”, true); rbut3 = new JRadioButton(“Banana”); rbuticon = new JRadioButton(“Fruits”, frut); conpan = getContentPane(); conpan.setLayout(new FlowLayout(FlowLayout.LEFT)); conpan.add(rbut1); conpan.add(rbut2); Swing and GUI Components 461 conpan.add(rbut3); conpan.add(rbuticon); // create button group ButtonGroup bg = new ButtonGroup(); bg.add(rbut1); bg.add(rbut2); bg.add(rbut3); bg.add(rbuticon); setVisible(true); } } class JRadio { public static void main(String args []) { new Radioframe(“JRadioButton on JFrame”); } } The above program gives the following output: Fig.19.17 Output Screens for Program 19.15 First window shows the initial display. The second window shows the status after selecting another radio button. 19.7.3 Using JRadioButton The radio buttons, when grouped, can be used to select one option out of many options in a mutually exclusive form. As the JRadioButton fires ItemEvent when clicked, it can be used to detect the item state change and appropriate process can be started. In the following program 19.16, three options C++, Java and Pascal are given. The user is asked to identify which of them is not an OOP language. When the user selects one choice, the program responds by displaying whether the selection is correct or wrong. The radio buttons are created and added on a JPanel. The panel is then added to a JFrame and called in another class with main() method. 462 Programming in JAVA2 Program 19.16 // // // // This program illustrates the use of JRadioButtons. The radio buttons are placed on JPanel. The JPanel is then added to a JFrame. somasundaramk@yahoo.com import javax.swing.*; import java.awt.*; import java.awt.event.*; class Usradiopanel extends JPanel implements ItemListener { JRadioButton rb1, rb2, rb3; ButtonGroup bg; boolean state, flag = false; Usradiopanel() { bg = new ButtonGroup(); rb1 = new JRadioButton(“C++”); rb2 = new JRadioButton(“Java”); rb3 = new JRadioButton(“Pascal”); add(rb1); add(rb2); add(rb3); bg.add(rb1); bg.add(rb2); bg.add(rb3); rb1.addItemListener(this); rb2.addItemListener(this); rb3.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { flag = true; repaint(); } public void paintComponent(Graphics gp) { super.paintComponent(gp); state = rb3.isSelected(); gp.drawString(“Which of the above is not an OOP language?”, 20, 70); if (flag) { if (state) gp.drawString(“Yes, you are correct”,20,110); Swing and GUI Components 463 else gp.drawString(“Sorry, it is wrong”, 20, 110); } } } class Radioframe extends JFrame { Container conpan; Radioframe(String str) { super(str); conpan = getContentPane(); conpan.add(new Usradiopanel()); // using anonymous inner class addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setSize(275, 150); } } class Usradpnl { public static void main(String args []) { JFrame radframe = new Radioframe(“RadioButtons on JPanel”); radframe.setVisible(true); } } The above program gives the following output: Fig.19.18 Output Screens for Program 19.16. The first window shows the initial display and the second one shows the display after the user has made a selection. 464 Programming in JAVA2 G JRadioButton is like a JCheckBox. To use JRadioButton in mutually exclusive selection of one option out of many options, it is to be grouped using ButtonGroup. All JRadioButtons are to be added to the ButtonGroup. 19.8 JList JList is a subclass of JComponent. JList creates a graphical display of a list of items and allows the user to select one or more items from the list. A list is used when the number of items for selection is large. Either strings or images can be elements of the list. Selection of an item is done by clicking on the item itself. A Swing list does not have a scroll bar to display the list. Hence, the list is to be placed inside a JScrollPane() object. A JList delegates the responsibilities of data handling, item selection and cell rendering to the interfaces ListModel, ListSelectionModel and ListCellRenderer. The text in a JList cannot be edited. Some basics of JList are given in this section. 19.8.1 Creating JList A JList is created with the following constructors: JList() Creates an empty list JList(Vector vec) Creates a list with items specified in the Vector vec JList(Object[] obj) Creates a list with items specified in the object array JList(ListModel lm) Creates a list with items contained in the list model lm; an instance of DefaultListModel. the list model is Methods The JList class has a large number of inherited methods and some of its own. Some of them are : void setVisibleRowCount(int c) Sets the number of rows in the list to be displayed void addListSelectionListener(ListSelectionListener ls) Adds a list selection listener to this list Swing and GUI Components 465 int getFirstVisibleIndex() Returns the index of the topmost item that is visible int getLastVisibleIndex() Returns the index of the bottom item that is visible int getSelectedIndex() Returns the index of the first selected item Object getSelectedValue() Returns the topmost selected item Object[] getSelectedValues() Returns an array of all selected items int getVisibleRowCount() Returns the number of rows visible in the JList 19.8.2 Creating JList with an Array A JList is created by passing a Vector or an array of Object as argument. In JList, there is no method for adding or removing items in the list. The following program 19.17 illustrates the creation of a JList with an array of String. First, two arrays are created. Then two lists, monthlist and countrylist, are created by passing the arrays as argument in JList. As JList has no scroll pane, the lists are then passed as argument to the JScrollPane constructor. The scroll pane enabled lists are then added to a JPanel. The JPanel is then attached to a JFrame and displayed using the main() method. Program 19.17 /* This program illustrates how to create JList. JListsts are placed on the JScrollPane. The JScrollPane is then added to a JPanel. The JPanel is then added to a JFrame. somasundaramk@yahoo.com */ import java.awt.*; import java.awt.event.*; import javax.swing.*; class Listpanel extends JPanel { JScrollPane monthsp, countrysp; JList monthlist, countrylist; ListModel monthmodel, countrymodel; 466 Programming in JAVA2 Listpanel() { // create array of String String monthname [] = { “January”,“February”,“March”, “April”,“May”,“June”,“July”, “August”,“September”,“October” }; String countryname [] = { “Australia”,“Africa”,“Bangladesh”,“India”, “Pakistan”, “Singapore”,“Russia”,“USA” }; // create JList with array as argument monthlist = new JList(monthname); countrylist = new JList(countryname); // set the number of visible rows monthlist.setVisibleRowCount(4); countrylist.setVisibleRowCount(3); // attach JSrollPane to the list monthsp = new JScrollPane(monthlist); countrysp = new JScrollPane(countrylist); // add the lists to the JPanel add(monthsp); add(countrysp); monthmodel = monthlist.getModel(); countrymodel = countrylist.getModel(); } public void paintComponent(Graphics gp) { super.paintComponent(gp); gp.drawString(“Monthlist”, 45, 120); gp.drawString(“Countrylist”, 155, 120); gp.drawString(“Size“+monthmodel.getSize(),5, 140); gp.drawString(“ “+countrymodel.getSize(),160,140); } } class Scrollframe extends JFrame { Container conpan; Scrollframe(String str) { Swing and GUI Components super(str); conpan = getContentPane(); conpan.add(new Listpanel()); // using anonymous inner class addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setSize(250, 250); setVisible(true); } } class Jlstpnl { public static void main(String args []) { new Scrollframe(“JList on JPanel”); } } The above program gives the following output: Fig.19.19 Output Screen for Program 19.17 G For creating a JList, first create an array or a Vector with the given items. Then construct a JList by passing them as argument in the constructor. JList does not have a scroll pane. Create a JScrollPane by passing the list as the argument in its constructor. 467 468 Programming in JAVA2 19.8.3 DefaultListModel Lists created in JList by passing an array or Vector do not have many methods for manipulating the items in the list. There is no method in the JList to add an item or remove an item in the list. The DefaultListModel, which is a concrete subclass of AbstractListModel, has methods for adding and removing items from a JList. This class implements an interface ListModel. A list with DefaultListModel is created in the following steps: — Create an instance of DefaultListModel. — Add the items to this model. — Create the JList by passing this model as argument in the constructor. The following example shows the creation DefaultListModel by following the above steps: of a JList with DefaultListModel monthmodel = new DefaultListModel(); monthmodel.addElement(“January”); monthmodel.addElement(“February”); monthmodel.addElement(“March”); monthmodel.addElement(“April”); JList monthlist = new JList(monthmodel); A JList created using DefaultListModel has a large number of methods. Some of the methods defined for DefaultListModel are given below: void addElement(Object obj) Adds the given object at the end of the list void clear() Removes all elements from the list Object firstElement() Returns the first element in the list Object getElementAt(int index) Returns the list item at the specified index int getSize() Returns the number of items in the list void insertElementAt(Object obj, int index) Inserts the given object at the specified index Swing and GUI Components 469 boolean removeElement(Object obj) Removes the first occurrence of the object in the list void removeElementAt(int index) Removes the item at the specified index in the list 19.8.4 Creation of JList Using DefaultListModel The following DefaultListModel: program 19.18 shows the creation of JList using Program 19.18 /* This program illustrates how to create a JList using the DefaultListModel. List items are added to the DefaultListModel object. A JList is created with the model as an argument. somasundaramk@yahoo.com */ import java.awt.*; import java.awt.event.*; import javax.swing.*; class Listpanel extends JPanel { JScrollPane monthsp, countrysp; JList monthlist, countrylist; DefaultListModel dfmodel1, dfmodel2; public Listpanel() { // create DefaultListModel dfmodel1 = new DefaultListModel(); dfmodel2 = new DefaultListModel(); String monthname [] = { “January”,“February”, “March”, “April”,“May”, “June”,“July”, “August”,“September”,“October” }; String countryname [] = { “Australia”,“Africa”, “Bangladesh”, “India”,“Pakistan”,“Singapore”, “Russia”, “USA” }; // add elements to the model for (int i = 0; i < monthname.length; i++) 470 Programming in JAVA2 dfmodel1.addElement(monthname[i]); for (int i = 0; i < countryname.length; i++) dfmodel2.addElement(countryname[i]); //create lists with the model as argument monthlist = new JList(dfmodel1); countrylist = new JList(dfmodel2); // set the number of visible rows in the display monthlist.setVisibleRowCount(4); countrylist.setVisibleRowCount(3); //insert the list in a scroll pane monthsp = new JScrollPane(monthlist); countrysp = new JScrollPane(countrylist); add(monthsp); add(countrysp); } public void paintComponent(Graphics gp) { super.paintComponent(gp); gp.drawString(“Monthlist”, 45,120); gp.drawString(“Countrylist”, 155,120); gp.drawString(“Size“+ dfmodel1.getSize(),5,140); gp.drawString(“ “ + dfmodel2.getSize(),160,140); gp.drawString(“First“ + dfmodel1.firstElement(), 5,160); gp.drawString(“item “, 5, 170); gp.drawString(“”+dfmodel2.firstElement(),160,160); gp.drawString(“Last“+dfmodel1.lastElement(),5,190); gp.drawString(“item “, 5, 200); gp.drawString(“”+dfmodel2.lastElement(),160,190); } } class DfListframe extends JFrame { Container conpan; DfListframe(String str) { super(str); conpan = getContentPane(); setSize(250, 250); // using anonymous inner class addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } Swing and GUI Components 471 }); conpan.add(new Listpanel()); setVisible(true); } } class Dflstpnl { public static void main(String args []) { new DfListframe(“JList on JPanel”); } } The above program gives the following output: Fig.19.20 G Output Screen for Program 19.18 When a JList is created using DefaultListModel, first add elements to the model and create the JList by passing the model as argument. 19.8.5 Using JList A JList is used when the number of items for selection is large. In the following program 19.19, we create a JList and show how the list can be used for an application. Program 19.19 /*This program illustrates how to use JList in an application. JList is placed on the JScrollPane. The JScrollPane is then added to a JPanel. The JPanel is then added to a JFrame. 472 Programming in JAVA2 somasundaramk@yahoo.com */ import import import import java.awt.*; java.awt.event.*; javax.swing.*; javax.swing.event.*; class Listpanel extends JPanel implements ListSelectionListener { JScrollPane monthsp; JList monthlist, source; int monthdays [] = new int[10]; String selected; ListModel lstmodel; int selectindex; public Listpanel() { String monthname [] = {“January”,“February”,“March”, “April”,“May”,“June”,“July”,“August” , “September”,“October” }; int mdays [] = { 31, 28, 31,30, 31, 30, 31, 31, 30,31 }; for (int i = 0; i < mdays.length; i++) monthdays[i] = mdays[i]; monthlist = new JList(monthname); monthlist.setVisibleRowCount(4); monthlist.addListSelectionListener(this); monthsp = new JScrollPane(monthlist); add(monthsp); lstmodel = monthlist.getModel(); } public void valueChanged(ListSelectionEvent lse) { source = (JList)lse.getSource(); selected = (String)source.getSelectedValue(); selectindex = source.getSelectedIndex(); repaint(); } public void paintComponent(Graphics gp) { super.paintComponent(gp); gp.drawString(“Size of the list : “ + lstmodel.getSize(), 20, 130); if (selected != null) { gp.drawString(“Selected month : “ + selected, 20, 150); Swing and GUI Components 473 gp.drawString(“No of days in this month : “ + monthdays[selectindex], 20, 170); gp.drawString(“Selected index : “ + selectindex, 20, 190); } } } class Listframe extends JFrame { Container conpan; Listframe(String str) { super(str); conpan = getContentPane(); setSize(250, 250); // using anonymous inner class addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); conpan.add(new Listpanel()); setVisible(true); } } class Uslstpnl { public static void main(String args []) { new Listframe(“JList on JPanel”); } } The above program gives the following output: 474 Programming in JAVA2 Fig.19.21 Output Screens for Program 19.19. First window shows the initial screen and the second window shows the output after a selection is made in the list. In the program 19.19, monthlist, an instance of JList, is created by passing the string array as the argument for the constructor. A scroll pane is attached to the list. Whenever a selection is made by clicking on the list, some process related to the selected item is to be carried out. To detect the list selection, the method addListSelectionListener() is used to register the monthlist. When a list selection is made by an user, a ListSelectionEvent is created. This event is passed to the listener ListPanel which contains the monthlist. The ListSelectionEvent is processed by the valueChanged() method defined in the interface ListSelectionListener. Hence, the class ListPanel implements the interface ListSelectionListener. The ListSelectionEvent is defined in the javax.swing.event package. The getSource() method returns the source object which generated the event. The getSize() method finds the number of elements in the list. This method is defined only in the ListModel class and not in JList. Hence, getModel() method is called on the monthlist and the lstmodel, which is an object of type ListModel. 19.9 JScrollBar JScrollBar is a subclass of JComponent. Scroll bars are visual components that can be used to bring a section of a large area of text, image or other items to view by scrolling. The scroll bars are available in two orientations, horizontal and vertical. The two orientations are defined by two constants: JScrollBar.HORIZONTAL JScrollBar.VERTICAL Swing and GUI Components 475 Though a better facility for scrolling is available in JScrollPane, on certain occasions, manual adjustment is needed for scrolling. JScrollBar is used in such applications. The scroll bar has three visual parts. Unit increment and decrement are represented by two arrow marks. A slider is available in between the two arrow marks, which can be dragged in forward and backward directions to select a view for display. In the space between slider and unit increment lies the block increment area. Similarly, in between slider and unit decrement lies the block decrement area. The distance between minimum visible position and maximum visible position is called visible area. Usually, it is between 0-100 and does not represent the pixel value. The distance between the minimum value and maximum value of a large area is called a range. 19.9.1 Creating JScrollBar The constructors used for creating a scroll bar are: JScrollBar() Creates a scroll bar in the vertical orientation JScrollBar(int Orientation) Creates a scroll bar in the specified orientation The Orientation can JScrollBar.VERTICAL. either be JScrollBar.HORIZONTAL or JScrollBar(int Orientation, int scrollpos, int visible, int minimum, int maximum) Creates a scroll bar in the specified orientation; the initial scroll position is specified by scrollpos, visible indicates the visual area of the scroll bar, minimum indicate the minimum position value and maximum indicates the maximum position value of the scroll bar. Methods Some of the methods defined in JScrollBar are: void addAdjustmentListener(AdjustmentListener al) Adds adjustment listener to this component int getBlockDecrement() Returns the amount of scroll bar units that give the distance through which the slider moves when block decrement is clicked int getBlockIncrement() Returns the amount of scroll bar units that give the distance through which the slider moves when block increment is clicked int getMaximum() Returns the scroll bar’s maximum value 476 Programming in JAVA2 int getMinimum() Returns the scroll bar’s minimum value int getOrientation() Returns the orientation of the scroll bar int getUnitIncrement(int orientation) Returns the amount of the slider which will be incremented when the scroll bar’s increment/decrement arrow is clicked int getValue() Returns the current value of the position of the slider void setMaximum(int max) Sets the scroll bar’s maximum value in scroll bar unit to the specified value void setMinimum(int min) Sets the scroll bar’s minimum value, in scroll bar unit, to the specified value void setOrientation(int orientation) Sets the orientation of the scroll bar void setUnitIncrement(int inc) Sets the amount of slider should move in scroll bar units when the increment/decrement arrow is clicked 19.9.2 Creating JScrollBar on JPanel The following program 19.20 illustrates the creation of one scroll bar in horizontal orientation and another one in vertical orientation. Note the slider position of the horizontal scroll bar is being shifted from the starting point by 50 scroll bar units as specified in the constructor. Program 19.20 // // // // This program shows how to create JScrollBars and add them on to a JPanel and add the JPanel to a JFrame window. somasundaramk@yahoo.com import java.awt.*; import java.awt.event.*; import javax.swing.*; class Scrollbarpanel extends JPanel { JScrollBar sbh, sbv; Swing and GUI Components 477 Scrollbarpanel() { sbh = new JScrollBar(JScrollBar.HORIZONTAL, 50, 50, 0, 250); sbv = new JScrollBar(JScrollBar.VERTICAL, 0, 50, 0, 200); add(sbh); add(sbv); } public void paintComponent(Graphics gp) { super.paintComponent(gp); gp.drawString(“Demo for scroll bars”, 10, 150); } } class Scrollpanecontainer extends JFrame { Scrollpanecontainer(String str) { super(str); setSize(250, 200); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); Container con = getContentPane(); con.add(new Scrollbarpanel()); } } public class JScrlbar { public static void main(String args []) { JFrame jf = new Scrollpanecontainer(“JScrollBar on JPanel”); jf.setVisible(true); } } The above program gives the following output screen: 478 Programming in JAVA2 Fig.19.22 Output Screen for Program 19.20 19.10 JScrollPane JScrollPane is a subclass of JComponent. A JScrollPane is a visual component that helps to scroll around a large-sized item that is too big to be seen all at once. A JScrollPane provides a horizontal scroll bar and a vertical scroll bar automatically. A JScrollPane is a better choice to view a large item in a window than using a JScrollBar. A schematic drawing of the JScrollPane visual component in relation to the large item to be scrolled is given in fig.19.23. Column header Corner Component to be viewed View View port Row header JScrollBar JScrollBar Fig.19.23 Schematic Drawing of JScrollPane A section of the component that is to be viewed is called a view. The display area managed by the JScrollPane on the screen is called a view port. There are four corners. Each corner is identified by the following int type constants defined in the interface ScrollPaneConstants: Swing and GUI Components 479 ScrollPaneConstants.UPPER_LEFT_CORNER ScrollPaneConstants.UPPER_RIGHT_CORNER ScrollPaneConstants.LOWER_LEFT_CORNER ScrollPaneConstants.LOWER_RIGHT_CORNER The top border is called column header and the left border is called row header. The right border represents an automatically adjustable vertical JScrollBar. The border at the bottom represents an automatically adjustable horizontal JScrollBar. Whether a horizontal scroll bar is needed or not is defined by the following int type constants called HorizontalScrollBarPolicy: ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS Similarly, whether a vertical scroll bar is needed or not is defined by the following int type constants called VerticalScrollBarPolicy: ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS Both scroll bars by default assume SCROLLBAR_AS_NEEDED. 19.10.1 Creating JScrollPane The scroll panes are created using the following constructors: JScrollPane() Creates a scroll pane without any component JScrollPane(int vconstant, int hconstant) Creates a scroll pane with scroll bars as specified in the vertical scroll bar constant vconstant and horizontal scroll bar constant hconstant JScrollPane(Component comp) Creates a scroll pane for the specified component JScrollPane(Component Comp, int vconstant, int hconstant) Creates a scroll pane for the component comp with scroll bars as specified in the vertical scroll bar constant vconstant and horizontal scroll bar constant hconstant Methods The JScrollPane class has a number of methods. Some of them are : Component getCorner(String corner) Returns the component, if any, at the specified corner 480 Programming in JAVA2 JScrollBar getHorizontalScrollBar() Returns the horizontal scroll bar int getHorizontalScrollBarPolicy() Returns the constant that tells whether the horizontal scroll bar will be displayed as needed, always or never JScrollBar getVerticalScrollBar() Returns the vertical scroll bar int getVerticalScrollBarPolicy() Returns the constant that tells whether the vertical scroll bar will be displayed as needed, always or never void setColumnHeaderView(Component comp) Sets the specified component as the column header view port void setCorner(String corner, Component comp) Sets the specified component to be put at the specified corner void setHorizontalScrollBarPolicy(int hconstant) Sets the hconstant that specifies whether the horizontal scroll bar will be displayed as needed, always or never void setRowHeaderView(Component comp) Sets the specified component as the row header view port void setVerticalScrollBarPolicy(int vconstant) Sets the vconstant that specifies whether the vertical scroll bar will be displayed as needed, always or never 19.10.2 Creating JScrollPane on JPanel In the following program 19.21, we show how to create a JScrollPane on a JPanel. The source component we used is an image. First an image icon is created using an image “vegetable.jpg”. It is then used to create a JLabel type object picholder. This JLabel is then used as component for the JScrollPane. This scroll pane is then added to a JFrame window and displayed. Program 19.21 // This program shows how to create a JScrollPane // and add it on a JFrame window. // somasundaramk@yahoo.com import java.awt.*; import java.awt.event.*; import javax.swing.*; Swing and GUI Components 481 class Scrollpanframe extends JFrame { JScrollPane jspan; JLabel picholder; Icon veg; Container conpan; Scrollpanframe(String str) { super(str); conpan = getContentPane(); //create an image icon veg = new ImageIcon(“vegetable.jpg”); // create a JLabel using the image picholder = new JLabel(veg); // insert the JLabel inside a JScrollPane jspan = new JScrollPane(picholder); conpan.add(jspan); setSize(200, 250); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } } public class JScrlpan1 { public static void main(String args []) { JFrame jsp = new Scrollpanframe(“JScrollPane on a JFrame”); jsp.setVisible(true); } } The above program gives the following output screen: 482 Programming in JAVA2 Fig.19.24 Output Screens for Program 19.21. The first one is the initial window and the second is after scrolling the horizontal and vertical scroll bars by the user. We will give another illustration in program 19.22 for creating JScrollPane. In this program, the source component is an image “vegetable.jpg”, which is to be viewed in a scroll pane. After creating the image icon veg, it is used to create a JLabel type object picholder. This JLabel component is passed as an argument to create a JScrollPane. A text is created for display in the column header. Using the setColumnHeaderView() the text is set for the scroll pane. Similarly an image “BARV.jpg” is used to create an image and set as row header, using the method setRowHeaderView(). The upper left corner and lower right corner are set with text “UL” and “LR” respectively using the setCorner() method. Program 19.22 /* This program shows how to create a JScrollPane and add it on to a JFrame window. Column header, row header and two corner components are also set for the scroll pane. somasundaramk@yahoo.com */ import java.awt.*; import java.awt.event.*; import javax.swing.*; class Scrollpanframe2 extends JFrame { JScrollPane jspan; JLabel picholder; Icon veg; Container conpan; Swing and GUI Components 483 Scrollpanframe2(String str) { super(str); conpan = getContentPane(); //create an image icon veg = new ImageIcon(“vegetable.jpg”); // create a JLabel using the image picholder = new JLabel(veg); // insert the JLabel inside a JScrollPane jspan = new JScrollPane(picholder); // create a title string for column header JLabel colhead = new JLabel(“Text in Column Header”); jspan.setColumnHeaderView(colhead); //create an image for row header Icon vbar = new ImageIcon(“BARV.jpg”); JLabel rowhead = new JLabel(vbar); jspan.setRowHeaderView(rowhead); // adding corner components JLabel ulc = new JLabel(“UL”); jspan.setCorner( ScrollPaneConstants.UPPER_LEFT_CORNER, ulc); JLabel lrc = new JLabel(“LR”); jspan.setCorner( ScrollPaneConstants.LOWER_RIGHT_CORNER, lrc); conpan.add(jspan); setSize(200, 250); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } } public class JScrlpan2 { public static void main(String args []) { JFrame jsp = new Scrollpanframe2(“JScrollPane on a JFrame”); jsp.setVisible(true); } } 484 Programming in JAVA2 The above program gives the following output screen: Fig.19.25 G Output screens for Program 19.22. The first window is the initial display and the second is after the scroll bars are moved by the user. Note the text in the column header, which is left aligned has moved out of view in the second window. A JScrollPane is used to view a part of a large text or image. When the view port of the JScrollPane is larger than the source, the whole source is displayed. When the view port is smaller than the area of the source, the horizontal and vertical scroll bars are added automatically to view a part of the source. 19.11 JTextField Swing provides different classes to handle the text of different styles using the Swing’s model-view concept. Basically, Swing’s text component deals with two distinct types of text. One text component deals with simple text of one font and one color of text. The other type is a styled text with multiple fonts and multiple colors. The simple type texts are dealt by JTextField, JPasswordField and JTextArea classes. The styled texts are handled in JEditorPane and JTextPane classes. JTextField is a subclass of JTextComponent, which is a subclass of JComponent. A JTextField object is a visual component that can display one line of editable text of one font and color at a time. The text is placed inside a box. The alignment of the text is defined by the following int type constants: JTextField.LEFT JTextField.CENTER JTextField.RIGHT Swing and GUI Components 485 19.11.1 Creating JTextField The text field component is created using the following constructors: JTextField() Creates a new text field; columns is set to 0. the text is set to null and the number of JTextField(String text) Creates a new text field with the specified string as text JTextField(int columns) Creates a new empty text field with the specified number of columns; each column can accommodate a character. JTextField(String text, int columns) Creates a new text field with the specified string as text and with a width to display the specified number of columns Methods The JTextField has a number of inherited methods and some of its own. Some of the methods to handle the JTextField object are given below: void addActionListener(ActionListener al) Adds the action listener to receive action events from this text field int getColumns() Returns the number of columns set for this text field void removeActionListener(ActionListener al) Removes the action listener from this text field void setColumns(int columns) Sets the specified number of columns for this text field void setText(String text) Sets the specified text as the text for this text field String getText() Returns the text contained in this text field String getSelectedText() Returns the selected text contained in this text field void setEditable(boolean edit) Sets the text field to editable (true) or not editable (false) 486 Programming in JAVA2 19.11.2 Creating JTextField on JPanel In the following program 19.23, we will show how to create text fields using different constructors and to add them on a JPanel. This JPanel is then attached to a JFrame window and displayed. Program 19.23 /* This program shows how to create JTextFields and to add them on to JPanel. This JPanel is then attached to a JFrame window. somasundaramk@yahoo.com */ import java.awt.*; import java.awt.event.*; import javax.swing.*; class JTxtfldpanel extends JPanel { JTextField txtf1, txtf2, txtf3; JTxtfldpanel() { setLayout(new FlowLayout(FlowLayout.LEFT)); txtf1 = new JTextField(); txtf2 = new JTextField("Demo Text Field"); txtf3 = new JTextField("Second Text Field", 20); add(txtf1); add(txtf2); add(txtf3); } } class JTxtfldframe extends JFrame { Container conpan; JTxtfldframe(String title) { super(title); conpan = getContentPane(); conpan.add(new JTxtfldpanel()); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); Swing and GUI Components 487 } }); setSize(200, 200); setVisible(true); } } class JTxtfp1 { public static void main(String args []) { new JTxtfldframe("JTextField on JPanel"); } } The above program gives the following output screen: Fig.19.26 Output Screen for Program 19.23 The first text field in fig.19.26 is created without any text using JTextField() constructor. The second text field is constructed using a text. The required column width is automatically adjusted to fit the text. The third text field is created with a text and set with 20 character column width. Hence, the unused columns are displayed empty. 19.11.3 Creating JTextField on JApplet In the following program 19.24, we will show how to create text fields and add them on to a JApplet window. Three text fields, as in program 19.23, are created and attached to the content pane of the JApplet. Program 19.24 // This program shows how to create JTextFields // and add them on to a JApplet window. // somasundaramk@yahoo.com 488 Programming in JAVA2 import java.awt.*; import javax.swing.*; import java.applet.*; /* <applet code =JTxtfda1 width =250 height = 150> </applet> */ public class JTxtfda1 extends JApplet { JTextField txtf1, txtf2, txtf3; Container conpan; public void init() { conpan = getContentPane(); conpan.setLayout(new FlowLayout(FlowLayout.LEFT)); txtf1 = new JTextField(); txtf2 = new JTextField(“Demo Text Field”); txtf3 = new JTextField(“Second Text Field”, 20); conpan.add(txtf1); conpan.add(txtf2); conpan.add(txtf3); } } The above program gives the following output screen: Fig.19.27 19.11.4 Output Screen for Program 19.24 Creating JTextField on JFrame In the following program 19.25, we will show how to create text fields and add them on a JFrame window. Swing and GUI Components 489 Program 19.25 /*This program shows how to create JTextFields and add them on to JFrame window. somasundaramk@yahoo.com */ import java.awt.*; import javax.swing.*; import java.awt.event.*; class Txtfdfr1 extends JFrame { JTextField txtf1, txtf2, txtf3; Container conpan; Txtfdfr1(String str) { super(str); conpan = getContentPane(); conpan.setLayout(new FlowLayout(FlowLayout.LEFT)); txtf1 = new JTextField(); txtf2 = new JTextField(“Demo Text Field”); txtf3 = new JTextField(“Second Text Field”, 20); conpan.add(txtf1); conpan.add(txtf2); conpan.add(txtf3); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); setSize(250, 200); } } class JTxtf1 { public static void main(String args []) { Txtfdfr1 tffr = new Txtfdfr1(“JFrame with JTextField”); tffr.setVisible(true); } } 490 Programming in JAVA2 The above program gives the following output screen: Fig.19.28 19.11.5 Output Screen for Program 19.25 Using JTextField So far, we have seen how to create text field. Now, we will show how text field can be used in an application. In the following program 19.26, we develop an application for e-banking. A screen initially displays fields for the customer to key in their bank details. Each customer will have to fill in his details to withdraw money from the bank. A customer can withdraw a maximum of Rs.5000 in one withdrawal. Withdrawal of more than Rs 5000 is not allowed in this system. In the text field, after filling in the entries, the Return key is to be pressed. Pressing of the Enter key generates actionEvent. This is captured and a response is given. A user has to delete the default display, enter the relevant data and press the Enter key, which generates an actionEvent. This action event is processed by the actionPerformed method. Program 19.26 /* This program shows how to create JTextField and add them on to JPanel window and use the JTextField in an application. somasundaramk@yahoo.com */ import java.awt.*; import javax.swing.*; import java.awt.event.*; class Txtfdaplcn extends JPanel implements ActionListener { JTextField nam, account, pinnumb, amount; Swing and GUI Components 491 JLabel name, acno, pin, amt, welcome; String names, accounts, pinnumbs, amounts, warning=“”; Txtfdaplcn() { welcome = new JLabel(“ Welcome to SOMSON e-Bank “); name = new JLabel(“ Name “); acno = new JLabel(“Ac. No “); pin = new JLabel(“PIN no “); amt = new JLabel(“Amount “); nam = new JTextField(“Type in your name”, 25); account = new JTextField(“Type in your Ac. No”, 25); pinnumb = new JTextField(25); amount = new JTextField(“0000”, 25); add(welcome); add(name); add(nam); add(acno); add(account); add(pin); add(pinnumb); add(amt); add(amount); nam.addActionListener(this); account.addActionListener(this); pinnumb.addActionListener(this); amount.addActionListener(this); } public void actionPerformed(ActionEvent ae) { repaint(); } public void paintComponent(Graphics gp) { super.paintComponent(gp); names = nam.getText(); accounts = account.getText(); pinnumbs = pinnumb.getText(); amounts = amount.getText(); int amountint = Integer.parseInt(amounts); if (amountint > 5000) { warning = “Sorry, you cannot draw more than Rs.5000”; amount.setText(“0000”); amounts = “0000”; gp.drawString(warning, 10, 320); 492 Programming in JAVA2 } gp.drawString(“Name : “ + names, 10, 230); gp.drawString(“Your Ac.No :“ + accounts, 10, 250); gp.drawString(“Your PIN.No : “ + pinnumbs, 10, 270); gp.drawString(“Amount to draw:“ + amounts, 10, 290); } } class Txtfdfr1 extends JFrame { Container conpan; Txtfdfr1(String str) { super(str); conpan = getContentPane(); setSize(300, 350); conpan.add(new Txtfdaplcn()); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } } class JTxtfapl { public static void main(String args []) { JFrame txtaplcn = new Txtfdfr1(“Application using JTextField”); txtaplcn.setVisible(true); } } The above program gives the following output screen when executed: Swing and GUI Components 493 Fig.19.29 a) The Initial Output Screen for Program 19.26 The output screen after the items are filled up by the customer is given below: Fig.19.29 b) Output Screen After Editing the Fields for Program 19.26 494 Programming in JAVA2 19.12 JPasswordField The JPasswordField creates a display for text field similar to JTextField. The only difference is that when text is displayed, the actual characters are replaced by * characters. This password field is useful where the text typed by a user is not to be seen by other people. JPasswordField is a subclass of JTextComponent. Like in JTextField, only one line of text, with one font and color can be used. 19.12.1 Creating JPasswordField The constructors used for creating password field are given below: JPasswordField() Creates an empty password field JPasswordField(int columns) Creates an empty password field with the specified number of columns JPassWordField(String text) Creates a password field with the specified text JPasswordField(String text, int columns) Creates a password field with the specified text and specified number of columns Methods JPasswordField has a number of inherited methods and some of its own. Some of the methods defined for JPasswordField are: boolean echoCharIsSet() Returns true if an echo character has been set char getEchoChar() Returns the echo character set for this field void setEchoChar(char c) Sets the specified character as echo character for this field 19.12.2 Creating JPasswordField on JFrame The JPasswordField is used whenever entries made into a text field are to be made in a secured way so that other persons viewing the screen are not able to read the characters typed. As an illustration, we will show in program 19.27, the creation of JPasswordField and placing it on JFrame window. By default, the echo character that is displayed as a substitute for the typed character is *. However, if a user wants a different echo character, it can be set using the setEchoChar() method. Swing and GUI Components 495 Program 19.27 /* This program shows how to create a JPasswordField and add it on a JFrame window. somasundaramk@yahoo.com */ import java.awt.*; import javax.swing.*; import java.awt.event.*; class JPswdframe extends JFrame { JPasswordField usrpswd; JTextField name; JLabel namelbl, pswdlbl; Container conpan; JPswdframe(String str) { super(str); conpan = getContentPane(); setSize(300, 200); conpan.setLayout(new FlowLayout(FlowLayout.LEFT)); namelbl = new JLabel(“Name : “); pswdlbl = new JLabel(“Password : “); name = new JTextField(“Type your name”, 20); usrpswd = new JPasswordField(10); conpan.add(namelbl); conpan.add(name); conpan.add(pswdlbl); conpan.add(usrpswd); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } } class JPwdf { public static void main(String args []) { JFrame pswdf = new JPswdframe(“JPassword on JFrame”); pswdf.setVisible(true); } } 496 Programming in JAVA2 The above program gives the following output: Fig.19.30 Output Screens for Program 19.27 The first window shows the initial screen display. The second one shows the screen after the entry has been made. 19.13 JTextArea JTextArea is a subclass of JTextComponent. A JTextArea component displays multiple lines of text in one color and with one font. Text area text are displayed as such in the defined window. There is no scroll bar to view the text. If the text is large, then a JScrollPane has to be created using the text area component. 19.13.1 Creating JTextArea JTextArea objects are created using the following constructors: JTextArea() Creates an empty text area JTextArea(int row, in column) Creates an empty text area with the specified number of rows and columns that are visible JTextArea(String text, int row, int column) Creates a text area with the specified text and with the specified rows and columns Methods A large number of methods are defined in JTextArea class. them are : void append(String text) Adds the specified text at the end of the text area void copy() Copies the selected text into the system clipboard Some of Swing and GUI Components void cut() Cuts the selected text into the system clipboard; removed from the text area. 497 the selected text is int getCaretPosition() Returns the current caret(cursor) position inside the text area int getColumns() Returns the number of columns set for the text area int getLineCount() Returns the number of lines in the text area boolean getLineWrap() Returns true if line wrap has been set for the text area, otherwise false int getRows() Returns the number of rows set for the text area String getSelectedText() Returns the selected text int getSelectionEnd() Returns the index next to the last character of the selected text int getSelectionStart() Returns the index of the first character of the selected text String getText() Returns the entire text of the text area void insert(String str, int pos) Inserts the specified string at the specified position pos boolean isEditable() Returns the boolean indicating whether the text area is editable or not void setLineWrap(boolean b) Sets the line wrap for the text area as specified by the boolean; wrapping is done as per the policy determined by the method setWrapStyleWord. void paste() Pastes the string from system clipboard at the current cursor position void replaceRange(String str, int start, int end) Replaces the string specified in the text area from start to end with the specified string void replaceSelection(String str) Replaces the selected text with the specified string 498 Programming in JAVA2 void setEditable(boolean b) Sets the text to the editable or non-editable mode as specified by the boolean value void setSelectionEnd(int end) Sets the index at which the selection should end void setSelectionStart(int start) Sets the index at which the selection should start void setText(String text) Sets the text for the text area void setWrapStyleWord(boolean b) Sets the wrapping style; if set to true, line wrapping is done at the end of word boundaries. If set to false, line wrapping occurs at character boundaries. G JTextArea does not provide scroll bar. Hence, a JTextArea is to be manually inserted into a JScrollPane. 19.13.2 Creating JTextArea on JPanel The following program 19.28 shows the creation of a JTextArea and placing it on a JPanel. The text area created has been set to display 6 rows of text with 25 character width. A JScrollPane is then attached to it so that the text area can be scrolled in a window. To illustrate the append() method, two additional strings are added to the text area created. The text in the text area is made to wrap at the end of each line of text using setLineWrap() method. The setWrapStyleWord(true) tells that the wrapping is to be done at the word boundaries. When the boolean is set to false, wrapping will occur at character boundaries. Program 19.28 /* This program shows how to create a JTextArea and add it on a JPanel window. somasundaramk@yahoo.com */ import java.awt.*; import java.awt.event.*; import javax.swing.*; class Txtapanel extends JPanel { JTextArea txta; Swing and GUI Components 499 String testtext = “This is a demo text used in a JTextArea object. Text area can hold multiple lines with one font and one color, unlike the JTextField, which can contain only one line of text. Text area is useful for displaying a large text. Text area does not support ScrollPane. Hence, if need be, the text area object has to be passed into a ScrollPane constructor”; Txtapanel() { Font fnt = new Font(“Courier”, Font.BOLD, 18); txta = new JTextArea(testtext, 6, 25); txta.setWrapStyleWord(true); txta.setLineWrap(true); txta.append(“\nSecond text”); txta.append(“\nThird text “); txta.setFont(fnt); JScrollPane txtasp = new JScrollPane(txta); add(txtasp); } } class Txtaframe extends JFrame { Container conpan; Txtaframe(String str) { super(str); conpan = getContentPane(); setSize(320, 200); conpan.add(new Txtapanel()); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } } class JTxtap { public static void main(String args []) { JFrame txtaf = new Txtaframe(“JTextArea on JPanel”); txtaf.setVisible(true); } } 500 Programming in JAVA2 The above program gives the following output screen: Fig.19.31 Output Screens for Program 19.28. The first window shows the line wrapping at character boundaries and the second shows the line wrapping at word boundaries. 19.13.3 Using JTextArea in Applications In this section, we discuss and give an application program that makes use of JTextArea. JTextArea has a model-view structure, which is the basic concept in all Swing user-interface components. There is a Document interface for storing all attributes for the text. There are a large number of actions that can be done on text area and are defined in the class EditorKit. Text area is used for various applications. Various actions like selecting a text, cutting, copying, pasting, appending and inserting are possible. In the following program 19.29, we show how to select a particular string in the JTextArea component. The cursor is termed as caret. There is an interface CaretListener, which has an abstract method caretUpdate(), which is to be given a concrete method. To capture CaretEvent, the addCaretListener() method is called on the JTextArea object. We made use of the caret event to update the selections made in the text area. Program 19.29 /* This program shows how to create a JTextArea and use it in an application. somasundaramk@yahoo.com */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class Txtaappanel extends JPanel implements CaretListener { Swing and GUI Components 501 JTextArea txta, txtsource; int caretindex = -1; String seltxt; String testtext = “This is a demo text used in a JTextArea object. Text area can hold multiple lines with one font and one color, unlike the JTextField, which can contain only one line of text. Text area is useful for displaying a large text. Text area does not support ScrollPane. Hence, if need be, the text area object has to be passed into a ScrollPane constructor”; Txtaappanel() { Font fnt = new Font(“Courier”, Font.BOLD, 18); // create a JTextArea object txta = new JTextArea(testtext, 6, 25); // set the line wrapping is to be done with word // boundary txta.setWrapStyleWord(true); // set line wrapping txta.setLineWrap(true); //add another line of text txta.append(“\nSecond text”); txta.append(“\nThird text “); // set font for JTextArea txta.setFont(fnt); // add caret(cursor) listener. The JPanel is the // listener txta.addCaretListener(this); JScrollPane txtasp = new JScrollPane(txta); add(txtasp); } // whenever caret position changes the caretUpdate // is called public void caretUpdate(CaretEvent ce) { txtsource = (JTextArea)ce.getSource(); seltxt = txtsource.getSelectedText(); caretindex = txtsource.getCaretPosition(); repaint(); } public void paintComponent(Graphics gp) { super.paintComponent(gp); 502 Programming in JAVA2 int row = txta.getRows(); boolean iswrap = txta.getLineWrap(); String wrapped = iswrap ? “Yes” : “NO”; gp.drawString(“Line Wrapped:“ + wrapped, 20, 200); gp.drawString(“Rows:“ + row, 20, 220); if (seltxt != null) gp.drawString(“Selected String : “ + seltxt, 20, 240); else gp.drawString(“ No Text Selected “, 20, 240); if (caretindex >= 0) gp.drawString(“Caret Position : “ + caretindex, 20, 260); else gp.drawString(“Caret Not Inside the Text Area“, 20, 260); } } class Txtaapframe extends JFrame { Container conpan; Txtaapframe(String str) { super(str); conpan = getContentPane(); setSize(320, 300); conpan.add(new Txtaappanel()); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } } class JTxtaap { public static void main(String args []) { JFrame txtaf = new Txtaapframe(“Using JTextArea”); txtaf.setVisible(true); } } Swing and GUI Components 503 The above program gives the following output screen: Fig.19.32 Output Screens for Program 19.29. The first is the unedited initial window. The second shows when a string is selected in the text area. 19.14 JComboBox JComboBox is a subclass of JComponent. A combo box is a visual Swing graphical component that gives a popup list when clicked. It is the combination of JList and JTextField. In combo box, only one item is visible at a time. A popup menu displays the choices a user can select from. In JList, the items cannot be edited, but in combo box, the items can be edited by setting the JComboBox editable. JComboBox has a model-view structure. It has DefaultComboBoxModel class, which can be used to add more flexible methods to JComboBox. 19.14.1 Creating JComboBox Combo boxes can be created using constructors defined in JComboBox class. Some of them are : JComboBox() Creates an empty combo box JComboBox(ComboBoxModel model) Creates a combo box using the items defined in the specified model JComboBox(Object[] array) Creates a combo box taking the items from the specified object array JComboBox(Vector vec) Creates a combo box taking the items from the specified Vector 504 Programming in JAVA2 Methods JComboBox class has a number of methods. Some of them are: void actionPerformed(ActionEvent ae) This method is to be implemented when addActionListener is used void addActionListener(ActionListener al) Adds an action listener to the combo box void addItem(Object obj) Adds the specified object to the list void addItemListener(ItemListener il) Adds an item listener to the combo box String getActionCommand() Returns the action command Object getItemAt(int index) Returns item at the specified index in the list int getItemCount() Returns the number of items in the list int getSelectedIndex() Returns the number of items in the list object getSelectedItem() Returns the currently selected item boolean isEditable() Returns a boolean specifying whether the combobox items are editable or not void removeAllItems() Removes all items from the list void removeItem(Object obj) Removes the specified item from the list void removeItemAt(int index) Removes the item at the specified index from the list void setActionCommand(String cmd) Sets the specified string as the action command for the combo box void setEditable(boolean edit) Sets the boolean value indicating whether the items in the list are editable or not Swing and GUI Components 505 void setEditor(ComboBoxEditor editor) Sets an editor for the combo box void setModel(ComboBoxModel model) Sets a model for the combo box 19.14.2 Adding JComboBox on JPanel JComboBox objects can be added on containers like JApplet window, JFrame, JPanel and other heavy-weight containers. In the following program 19.30, we will show how to create JComboBox objects and add them on to JPanel. We create two String arrays, monthname and countryname. They are then passed as argument to the JComboBox constructor to create two combo boxes. One of the combo boxes is made editable using setEditable() method. The two combo boxes are then added to a JPanel. The JPanel is then added to a JFrame. The JFrame is displayed through a main() method in another class. Program 19.30 /*This program illustrates how to create JComboBox. JComboBoxes are then added to a JPanel. The JPanel is then added to a JFrame. somasundaramk@yahoo.com */ import java.awt.*; import java.awt.event.*; import javax.swing.*; class Combopanel extends JPanel { JComboBox monthcombo, countrycombo; Combopanel() { // create array of String String monthname [] = {“January”,“February”,“March”, “April”,“May”,“June”,“July”, “August”,“September”,“October”}; String countryname [] = {“Australia”,“Africa”,“Bangladesh”, “India”, “Pakistan”,“Singapore”,“Russia”,“USA”}; // create JComboBox with array as argument monthcombo = new JComboBox(monthname); countrycombo = new JComboBox(countryname); countrycombo.setEditable(true); 506 Programming in JAVA2 // add the combo boxes to the JPanel add(monthcombo); add(countrycombo); } } class Comboframe extends JFrame { Container conpan; Comboframe(String str) { super(str); conpan = getContentPane(); conpan.add(new Combopanel()); // using anonymous inner class addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setSize(250, 250); setVisible(true); } } class JCmbop { public static void main(String args []) { new Comboframe(“JComboBox on JPanel”); } } The above program gives the following screen output: Swing and GUI Components Fig.19.33 G 507 Output Screens for Program 19.30. The first window shows the initial display. The second window shows the screen after the users selection. Note the country display is in white, indicating that it is editable. JComboBox is like the combination of JList and JTextField. Items in a JList cannot be edited, but items in a JComboBox can be set to editable. 19.14.3 Using JComboBox In this section, we will discuss how to make use of a JComboBox in reallife problems with an example. The problem is to display the list of months and ask the user to select a month. The selected month is to be identified and displayed separately. Many applications require this kind of a situation. Displaying the selected month is an illustration of how to capture the selected item. Once the selection is identified, appropriate action can be carried out. In the following program 19.31, we will create a JComboBox containing the names of months. A JLabel object with a text instructing the user to select a month is created. The JComboBox is attached with an ItemListener. Whenever there is a change of state in the JComboBox, the itemStateChanged() method is executed. This method identifies the source of event. From the source, the selected item and its corresponding index are obtained. The repaint() method calls the paintComponent() method and updates the screen display. 508 Programming in JAVA2 Program 19.31 /* This program illustrates how to use JComboBox. somasundaramk@yahoo.com */ import java.awt.*; import java.awt.event.*; import javax.swing.*; class Combopanel extends JPanel implements ItemListener { JComboBox monthcombo; JComboBox combosource; String selectitem; int selectindex; public Combopanel() { String monthname [] = {“January”,“February”,“March”, “April”,“May”,“June”,“July”,“August”, “September”,“October”,“November”,“December”}; monthcombo = new JComboBox(); // add elements to the model for (int i = 0; i < monthname.length; i++) monthcombo.addItem(monthname[i]); monthcombo.addItemListener(this); JLabel month = new JLabel(“Select a month “); add(month); add(monthcombo); } public void itemStateChanged(ItemEvent ie) { combosource = (JComboBox)ie.getSource(); selectitem = (String)combosource.getSelectedItem(); selectindex = combosource.getSelectedIndex(); repaint(); } public void paintComponent(Graphics gp) { super.paintComponent(gp); if (combosource != null) { Swing and GUI Components 509 gp.drawString(“No. of months in the list : “ + combosource.getItemCount(), 5, 140); gp.drawString(“Selected item : “ + selectitem, 5, 160); gp.drawString(“Item index : “ + selectindex, 5, 180); } else gp.drawString(“No selection is made”, 5, 160); } } class Dfcomboframe extends JFrame { Container conpan; Dfcomboframe(String str) { super(str); conpan = getContentPane(); setSize(250, 250); // using anonymous inner class addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); conpan.add(new Combopanel()); setVisible(true); } } class JCmbop1 { public static void main(String args []) { new Dfcomboframe(“Using JComboBox “); } } The above program gives the following output screen: 510 Programming in JAVA2 Fig.19.34 Output Screens for Program 19.31. The first window shows the initial display and the second shows the screen after the user’s selection. 19.15 JMenuItem, JMenu and JMenuBar A pull-down menu with several items can be created using JMenuItem, JMenu and JMenuBar objects. JMenu is a subclass of JComponent and JMenu is a subclass of JMenuItem. JMenuBar is a subclass of JComponent. A JMenu contains several JMenuItem. By clicking menu item, actions can be initiated. A JMenuItem is like a button. A JMenuItem is to be attached to a JMenu object. A JMenu is to be attached to a JMenuBar. A JMenuBar is to be attached to a JFrame or JApplet window. To create a menu window, the following steps are to be followed: Create JMenuItem (many). Create JMenu (many). Create JMenuBar. Create JFrame(or JApplet). Add all JMenuItem to JMenu. Add all JMenu to JMenuBar. Add JMenuBar to JFrame( or JApplet). 19.15.1 Creating JMenuItem A JMenuItem is a JMenu is clicked, a popup in it. Each menu item acts be initiated. In this section, part of JMenu displayed in a window. When a menu appears, displaying all menu items contained like a button. By clicking a menu item, actions can we will see how to create JMenuItem. Swing and GUI Components 511 The following constructors are used to create JMenuItem. A JMenuItem can contain a string or an image or both. JMenuItem() Creates an empty menu item JMenuItem(Icon img) Creates a menu item with the specified icon JMenuItem(String str) Creates a menu item with a text as specified in the string JMenuItem(String text, Icon img) Creates a menu item with the specified string and icon Methods The actions created by clicking the menu item are handled by several methods defined in the JMenuItem class. Some of them are : void addActionListener(ActionListener al) Adds action listener to the menu item void addMenuDragMouseListener(MenuDragMouseListener mdl) Adds menu drag mouse listener to this menu item String getActionCommand() Returns the action command set for this menu item Icon getIcon() Returns the icon of this menu item String getText() Returns text of this menu item void setActionCommand(String cmd) Sets the specified string as action command void setIcon(Icon img) Sets the icon for this menu item void setRolloverIcon(Icon img) Sets the roll over icon for this menu item 19.15.2 Creating JMenu JMenu is a container for JMenuItem. A menu can be attached with several menu items. When a menu is clicked, a popup menu displays all the menu items. Several such menus can be attached to a menu bar. A JMenu 512 Programming in JAVA2 can also contain JSeparator, which displays a visual line separator between two menu items. In this section, we will see how to create JMenu objects. The constructors used for creating JMenu are : JMenu() Creates an empty menu JMenu(String str) Creates a menu with the specified string JMenu(String str, boolean tearoff) Creates a menu with the specified string; the menu is tear-off or not. the boolean specifies whether Methods The JMenu class has a number of methods to manage JMenu objects. Some of them are: Component add(Component com) Appends a component to the end of the menu Component add(Component com, int index) Inserts the specified component at the specified location in the menu JMenuItem add(JMenuItem mitem) Adds the specified menu item at the end of the menu JMenuItem add(String str) Creates a new menu item with the specified string and appends it to the end of the menu void addSeparator() Appends a separator to the menu int getItemCount() Returns the total number of items, including the separator, in the menu JMenuItem insert(JMenuItem mitem, int index) Inserts the specified menu item at the specified index void addActionListener(ActionListener al) Adds action listener 19.15.3 Creating JMenuBar JMenuBar is a subclass of JComponent. A menu bar holds many menus in its bar. A menu bar has to be attached to a JFrame window or Swing and GUI Components to a JApplet window. It is: 513 There is only one constructor to create a JMenubar. JMenuBar() Creates a menu bar Methods A menu bar can be managed using the methods defined in JMenuBar class. Some of them are: JMenu add(JMenu jm) Adds specified menu to the menu bar JMenu getHelpMenu() Returns the help menu JMenu getMenu(int index) Returns the menu at the specified location int getMenuCount() Returns the number of items in the menu bar void setHelpMenu(JMenu jm) Sets a help menu in the menu bar 19.15.4 Creating JMenu on JFrame Having seen the functions of the JMenuItem, JMenu and JMenuBar, we will see in this section, how all these three components are integrated together to produce a user window with a menu. We will follow the steps mentioned in section 19.15. Program 19.32 shows how to create a window with two menus, cities and states, each having several items. First a JMenuBar is created using the constructor and setMenuBar() method. Then two menus, cities and states, are created. Several menu items for each of them are created and added to the respective menu using add() method. The menus are then added to the menu bar. Note that one of the menu items for cities is set with an image icon. Program 19.32 /* */ This program illustrates the following: JMenuItem JMenu JMenuBar somasundaramk@yahoo.com 514 Programming in JAVA2 import java.awt.*; import javax.swing.*; import java.awt.event.*; // You need a JFrame window to set up a menu bar. class Menufrmae1 extends JFrame { JMenuItem albd, blore, cbe, dhi, chni, dgl, mdu; JMenuItem ap, up, ka, kr, or, mh, bn, pb, hr, tn; Menufrmae1(String title) { super(title); // create a menu bar JMenuBar mnubar = new JMenuBar(); setJMenuBar(mnubar); // create menu JMenu city = new JMenu(“Cities”); //create menu items Icon laughimg = new ImageIcon(“laugh.jpg”); albd = new JMenuItem(“Allahabad”); blore = new JMenuItem(“Bangalore”); cbe = new JMenuItem(“Coimbatore”); dhi = new JMenuItem(“Delhi”); chni = new JMenuItem(“Chennai”); dgl = new JMenuItem(“Dindigul”); mdu = new JMenuItem(“Madurai”, laughimg); // add menu items to menu city.add(albd); city.add(blore); city.add(cbe); city.add(chni); city.add(dhi); city.add(dgl); city.add(mdu); // attach city menu to menu bar mnubar.add(city); // create a second menu JMenu states = new JMenu(“States”); // ap up ka kr or Create menu items for the second menu = new JMenuItem(“Andhra Pradesh”); = new JMenuItem(“Uttar Pradesh”); = new JMenuItem(“Karnataka”); = new JMenuItem(“Kerala”); = new JMenuItem(“Orissa”); Swing and GUI Components mh bn pb hr tn = = = = = new new new new new JMenuItem(“Maharashtra”); JMenuItem(“West Bengal”); JMenuItem(“Punjab”); JMenuItem(“Haryana”); JMenuItem(“Tamil Nadu”); // add menu items to menu states.add(ap); states.add(hr); states.add(ka); states.add(kr); states.add(mh); states.add(or); states.add(pb); states.add(up); states.add(tn); //add the menu states to the menubar mnubar.add(states); setSize(250, 250); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } } class JMenuf1 { public static void main(String args []) { new Menufrmae1(“JMenu Example”); } } The above program gives the following output screen: 515 516 Programming in JAVA2 Fig.19.35 19.15.5 Output Screens for Program 19.32 The first window shows the initial display. The second window shows the display after the user clicked cities menu. Creating JMenu on JApplet A JApplet program which creates the same user window as that of the above program (19.32) is shown in progam 19.33. Program 19.33 /* This program illustrates how to use the following JMenuItem JMenu JMenuBar on JApplet window. somasundaramk@yahoo.com <applet code = JMenua1 width =250 height =250> </applet> */ import java.awt.*; import javax.swing.*; import java.applet.*; public class JMenua1 extends JApplet { JMenuItem albd, blore, cbe, dhi, chni, dgl, mdu; JMenuItem ap, up, ka, kr, or, mh, bn, pb, hr, tn; JMenu city, states; public void init() { // create a menu bar JMenuBar mnubar = new JMenuBar(); setJMenuBar(mnubar); Swing and GUI Components // create city menu city = new JMenu(“Cities”); //create menu items for city Icon laughimg = new ImageIcon(“laugh.jpg”); albd = new JMenuItem(“Allahabad”); blore = new JMenuItem(“Bangalore”); cbe = new JMenuItem(“Coimbatore”); dhi = new JMenuItem(“Delhi”); chni = new JMenuItem(“Chennai”); dgl = new JMenuItem(“Dindigul”); mdu = new JMenuItem(“Madurai”, laughimg); // add menu items to menu city.add(albd); city.add(blore); city.add(cbe); city.add(chni); city.add(dhi); city.add(dgl); city.add(mdu); // attach city menu to menu bar mnubar.add(city); // create states menu states = new JMenu(“States”); // Create menu items for the states menu ap = new JMenuItem(“Andhra Pradesh”); up = new JMenuItem(“Uttar Pradesh”); ka = new JMenuItem(“Karnataka”); kr = new JMenuItem(“Kerala”); or = new JMenuItem(“Orissa”); mh = new JMenuItem(“Maharashtra”); bn = new JMenuItem(“West Bengal”); pb = new JMenuItem(“Punjab”); hr = new JMenuItem(“Haryana”); tn = new JMenuItem(“Tamil Nadu”); // add menu items to menu states.add(ap); states.add(hr); states.add(ka); states.add(kr); states.add(mh); states.add(or); states.add(pb); states.add(up); states.add(tn); //add the menu states to the menubar mnubar.add(states); } } 517 518 Programming in JAVA2 19.16 JDialog JDialog object is a top-level window with a title and a border. JDialog is a subclass of Dialog. A JDialog is created by another window to enable the user to input data or to display a message. A dialog must have either a Frame or Dialog as its owner. There are two types of dialog windows, modal and non-modal. A modal dialog prevents input to other top-level windows. By default, all dialogs are non-modal. JDialog creates WindowOpened, WindowClosing, WindowClosed, WindowActivated and WindowDeactivated events. 19.16.1 Creating JDialog JDialog objects are created as a result of some action performed on the user-interface components. Hence, there essentially is a owner for the JDialog. Whenever some process takes place, a JDialog is created as a response to the process. A JDialog is created using the following constructors: JDialog(Dialog owner) Creates a new dialog window with an empty title and the specified owner dialog; the dialog is invisible and non-modal. JDialog(Dialog owner, String title) Creates a new dialog window with the specified dialog as owner and the specified string as title JDialog(Dialog owner, String title, boolean modal) Creates a new dialog window with the specified dialog as owner and the specified string as title; the boolean value specifies whether the dialog is modal or non-modal. JDialog(Frame owner) Creates a new dialog window with the specified frame as owner without a title and is invisible JDialog(Frame owner, boolean modal) Creates a new dialog window with the specified frame as owner and without a title; the boolean value specifies whether the dialog is modal or non-modal. JDialog(Frame owner, String title, boolean modal) Creates a new dialog with the specified frame as owner and the specified string as title; the boolean value specifies whether the dialog is modal or non-modal. Swing and GUI Components 519 Methods JDialog class has a number of methods to handle the dialog windows. Some of them are : void dispose() Disposes the dialog String getTitle() Returns the title of the dialog Container getContentPane() Returns the content pane void hide() Hides the dialog boolean isModal() Returns true, if the dialog is modal void setTitle(String str) Sets the title for the dialog void setJMenuBar(JMenuBar menu) Sets the menu bar for the dialog void show() Makes the dialog visible 19.16.2 Using JDialog JDialog windows enable the user to make a dialog-like interaction with the user, allowing them to input a data or get messages to proceed further. In the following program 19.34, we will illustrate how to create a menu and then create a dialog window as a response to the clicking of an item in a menu. The JDia1 class sets up a dialog. The JDiagenerator frame creates a menu select. The select menu has three menu items, Start, Continue and Exit. Clicking the first two items will not produce any response. When the menu item Exit is clicked, a dialog window is created. When the Close button on the dialog window is selected, it is hidden. Program 19.34 /* This program illustrates the creation of JDialog on a JFrame. somasundaramk@yahoo.com */ import java.awt.*; import javax.swing.*; 520 Programming in JAVA2 import java.awt.event.*; class JDia1 extends JDialog implements ActionListener { Container conpan; JDia1(Frame fm, String str) { super(fm, str); conpan = getContentPane(); JButton b = new JButton(“ Close”); b.addActionListener(this); conpan.add(b); setSize(150, 100); } public void actionPerformed(ActionEvent ae) { dispose(); } } class JDiagenerator extends JFrame implements ActionListener { String cmd = “”; JDia1 d1; Container conpan; JDiagenerator(String str) { super(str); conpan = getContentPane(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); conpan.setLayout(new BorderLayout()); JLabel mesg = new JLabel(“Click each choice in the Select menu”); conpan.add(mesg, BorderLayout.SOUTH); JMenuBar mbar = new JMenuBar(); setJMenuBar(mbar); JMenu select = new JMenu(“Select”); JMenuItem start = new JMenuItem(“Start”); Swing and GUI Components JMenuItem cont = new JMenuItem(“Continue”); JMenuItem stop = new JMenuItem(“Exit”); select.add(start); select.add(cont); select.add(stop); mbar.add(select); conpan.add(mbar, BorderLayout.NORTH); setSize(300, 200); setVisible(true); start.addActionListener(this); cont.addActionListener(this); stop.addActionListener(this); } public void actionPerformed(ActionEvent ae) { cmd = ae.getActionCommand(); if (cmd == “Exit”) { d1 = new JDia1(this, “JDialog Window”); d1.setVisible(true); d1.setLocation(100, 50); } else { d1 = new JDia1(this, “ “); d1.setLocation(70, 50); d1.setVisible(false); } } } class JDialogf { public static void main(String args []) { new JDiagenerator(“Main Window”); } } The above program gives the following output screen: 521 522 Programming in JAVA2 Fig.19.36 G Output Screens for Program 19.34. The first window shows the initial display. The second window shows the screen after the user has clicked Exit item. JDialog creates a top-level window. However, there should be a parent Component to which the dialog frame has to be attached. A JDialog can be owned by a JFrame or another JDialog. 19.17 JOptionPane JOptionPane is used for creating dialogs in a user-interface. JOptionPane can display text messages and icons. JOptionPane class provides a large number of methods that can be used to create instant dialogs. JOptionPane has methods to display dialogs with different types of messages. Simple dialogs can be created easily than using JDialog objects. Dialog created by JOptionPane contains predefined buttons, which can be used for developing interactive applications. JOptionPane has a number of static methods that can be called directly to create dialogs. JOptionPane has static methods to create dialogs of the following types: Message Dialogs - Gives some information Confirmation Dialogs - Asks the user to confirm something that is going to take place like Yes/No/Cancel Input Dialogs - Asks the user to give input Option Dialogs - It is a dialog that combines all the above three. JOptionPane defines a number of constants that are used to create standard dialogs. The static methods and constructors have one or more of the following parameters as arguments: Swing and GUI Components 523 ParentComponent This is the component which has generated the dialog. message This is the message meant for the user to read. It can be an array of object or an Icon or a Component that is to be displayed. messageType This defines the style of the displayed message. It always has a default icon that is displayed along with the message. This value is defined by the following int type constants: JOptionPane.ERROR_MESSAGE JOptionPane.INFORMATION_MESSAGE JOptionPane.WARNING_MESSAGE JOptionPane.QUESTION_MESSAGE JOptionPane.PLAIN_MESSAGE optionType This defines the buttons that appear on the dialog box. This value is defined by the following int type constants: JOptionPane.DEFAULT_OPTION JOptionPane.YES_NO_OPTION JOptionPane.YES_NO_CANCEL_OPTION JOptionPane.OK_CANCEL_OPTION JOptionPane.YES_OPTION icon This is a decorative icon that is displayed in the dialog box. The default icon is defined by the messageType. title It is a string that is displayed as title for the dialog box. 19.17.1 Creating JOptionPane JOptionPane has number of constructors to create dialogs. Some of them are: JOptionPane(Object message) Creates an option pane to display the specified message JOptionPane(Object message, int messageType) Creates an option pane to display the specified message with a style specified by messageType JOptionPane(Object message, int messageType, int optionType) Creates an option pane to display the specified message with a style specified by messageType and with buttons specified by optionType JOptionPane(Object message, int messageType, int optionType, Icon icon) Creates an option pane to display the specified message with a style 524 Programming in JAVA2 specified by messageType and with buttons specified by optionType with the specified icon instead of default icon defined by messageType Methods JOptionPane has a large number of methods to create dialog boxes and manage JOptionPane objects. Static methods defined in JOptionPane class can be used to create dialog boxes. Some of the methods are: JDialog createDialog(Component parentComponent, String title) Creates and returns a JDialog with the specified string as title for the dialog box Icon getIcon() Returns icon of the pane Object getMessage() Returns the message displayed in the pane. Object getValue() Returns the value the user had selected void setMessage(Object message) Sets the message for the pane void setOptionType(int optionType) Sets the optionType for the pane static int showConfirmDialog(Component parentComponent, Object message) Brings up a dialog box with the specified message with buttons Yes, No and Cancel static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType) Brings up a dialog box with the specified message with the specified string as title for the dialog box and with buttons specified by optionType static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType) Brings up a dialog box with the specified message with the specified string as title for the dialog box with buttons specified by optionType and display style specified by messageType Static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon) Brings up a dialog box with the specified message with the specified string as title with buttons specified by optionType with display style specified by messageType and with the specified icon Swing and GUI Components 525 static int showMessageDialog(Component parentComponent, Object message) Brings up a dialog box to display the specified message and with a default OK button static int showMessageDialog(Component parentComponent, Object message, String title, int messageType) Brings up a dialog box to display the specified message with the specified title and style specified by messageType static int showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) Brings up a dialog box to display the specified message with the specified title with style specified by messageType and with specified icon To create a dialog box using JOptionPane, techniques may be followed: 1. Construct a JOptionPane ex : JOptionPane job = new JOptionPane(.....); Call the createDialog method ex : JDialog jd = job.createDialog(....); Call the show() method ex : jd.show() 2. Call the static method directly ex : JOptionPane.showMessageDialog(.....); any of the following two 19.17.2 Using JOptionPane Dialog boxes can be created using JOptionPane’s constructors or by calling its static methods. In the following program 19.35, we show how the raw JOptionPane will look like. Generally, JOptionPane objects are created as a result of a user clicking a component in a user-interface screen. In this example, the JOptionPane objects are being displayed without any parent component for option pane. The program 19.35 generates output for four message types. Program 19.35 /* This program illustrates the creation somasundaramk@yahoo.com */ import javax.swing.*; import java.awt.*; import java.awt.event.*; class Joption extends JFrame { of JOptionPane. 526 Programming in JAVA2 Container conpan; Joption(String str) { super(str); conpan = getContentPane(); conpan.setLayout(new FlowLayout(FlowLayout.LEFT)); JOptionPane jop1 = new JOptionPane(“Information message “, JOptionPane.INFORMATION_MESSAGE); JOptionPane jop2 = new JOptionPane(“Warning message”, JOptionPane.WARNING_MESSAGE); JOptionPane jop3 = new JOptionPane(“Question message”, JOptionPane.QUESTION_MESSAGE); JOptionPane jop4 = new JOptionPane(“Error message”, JOptionPane.ERROR_MESSAGE); JLabel info = new JLabel(“Default Icons for message types”); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); conpan.add(jop1); conpan.add(jop2); conpan.add(jop3); conpan.add(jop4); conpan.add(info); setSize(550, 250); setVisible(true); } } class JOpan { public static void main(String args []) { new Joption(“JOptionPane “); } } The above program gives the following output: Swing and GUI Components Fig.19.37 527 Output Screen for Program 19.35. Note the default icons in the message. In the following program 19.36, we show how JOptionPane can be used to create dialog in applications. First, we create a JFrame window. We then add three JButtons and a JLabel. The action listeners are registered with the buttons. Whenever the respective buttons are clicked by the user, action events are generated and the actionPerformed() method is called. To illustrate various message types, we create different option panes. The oplangb button, when clicked, generates a dialog with information message. The corgb button, when clicked, generates a dialog with warning message with Yes, No, Cancel options. The mmb button, when clicked, generates a dialog box with a warning message with an icon. The dialog box for oplangb button is created using the JOptionPane constructor, createDialog() and show() method. The dialog box for corgb button is created using the JOptionPane’s static method showConfirmDialog() method and for the mmb button, showMessageDialog() is used. Program 19.36 /* This program illustrates the creation and use of JOptionPane. somasundaramk@yahoo.com */ import javax.swing.*; import java.awt.*; import java.awt.event.*; class Joption1 extends JFrame { Container conpan; 528 Programming in JAVA2 JButton oplangb, corgb, mmb; JLabel inform; Joption1(String str) { super(str); conpan = getContentPane(); conpan.setLayout(new FlowLayout(FlowLayout.LEFT)); inform = new JLabel(“Click the following to know about them”); oplangb = new JButton(“OOP Language”); corgb = new JButton(“Computer Organization”); mmb = new JButton(“Multimedia”); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent ae) { System.exit(0); } }); oplangb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String langs = “OOP Language deals with\n Object-Oriented Languages like Java/ C++”; JOptionPane jop = new JOptionPane(langs, JOptionPane.INFORMATION_MESSAGE); JDialog jdia = jop.createDialog(oplangb, “Infromation”); Icon laugh = new ImageIcon(“laugh.jpg”); jdia.show(); } }); corgb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String corgs = “Computer Organization deals with\n functioning of a computer”; JOptionPane.showConfirmDialog(corgb, corgs, “Confirm Dialog”, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); } }); Swing and GUI Components 529 mmb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { Icon laugh = new ImageIcon(“laugh.jpg”); String mms = “Multimedia deals with \n the combination of text,audio and video”; JOptionPane.showMessageDialog(mmb, mms, “Warning”, JOptionPane.WARNING_MESSAGE, laugh); } }); conpan.add(inform); conpan.add(oplangb); conpan.add(corgb); conpan.add(mmb); setSize(250, 250); setVisible(true); } } class JOpan1 { public static void main(String args []) { new Joption1(“JOptionPane “); } } The above program gives the following output screens: (a) 530 Programming in JAVA2 Fig.19.38 (b) Output Screens for Program 19.36 a) The first one is the initial screen and the second one shows dialog box created after clicking the oplangb button. b) The first window shows dialog window created after clicking the corgb button and the second after clicking the mmb button. All the dialog windows are manually shifted to show both the main and dialog windows. The dialogs are the after-effect of clicking a button or any component that can generate event. Event listeners are registered with the event source and as and when events occur, the event listeners carry out some process required for that application. For JButton objects, action listeners can be used to capture the event and generate dialog messages. In the previous program 19.36, action listeners were registered with the buttons and the actionPerformed() method was called through the anonymous inner class. This way of processing is straightforward and it is explicitly shown what action will be carried out for each button click. However, if there are more number of components in an application and for each of them only the dialog messages differ, then implementing the actionPerformed() method for each button appears to be repeating the same statements. An alternative way is to implement one common actionPerformed() method for action events received from different event sources. When one actionPerformed() method is used for several event sources (several buttons), it is necessary to identify from which source an event has originated. For that, getSource() and getActionCommand() methods can be used. We will show this technique in program 19.37. Swing and GUI Components 531 Program 19.37 /* This program illustrates the creation and use of JOptionPane. somasundaramk@yahoo.com */ import javax.swing.*; import java.awt.*; import java.awt.event.*; class Joption2 extends JFrame implements ActionListener { Container conpan; JOptionPane jop; JButton oplangb, corgb, mmb; Joption2(String str) { super(str); conpan = getContentPane(); conpan.setLayout(new FlowLayout(FlowLayout.LEFT)); JLabel inform = new JLabel(“Click the following to know about them”); oplangb = new JButton(“OOP Language”); corgb = new JButton(“Computer Organization”); mmb = new JButton(“Multimedia”); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); oplangb.addActionListener(this); corgb.addActionListener(this); mmb.addActionListener(this); oplangb.setActionCommand(“oplang”); corgb.setActionCommand(“corg”); mmb.setActionCommand(“mm”); conpan.add(inform); conpan.add(oplangb); conpan.add(corgb); conpan.add(mmb); setSize(250, 250); setVisible(true); } 532 Programming in JAVA2 public void actionPerformed(ActionEvent ae) { JButton buttonsource = (JButton)ae.getSource(); String cmd = buttonsource.getActionCommand(); String message = null; JDialog jdia; JOptionPane jop; if (cmd == “oplang”) { message = “OOP Language deals with\n ObjectOriented Languages like Java/C++”; JOptionPane.showMessageDialog(buttonsource, message, “Information”, JOptionPane.INFORMATION_MESSAGE); } if (cmd == “corg”) { message = “Computer Organization deals with\n functioning of a computer”; JOptionPane.showMessageDialog(buttonsource, message, “Warning”, JOptionPane.WARNING_MESSAGE); } if (cmd == “mm”) { message = “Multimedia deals with \n the combination of text,audio and video”; Icon magesh = new ImageIcon(“mag65.jpg”); JOptionPane.showMessageDialog(buttonsource, message, “Plain”, JOptionPane.PLAIN_MESSAGE, magesh); } } } class JOpan2 { public static void main(String args []) { new Joption2(“JOptionPane “); } } The above program gives the following output: Swing and GUI Components Fig.19.39 533 Output Screens for Program 19.37 The purpose of generating a dialog is to display a message and get the response from the user. In the case of displaying information message and warning message, press OK button in the dialog box. However, in the case of displaying confirmation message, the user has the option of selecting Yes, No or Cancel. In those occasions, it is necessary to know which button the user has selected in the dialog box. The showConfirmDialog() method returns an int value. This int value represents any of the following values, which can be used for the application: JOptionPane.YES_OPTION JOptionPane.NO_OPTION JOptionPane.CANCEL_OPTION JOptionPane.OK_OPTION JOptionPane.CLOSED_OPTION The last value CLOSED_OPTION represents that the user has closed the dialog window without selecting any option. In the following program 19.38, we will show how to detect the selection made in the dialog window of a confirmation message. We create four JButtons and register action listener with each one of them. When a button is clicked, a dialog with a confirmation message with Yes and No button is displayed using showConfirmDialog() method. When the user clicks either Yes or No button, according to the message displayed, the user’s selection is identified by taking the int value assigned to the variable result1. Accordingly, another dialog message appears, indicating whether the user has selected Yes or No button. 534 Programming in JAVA2 Program 19.38 /* This program illustrates how to create JOptionPane dialog and detect the option button selected by the user. somasundaramk@yahoo.com */ import javax.swing.*; import java.awt.*; import java.awt.event.*; class Joptionuse extends JFrame { Container conpan; JButton teleb, compb, zerob, sunb; JLabel inform1, inform2; int result1; Icon laugh = new ImageIcon(“laugh.jpg”); Joptionuse(String str) { super(str); conpan = getContentPane(); conpan.setLayout(new FlowLayout(FlowLayout.LEFT)); inform1 = new JLabel(“Click the following and “); inform2 = new JLabel(“ test the statements”); teleb = new JButton(“Telescope”); compb = new JButton(“Computer “); zerob = new JButton(“Zero “); sunb = new JButton(“Sun “); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); teleb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String teles = “Aristotle invented Telescope.”; result1 = JOptionPane.showConfirmDialog(teleb, teles, “Confirm Dialog”, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); String selection; switch (result1) Swing and GUI Components 535 { case JOptionPane.YES_OPTION: selection = “Sorry.\n Only Galileo invented Telescope”; break; case JOptionPane.NO_OPTION: selection = “You are RIGHT.\n Only Galileo invented Telescope”; break; case JOptionPane.CLOSED_OPTION: default: selection = “Window closed without answering”; } JOptionPane.showMessageDialog(teleb, “ “ + selection, “Selection”, JOptionPane.INFORMATION_MESSAGE, laugh); } }); compb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String comps = “The concept of present-day computer\n was given by Charless Babbage “; result1 = JOptionPane.showConfirmDialog(compb, comps, “Confirm Dialog”, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); String selection; switch (result1) { case JOptionPane.YES_OPTION: selection = “Yes, You are RIGHT.”; break; case JOptionPane.NO_OPTION: selection = “Sorry, Charless Babbage gave the concept”; break; default: selection = “Window closed without answering”; } JOptionPane.showMessageDialog(compb, selection, “Selection”, 536 Programming in JAVA2 JOptionPane.INFORMATION_MESSAGE, laugh); } }); zerob.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String zeros = “The ancient Indian Mathematician \n gave the zero to the world”; result1 = JOptionPane.showConfirmDialog(zerob, zeros, “Confirm Dialog”, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); String selection; switch (result1) { case JOptionPane.YES_OPTION: selection = “Yes, You are RIGHT.”; break; case JOptionPane.NO_OPTION: selection = “Sorry, Take pride in telling that\n ancient Indians invented Zero”; break; default: selection = “Window closed without answering”; } JOptionPane.showMessageDialog(zerob, selection, “Selection”, JOptionPane.INFORMATION_MESSAGE, laugh); } }); sunb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String suns = “The sun has a solid body”; result1 = JOptionPane.showConfirmDialog(sunb, suns, “Confirm Dialog”, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); String selection; switch (result1) { Swing and GUI Components 537 case JOptionPane.YES_OPTION: selection = “Sorry.\n Sun has a gaseous body”; break; case JOptionPane.NO_OPTION: selection = “Yes. Sun has only gaseous body”; break; default: selection = “Window closed without answering”; } JOptionPane.showMessageDialog(sunb, selection, “Selection”, JOptionPane.INFORMATION_MESSAGE, laugh); } }); conpan.add(inform1); conpan.add(inform2); conpan.add(teleb); conpan.add(compb); conpan.add(zerob); conpan.add(sunb); setSize(200, 250); setVisible(true); } } class JOpuse { public static void main(String args []) { new Joptionuse(“JOptionPane“); } } The above program gives the following output screens: 538 Programming in JAVA2 (a) (b) Fig.19.40 Output Screens for Program 19.38 (a) (b) G First window shows the initial display. The second shows the dialog box after clicking the Zero button. The window shows the response dialog when the No button is selected. For creating simple dialogs, use JOptionPane. To detect which option is selected in a dialog, make use of the int value returned by the static methods. 19.18 JFileChooser The JFileChooser class helps to open a window and display files and directories in a specified path. JFileChooser class is a subclass of JComponent. Using JFileChooser object, one can create user-interface Swing and GUI Components 539 windows for opening or saving files. The look and feel of JFileChooser windows are different from the conventional file Open/Save Window of windowsbased computers. But, the display content and tools are almost the same. JFileChooser operates in three different modes, files only, directories and files and directories. JFileChooser class provides three types of file choosers, which are associated with a dialog. The dialog types are open, save and custom. These dialogs provide options either to proceed with by clicking a button indicating the process or cancel the dialog by clicking cancel option. The methods that create the dialog return integer constants indicating what has been selected by the user. The int type constants are : JFileChooser.APPROVE_OPTION JFileChooser.CANCEL_OPTION 19.18.1 Creating JFileChooser To create file chooser windows, one has to create an object of the type JFileChooser and call methods on the object. This class has several constructors. Some of the constructors are: JFileChooser() Creates a new file chooser using the user’s default directory. JFileChooser(File path) Creates a file chooser using the specified file path JFileChooser(String path) Creates a file chooser using the file specified in the string Methods The JFileChooser has a large number of methods. There are methods to create user windows to open and save files. File filtering methods allow only specified file extensions to be displayed. Some of the methods defined in JFileChooser class are: boolean accept(File f) Returns true if the file is to be displayed void addActionListener(ActionListener al) Adds an action listener to the file chooser JDialog createDialog(Component parent) Creates a dialog with the specified component as its parent 540 Programming in JAVA2 String getApproveButtonText() Returns the text contained in the ApproveButton in the dialog display File getCurrentDirectory() Returns the current directory FileFilter getFileFilter() Returns the currently selected file filter String getName(File f) Returns the file name File[] getSelectedFiles() Returns a list of selected files void setCurrentDirectory(File dir) Sets the specified directory as the current directory void setFileFilter(FileFilter filter) Sets the file filter int showDialog(Component parent, String approveButton) Pops up a custom file chooser dialog with the specified string as approveButton int showOpenDialog(Component parent) Pops up a “Open File” file chooser dialog int showSaveDialog(Component parent) Pops up a “Save File” file chooser dialog 19.18.2 Creating JFileChooser Dialog Using constructors and methods discussed in the previous section, we now show how to create file chooser dialogs. Usually, a file chooser dialog is created when a user clicks a button to open a “Open File” dialog or “Save File” dialog. But, in the following example program 19.39, we create the file chooser dialogs without clicking any button, just to make the concept of opening a file chooser dialog simple. Program 19.39 /* This program illustrates the creation of JFileChooser. somasundaramk@yahoo.com */ import javax.swing.*; import java.awt.*; import java.io.*; Swing and GUI Components import java.awt.event.*; class Filech1 extends JFrame { Container conpan; JFileChooser fchoose; JLabel info; Filech1(String str) { super(str); conpan = getContentPane(); conpan.setLayout(new FlowLayout(FlowLayout.LEFT)); setSize(250, 250); info = new JLabel(“Dialog created with showOpenDialog”); conpan.add(info); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); File myfile = new File(“c:/jdk1.2.1/bin/Swing”); fchoose = new JFileChooser(myfile); fchoose.showOpenDialog(this); setVisible(true); } public static void main(String args []) { new Filech1(“File Chooser”); } } The above program gives the following output screens: 541 542 Programming in JAVA2 (a) (a) (b) 19.18.3 (b) Fig.19.41 Output Screens for Program 19.39 The “Open File” file chooser Screen display after cancel option is clicked by the user. Using JFileChooser In the previous section, we have shown how to create JFileChooser. In this section, we will show how to use the JFileChooser in an application. The example program 19.40 shows how to create a JMenu with File menu and use it like the familiar file handling menu with options, New, Open, Save, Save as and Exit. Menu items, new, open, save, save as and exit, are used to create a JMenu. Each of the menu item generates an ActionEvent and the Swing and GUI Components 543 actionPerformed() method initiates dialogs generated by methods of JFileChooser. Click of the menu item “open” invokes showOpenDialog() method. From the JFileChooser object fch, the file selected by the user is obtained by calling the getSelectedFile() method, which gives a File type object. When the user clicks “open” in the open dialog, the showOpenDialog() returns an integer indicating that JFileChooser.APPROVE_OPTION is selected. From this, the file selected is displayed using showConfirmDialog() method. The user can choose either Yes or No option in the dialog, which ends the open menu item session. Similar process has been added to Save option. The class Respond is developed to create a dialog for the Exit menu item. A manual coding is done using JDialog to create the confirmation dialog Yes or No. (It could have been done more easily through showConfirmDialog() method). We did this only to show how to code JDialog to create interactive dialogs. NO option will return the control to the main window and YES option response to Exit menu item will close the main window. Program 19.40 /* This program illustrates the creation and use of JFileChooser in a JMenu on a JFrame window. somasundaramk@yahoo.com */ import java.awt.*; import java.io.*; import javax.swing.*; import java.awt.event.*; class Fileframe extends JFrame implements ActionListener { Fileframe(String str) { super(str); JMenuBar mbar = new JMenuBar(); setJMenuBar(mbar); JMenu file = new JMenu(“File”); JMenuItem neu = new JMenuItem(“New”); JMenuItem open = new JMenuItem(“Open”); JMenuItem save = new JMenuItem(“Save”); JMenuItem saveas = new JMenuItem(“Save As”); JMenuItem exit = new JMenuItem(“Exit”); neu.addActionListener(this); open.addActionListener(this); save.addActionListener(this); saveas.addActionListener(this); exit.addActionListener(this); file.add(neu); file.add(open); 544 Programming in JAVA2 file.add(save); file.add(saveas); file.add(exit); mbar.add(file); setSize(250, 200); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } public void actionPerformed(ActionEvent ae) { JFileChooser fch = new JFileChooser(“c:/jdk1.2.1/ bin/Swing”); String cmd = “ “; cmd = ae.getActionCommand(); if (cmd == “New”) fch.showDialog(this, “New”); else if (cmd == “Open”) { int odint = fch.showOpenDialog(this); File myfile = fch.getSelectedFile(); if ((odint == JFileChooser.APPROVE_OPTION) && (myfile != null)) JOptionPane.showConfirmDialog(this, “File to open : “ + myfile.getPath(), “Confirm the file Name”, JOptionPane.YES_NO_OPTION); else JOptionPane.showMessageDialog(this, “Cancelled”); } else if (cmd == “Save”) { int sdint = fch.showSaveDialog(this); File myfile = fch.getSelectedFile(); if ((sdint == JFileChooser.APPROVE_OPTION) && (myfile != null)) JOptionPane.showConfirmDialog(this, “Save File : “ + myfile.getPath(), “Confirm the file Name”, JOptionPane.YES_NO_OPTION); else JOptionPane.showMessageDialog(this, Swing and GUI Components 545 “Cancelled”); } else if (cmd == “Save As”) fch.showDialog(this, “Save As”); else if (cmd == “Exit”) new Respond(this, “Confirm Exit”); } } class Respond implements ActionListener { Container dconpan; JDialog dl; Respond(JFrame fm, String title) { dl = new JDialog(fm, title, true); JLabel mesg = new JLabel(“Are you sure you want to Exit?”); JButton yes = new JButton(“Yes”); JButton no = new JButton(“No”); yes.addActionListener(this); no.addActionListener(this); dconpan = dl.getContentPane(); dconpan.setLayout(new FlowLayout(FlowLayout.LEFT)); dconpan.add(mesg); dconpan.add(yes); dconpan.add(no); dl.setSize(200, 100); dl.setVisible(true); } public void actionPerformed(ActionEvent ae) { String res = “ “; res = ae.getActionCommand(); if (res == “Yes”) System.exit(0); else dl.dispose(); } } class JFilech2 { public static void main(String args []) { new Fileframe(“JFileChooser”); } } The above program gives the following output screens: 546 Programming in JAVA2 (a) (b) Swing and GUI Components 547 (c) (d) Fig.19.42 Output Screens for Program 19.40 (a) (b) (c) (d) The first window shows the initial display. The second shows the popup menu after clicking the File menu. The top window shows the open dialog of file chooser. The second shows the message dialog after the Open option is selected. The top window shows the save dialog of the file chooser. The second shows the message dialog after the Cancel option is selected. The window shows the confirmation dialog. No option will take the control back to the menu and Yes option will close the menu window. 548 G Programming in JAVA2 To capture the options selected by the user in showOpenDialog(), showOptionDialog() and showSaveDialog() methods, use the integers returned by these methods. Test the integers with JFileChooser.APPROVE_OPTION or JFileChooser.CANCEL_OPTION. 19.19 JProgressBar JProgressBar object gives the visual component that shows the amount of progress of a process that is taking place. It gives a continuously progressing shade, which is proportional to the percentage of work that has been carried out. JProgressBar is a subclass of JComponent. A JProgressBar can be used wherever a process that takes a long time to complete is to be informed to the user. The lowest point of the progress bar is called minimum value and the highest point is called the maximum value. Any point in between the two is called as value. 19.19.1 Creating JProgressBar A JProgressBar can be created in two different orientations. orientations are specified by two integer constants: JProgressBar.VERTICAL JProgressBar.HORIZONTAL The two which define the orientation of the progress bar in vertical or horizontal direction. Some of the constructors used to create a JProgressBar are: JProgressBar() Creates a horizontal progress bar that displays a border; minimum value is 0 and the maximum value is 100. the initial JProgressBar(int orientation) Creates a new progress bar in the specified orientation; minimum value is 0 and the maximum is 100. the initial JProgressBar(int min, int max) Creates a new horizontal progress bar with the specified minimum and maximum value JProgressBar(int orientation, int min, int max) Creates a progress bar with the specified orientation with the specified minimum and maximum value Swing and GUI Components 549 Methods The JProgressBar class has a number of methods to update and manage a progress bar. Some of the methods defined in JProgressBar class are : void addChangeListener(ChangeListener cl) Adds the specified change listener to the progress bar int getMaximum() Returns the maximum value of the progress bar int getMinimum() Returns the minimum value of the progress bar int getOrientation() Returns the orientation of the progress bar double getPercentComplete() Returns the percent complete for the progress bar String getString() Returns the current value of the progress string int getValue() Returns the current value of the progress bar void setMaximum(int max) Sets the maximum value for the progress bar void setMinimum(int min) Sets the minimum value for the progress bar void setString(String str) Sets the value of the progress string void setStringPainted(boolean b) Sets the stringPainted property that determines whether the progress bar should render a progress string or not void setValue(int value) Sets the progress bar’s current value 19.19.2 Creating JProgressBar on JFrame Progress bar can be created using the constructor methods of JProgressBar. Methods in the JProgressBar class can be used to make the progress bar useful to an application. After creating a progress bar, the minimum and maximum value of the progress has to be set. The interval between minimum and maximum will be converted to 100 units. The 550 Programming in JAVA2 percentComplete() method returns this value between 0 and 1. A progress bar will be continuously added on the progress bar. The setValue() method will automatically update the progress bar. There is no separate method required to update. We show in program 19.41, the technique of creating a horizontal progress bar, simulating a simple process, incrementing some value and making the progress bar propagate. A process like task is created by introducing a delay loop using sleep() method. Program 19.41 /* This program illustrates the creation of a JProgressBar on a JFrame. somasundaramk@yahoo.com */ import java.awt.*; import java.awt.event.*; import javax.swing.*; class JPbar1 extends JFrame { Container conpan; int max = 1000; int min = 0; int value; int incr = (max - min) / 100; JProgressBar jpbar; JPbar1(String str) { super(str); conpan = getContentPane(); conpan.setLayout(new FlowLayout()); jpbar = new JProgressBar(); jpbar.setMaximum(max); jpbar.setMinimum(min); jpbar.setValue(value); conpan.add(jpbar); setSize(250, 200); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); Swing and GUI Components 551 // This delay is introduced to simulate a process try { for (int i = 0; i < 100; i++) { Thread.sleep(500); value = value + incr; jpbar.setValue(value); } } catch (InterruptedException e) { ; } } public static void main(String args []) { new JPbar1(“JProgressBar on JFrame “); } } The above program gives the following output screens: Fig.19.43 Output Screens for Program 19.41 The first window shows the progress bar status after progressing for about 20%. The second screen shows progress after 100%. G No separate method is needed to update a progress bar. 19.19.3 Using JProgressBar Progress bars are needed wherever a time-consuming process takes place, to inform the user about the progress of the process. In the absence of such information, the user is not aware what is happening inside the program code. 552 Programming in JAVA2 In the following program 19.42, we show how a progress bar can be set up and the progress of the process is displayed on the progress bar. We first create a JProgressBar. By default, it is a horizontal progress bar. We then create a JButton with a text ”Start”. An empty info JLabel is created and added to the contentPane of JFrame. Another JButton with text Cancel is added to the contentPane. An action listener is registered with the start button. The time-consuming process and updation of the progress bar are placed in a separate thread and called in the actionPerformed() method. A separate thread is necessary as the action event thread will not process the action event until the time-consuming process is complete. When the user clicks Start button, the simulated time-consuming process and the progress bar updation take place. The start button is disabled from any more action on it. During the process, the Cancel button appears using which the process can be cancelled. At the completion of the process, the same Cancel button is made as Finish button. Program 19.42 /* This program illustrates the use of JProgressBar. somasundaramk@yahoo.com */ import java.awt.*; import java.awt.event.*; import javax.swing.*; class Pbarframe extends JFrame implements ActionListener { Container conpan; JButton begin, cancel; JLabel info; int max = 1000; int min = 0; int value; // divide the interval into 100 units int incr = (max - min) / 100; JProgressBar jpbar; Pbarframe(String str) { super(str); conpan = getContentPane(); conpan.setLayout(new FlowLayout()); info = new JLabel(); begin = new JButton(“Start “); cancel = new JButton(“Cancel”); jpbar = new JProgressBar(); jpbar.setStringPainted(true); Swing and GUI Components conpan.add(begin); conpan.add(jpbar); conpan.add(info); conpan.add(cancel); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { System.exit(0); } }); setSize(250, 200); setVisible(true); begin.addActionListener(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } // This thread updates the progress bar values. class Updatebar extends Thread { public void run() { begin.setEnabled(false); info.setText(“Process in progress. Please wait......”); jpbar.setMaximum(max); jpbar.setMinimum(min); jpbar.setValue(value); // This delay is introduced to simulate // a process try { for (int i = 0; i < 100; i++) { Thread.sleep(500); value = value + incr; jpbar.setValue(value); } } catch (Exception e) { ; } info.setText(“Process complete”); 553 554 Programming in JAVA2 cancel.setText(“Finish”); } } public void actionPerformed(ActionEvent ae) { (new Updatebar()).start(); } } class JPbar2 { public static void main(String args []) { new Pbarframe(“Using JProgressBar “); } } The above program gives the following output screens: (a) (b) Fig.19.44 Output Screens for Program 19.42 (a) The initial window (b) The first window shows the screen after 35% completion of the process. Note the Start button is disabled. The second window shows the screen after 100% completion of the process. Swing and GUI Components G 555 In an action-driven process, use a separate thread to update the progress bar. By default, the setStringPainted() method displays the percentage of progress in numerical digits. However, if setString(“String”) is called, the numeric digit will be removed and the String will be displayed in the bar. 19.20 Layout Managers In the previous sections, we have seen how to add components on the container (like window). All the components like buttons, labels, check boxes were added at locations defined by default locations of the container. For placing the components in a container, layout managers are used. Each container has a default layout manager. Java defines several layout managers. A container can set the required layout manager using setLayout() method. Some of the layout managers are explained in this section. 19.20.1 BorderLayout BorderLayout class has a layout manager that divides its container into five regions and fits the components into it. The five regions are north, south, east, west, and center as given in fig. 19.45: north west east center south Fig. 19.45. The BorderLayout Each of these regions is represented by a string constant. They are: BorderLayout.CENTER - BorderLayout.EAST - The center layout constraint (middle of container) The east layout constraint (right of container) 556 Programming in JAVA2 BorderLayout.NORTH - BorderLayout.SOUTH - The north layout constraint (top of container) The south layout constraint (bottom of container) Constructors The BorderLayout class has the following constructors for creating border layout: BorderLayout() Creates a new border layout with no gap between components BorderLayout (int hgap, int vgap) Creates a border layout with the specified gaps between components; hgap specifies the horizontal gap and vgap specifies the vertical gap. the Methods Some of the methods defined in this class are given below. int getHgap() Returns the horizontal gap between components void setHgap(int hgap) Sets the horizontal gap between components public int getVgap() Returns the vertical gap between components void setVgap(int vgap) Sets the vertical gap between components void addLayoutComponent(Component comp, Object constraints) Adds the specified component to the layout using the specified constraint object; the constraints must be one of the constraints, NORTH, SOUTH, EAST, WEST or CENTER. To add components to a container, the string constraints can be used as parameters. The following methods are defined in Container class: void add(Component comp, Object constraints) Adds the specified component to the end of the container void add(Component comp, Object constraints, int index) Adds the specified component to this container constraints at the specified index with the specified Swing and GUI Components In the following program 19.43, the use of border layout is given: Program 19.43 /* This program illustrates the use of BorderLayout. somasundaramk@yahoo.com <applet code = Bordera1 width = 250 height = 150> </applet> */ import java.awt.*; import javax.swing.*; import java.applet.*; public class Bordera1 extends JApplet { JButton north, south, east, west, center; Container conpan; public void init() { conpan = getContentPane(); BorderLayout bl = new BorderLayout(); conpan.setLayout(bl); north = new JButton(“NORTH “); south = new JButton(“SOUTH “); east = new JButton(“EAST “); west = new JButton(“WEST “); center = new JButton(“CENTER “); conpan.add(north, BorderLayout.NORTH); conpan.add(south, BorderLayout.SOUTH); conpan.add(west, BorderLayout.WEST); conpan.add(east, BorderLayout.EAST); conpan.add(center, BorderLayout.CENTER); setVisible(true); } } The output screen for program 19.43 is given below: 557 558 Programming in JAVA2 Fig.19.46 Output Screen for Program 19.43 In program 19.43, gaps can be introduced between components by inserting the following methods: bl.setVgap(10); bl.setHgap(10); After inserting the above statement, program 19.43 will give the following output: Fig.19.47 Output Screen for Program 19.43 with Vertical and Horizontal Gap 19.20.2 FlowLayout In the FlowLayout manager, components are manner, like the flow of words in a line. When no line, it is taken to the next line. A small space is Components are arranged in a centered layout. It JApplet. arranged in a left-to-right more components fit in a left between components. is the default layout for The FlowLayout class defines the following integer constants representing the different orientations: Swing and GUI Components FlowLayout.CENTER - FlowLayout.LEFT - FlowLayout.RIGHT - 559 Indicates that each row of component should be centered Indicates that each row of component should be left-justified Indicates that each row of component should be right-justified Constructors The FlowLayout class defines the following constructors to create flow layout managers: FlowLayout() Creates a new flow layout with a centered alignment and a default 5 pixel horizontal and vertical gap FlowLayout(int align) Creates a new flow layout with the specified alignment with default 5 pixel horizontal and vertical gap; the value of the alignment must be one of the values, FlowLayout.CENTER, FlowLayout.LEFT or FlowLayout.RIGHT. FlowLayout(int align, int hgap, int vgap) Creates a new flow layout with the specified alignment, horizontal gap and vertical gap; the value of the alignment must be one of the values, FlowLayout.CENTER, FlowLayout.LEFT or FlowLayout.RIGHT. Methods The FlowLayout class has the following methods: int getAlignment() Returns the alignment value for this layout void setAlignment(int align) Sets the alignment value for this layout int getHgap() Returns the horizontal gap between components void setHgap(int hgap) Sets the horizontal gap between components int getVgap() Returns the vertical gap between components void setVgap(int vgap) Sets the vertical gap between components 560 Programming in JAVA2 In the program 19.44, the use of FlowLayout is given. JRadioButtons are created and grouped. These buttons are placed on a JFrame window. JLabel component is added to make the application suitable for a quiz. Program 19.44 /* This program illustrates the use of FlowLayout manager. The JRadioButtons are placed on JPanel window. The JRadioButtons are grouped using ButtonGroup. somasundaramk@yahoo.com */ import java.awt.*; import javax.swing.*; import java.awt.event.*; class Flowpanel extends JPanel implements ItemListener, ActionListener { JButton ok; JRadioButton rb1, rb2, rb3; ButtonGroup rbxg; String cmd; boolean state; Flowpanel() { Font fnt = new Font(“Courier”, Font.BOLD, 14); setFont(fnt); rbxg = new ButtonGroup(); setLayout(new FlowLayout(FlowLayout.LEFT)); ok = new JButton(“OK”); rb1 = new JRadioButton(“C++”, true); rb2 = new JRadioButton(“Java”, false); rb3 = new JRadioButton(“Pascal”, false); add(rb1); add(rb2); add(rb3); add(ok); rbxg.add(rb1); rbxg.add(rb2); rbxg.add(rb3); ok.addActionListener(this); rb1.addItemListener(this); rb2.addItemListener(this); rb3.addItemListener(this); } public void actionPerformed(ActionEvent ae) { cmd = ae.getActionCommand(); Swing and GUI Components 561 repaint(); } //implemented to meet the interface requirement public void itemStateChanged(ItemEvent ie) { } public void paintComponent(Graphics gp) { super.paintComponent(gp); state = rb3.isSelected(); gp.drawString(“Which of the above is not an OOP language?”, 20, 70); gp.drawString(“Press OK after selection”, 20, 90); if (cmd != null) { if (state) gp.drawString(“Yes, you are right“, 20, 110); else gp.drawString(“Sorry, you are wrong”,20,110); } } } class Flowframe extends JFrame { Container conpan; Flowframe(String str) { super(str); conpan = getContentPane(); conpan.add(new Flowpanel()); setSize(375, 200); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } } class Flowlof { public static void main(String args []) { 562 Programming in JAVA2 new Flowframe(“Quiz using JRadioButton “); } } The above program gives the following output: Fig.19.48 Output Screens for Program 19.44 The top screen shows the initial display. The bottom screen shows the screen after the user has selected an option. 19.20.3 GridLayout The GridLayout class manager arranges the components into a rectangular, two-dimensional grid of rows and columns. The container is divided into equal-sized rectangles and one component is placed in each rectangle. Constructors The GridLayout class provides the following constructors to create grid layout: GridLayout() Creates a new grid layout with one column per component in a single row GridLayout(int rows, int columns) Creates a new grid layout with a specified number of rows and columns GridLayout(int rows, int columns, int hgap, int vgap) Swing and GUI Components 563 Creates a new grid layout with a specified number of rows and columns; the horizontal gap hgap is set between each column and at the left and right edges. The vertical gap vgap is set between each row and at the top and bottom. Methods The methods defined in this GridLayout class are given below: int getRows() Returns the number of rows in this layout void setRows(int rows) Sets the number of rows in this layout int getColumns() Returns the number of columns in this layout void setColumns(int Columns) Sets the number of columns in this layout int getHgap() Returns the horizontal gap between the components void setHgap(int hgap) Sets the horizontal gap between the components int getVgap() Returns the vertical gap between components void setVgap(int vgap) Sets the vertical gap between components The following program 19.45 illustrates the use of GridLayout manager: Program 19.45 /* This program illustrates the use of GridLayout manager. somasundaramk@yahoo.com <applet code = Gridap1 width = 200 height = 150> </applet> */ import java.awt.*; import javax.swing.*; import java.awt.event.*; class Gridpanel extends JPanel { Gridpanel() 564 Programming in JAVA2 { setLayout(new GridLayout(2, 3)); add(new JButton(“A”)); add(new JButton(“B”)); add(new JButton(“C”)); add(new JButton(“D”)); add(new JButton(“E”)); add(new JButton(“F”)); } } class Gridlo1 extends JFrame { Container conpan; Gridlo1(String str) { super(str); conpan = getContentPane(); conpan.add(new Gridpanel()); setSize(250, 200); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String args []) { new Gridlo1(“GridLayout”); } } The program 19.45 gives the following output: Fig.19.49 Output Screen for Program 19.45 Swing and GUI Components 565 Program 19.46 shows an application of grid layout. JRadioButtons are created and grouped using ButtonGroup. Whenever a user checks a button, the selection is displayed on the corresponding button on the second column. Checking a button creates an item event. The state of each button is obtained and the selection is displayed on the button. Program 19.46 /* This program illustrates the use of Gridlayout. JRadioButtons are placed on JPanel window. The JRadioButton components are arranged using the GridLayout manager. somasundaramk@yahoo.com */ import java.awt.*; import javax.swing.*; import java.awt.event.*; class Gridap2 extends JPanel implements ItemListener { JRadioButton rb1, rb2, rb3; ButtonGroup rbg; boolean st1, st2, st3; JButton pas, cpp, java; String pass, cpps, javas; Gridap2() { pass = “Pascal Selected “; cpps = “ “; javas = “ “; // make 4 rows and 2 columns layout GridLayout glo = new GridLayout(4, 2); setLayout(glo); rbg = new ButtonGroup(); rb1 = new JRadioButton(“C++”, false); rb2 = new JRadioButton(“Java”, false); rb3 = new JRadioButton(“Pascal”, true); rb1.addItemListener(this); rb2.addItemListener(this); rb3.addItemListener(this); pas = new JButton(pass); cpp = new JButton(cpps); java = new JButton(javas); JLabel lbl = new JLabel(“Check Your Option”); rbg.add(rb1); rbg.add(rb2); 566 Programming in JAVA2 rbg.add(rb3); add(rb1); add(cpp); add(rb2); add(java); add(rb3); add(pas); add(lbl); } // Update the screen when a check box state is changed public void itemStateChanged(ItemEvent ie) { st1 = rb1.isSelected(); st2 = rb2.isSelected(); st3 = rb3.isSelected(); if (st1) { pass = “”; cpps = “C++ Selected”; javas = “”; cpp.setText(cpps); java.setText(javas); pas.setText(pass); } if (st2) { pass = “”; cpps = “”; javas = “Java Selected”; cpp.setText(cpps); java.setText(javas); pas.setText(pass); } if (st3) { pass = “Pascal Selected”; cpps = “”; javas = “”; cpp.setText(cpps); java.setText(javas); pas.setText(pass); } } } class Gridlo2 extends JFrame Swing and GUI Components 567 { Container conpan; Gridlo2(String str) { super(str); conpan = getContentPane(); conpan.add(new Gridap2()); setSize(300, 200); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } public static void main(String args []) { new Gridlo2(“GridLayout Application”); } } The above program gives the following output: Fig.19.50 Output Screens for Program 19.46. The first window shows the initial screen. The second window shows the screen after the user has made a selection. 19.20.4 CardLayout A card layout is a layout manager for a container. The components of the container are treated as a stack of cards. At any time, one card is visible. The first component added to the card is the visible component when the container is displayed (see fig.19.51). 568 Programming in JAVA2 C4 C3 C2 C1 Fig.19.51 Card Layout CardLayout provides methods to display a card of the user’s choice. Cards can be displayed sequentially using suitable methods defined in CardLayout. To make a card, a JPanel is to be created and components are to be attached to it. Make the required number of such cards. Create a (master) JPanel and set that panel to have a CardLayout manager. Then add all the cards to the panel. Then add this main panel to JApplet window or JFrame window. 19.20.4.1 Creating CardLayout CardLayout managers are created using constructors defined in it. constructors are : The CardLayout() Creates a new card layout with no gaps surrounding the card CardLayout(int hgap, int vgap) Creates a new card layout with the specified vertical and horizontal gaps; the horizontal gap appears at the top and bottom edges. The vertical gap appears at the left and right edges. Methods CardLayout class has several methods to handle the layout. Some of the methods are : void addLayoutComponent(Component comp, Object Constraints) Adds the specified component to this card layout’s internal table of names; the Object specified must be a string. The card layout stores this string as a key-value pair that can be used for random access to a particular card. Using the show method, an application can display the component with the specified name. Swing and GUI Components 569 void first(Container parent) Shows the first card of the container void next(Container parent) Shows the next card of the specified container; first card is shown. after the last card, the void previous(Container parent) Shows the previous card of the specified container; after the first is the last card. the previous card void last(Container parent) Shows the last card of the container In addition, the following methods defined in Container class are used to add components to container: void add(Component comp, Object constraints) Adds the specified component to the end of this container; the specified Object, usually a string, standing for the name of the component, is added to the layout manager’s list void add(Component comp, Object Constraints, int index) Adds the specified component at the specified location; the object representing the name of the component is added to the layout manger’s list. 19.20.4.2 Using CardLayout To understand how to use the CardLayout manager and methods defined in it, we have developed the program 19.47 with two cards. Two cards, “fruits” and “animals”, are prepared in a panel and attached to another panel set with CardLayout manager and added to the applet panel. By default, the first card will be displayed, whether the show method is called or not. Events registered on the button on the applet panel are listened and, for each action, the next card is called by using the next method. Program 19.47 /* This program illustrates the use of CardLayout. Two cards are created on JPanel and attached to another JPanel. The master JPanel, which contains the two cards, is then added to a JFrame is available for their display. Cards can be attached to Panel only. somasundaramk@yahoo.com */ 570 Programming in JAVA2 import java.awt.*; import javax.swing.*; import java.awt.event.*; class Card1 extends JPanel implements ActionListener { JPanel fruits, animals; JPanel cardholder = new JPanel(); CardLayout cl; Card1() { setLayout(new FlowLayout()); cl = new CardLayout(); cardholder.setLayout(cl); // create the first card fruits = new JPanel(); fruits.setLayout(new GridLayout(2, 3)); JButton apl = new JButton(“Apple”); JButton ban = new JButton(“Banana”); JButton grp = new JButton(“Grapes”); JButton jac = new JButton(“Jackfruit”); JButton man = new JButton(“Mango”); JButton lem = new JButton(“Lemon”); JButton ora = new JButton(“Orange”); fruits.add(apl); fruits.add(ban); fruits.add(grp); fruits.add(jac); fruits.add(man); fruits.add(ora); //create the second card animals = new JPanel(); animals.setLayout(new GridLayout(2, 3)); JButton ant = new JButton(“Antelope”); JButton bis = new JButton(“Bison”); JButton gor = new JButton(“Gorilla”); JButton ele = new JButton(“Elephant”); JButton cow = new JButton(“Cow”); JButton lio = new JButton(“Lion”); JButton tig = new JButton(“Tiger”); JButton cam = new JButton(“Camel”); animals.add(ant); animals.add(bis); animals.add(gor); animals.add(ele); Swing and GUI Components 571 animals.add(cow); animals.add(tig); animals.add(cam); // add the two cards to the main panel cardholder.add(fruits, “Card1”); cardholder.add(animals, “Card2”); // add the main panel to add(cardholder); panel //show the second card as initial screen cl.show(cardholder, “Card2”); // add a Next Card Button to the applet panel JButton nxt = new JButton(“Next card”); add(nxt); nxt.addActionListener(this); } //show the next card for each press of the Next card //button public void actionPerformed(ActionEvent ae) { cl.next(cardholder); } } class Cardlo extends JFrame { Container conpan; Cardlo(String str) { super(str); conpan = getContentPane(); conpan.add(new Card1()); setSize(370, 150); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } public static void main(String args []) { JFrame clfrm = new Cardlo(“CardLayout on JFrame”); clfrm.setVisible(true); } } 572 Programming in JAVA2 The above program gives the following output: Fig.19.52 Output Screens for Program 19.47 The top window shows the initial display. The bottom window shows the screen after the user clicked Next button. After reading this chapter, you should have learned the following concepts: Ü Creation of various JComponents in Swing Ü Adding JComponents on JFrame, JApplet and JPanel Ü Registering various listeners to the JComponents Ü Carrying out the desired process when a component is clicked Ü Using different layout managers to layout the JComponent Ü Using JComponents in various applications In the next chapter, the basics of networking is explained. Swing and GUI Components 573 Worked Out Problem–19 19.1w. Design a screen to input the bill details and prepare an on-line bill. Name of Customer : 25 Characters - Key Input Item : Selectable from 10 Items - Use Combo Box Unit Price : Floating Point Automatically selected when Item is selected Qty. Sold : Integer - Key Input Amount : Unit Price x Qty. Sold Tax Rate : Floating Point xx.xx Automatically selected when Item is selected. Total Cost : Amount(1 + Tax Rate/100) Program 19.1w /* This program illustrates how to make data entry and prepare a bill in a company. Once a bill is prepared, it is written into a disk file. somasundaramk@yahoo.com */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; import java.io.*; class Combopanel extends JPanel implements ItemListener, ActionListener { JTextField namef, pricef, qtyf, taxf, amountf, costf; JTextField keysource; JLabel namel, iteml, qtyl, pricel, amountl, taxl, costl; JButton cal, clear; String itemnam [] = new String[10]; double itemprice [] = new double[10]; double taxtable [] = new double[10]; JComboBox itemcombo; JComboBox combosource; String selectitem, selectprice; 574 Programming in JAVA2 int selectindex; int qtysold; double taxrate, unitprice, amount, totalcost; // date variables int day, month, year; String date; JLabel datel, datefield; ObjectOutputStream objos; Combopanel() { GregorianCalendar calendr = new GregorianCalendar(); day = calendr.get(Calendar.DATE); month = calendr.get(Calendar.MONTH); month += 1; // January is 0 hence this conversion year = calendr.get(Calendar.YEAR); // create file for storing bill deatils in a file try { FileOutputStream fos = new FileOutputStream(“bill.dat”, true); objos = new ObjectOutputStream(fos); } catch (IOException ioe) { JOptionPane.showMessageDialog(this, “File opening problem”); } setLayout(new GridLayout(10, 2)); String itemname [] = { “Bolt”,“Cutter”,“Emmery Paper”,“Hammer”, “Latch”,“Nut”,“Paint”,“Pipe”, “Screw”,“Rings” }; double price [] = {25.75, 125.50,8.50, 200.0, 25.0, 2.0, 150.75, 300.0, 1.50, 4.50 }; double tax [] = { 4.0,8.5,0,5.0,0,0,12.5, 10.0,0,2.0 }; itemcombo = new JComboBox(); for (int i = 0; i < itemname.length; i++) { Swing and GUI Components 575 itemcombo.addItem(itemname[i]); itemnam[i] = itemname[i]; itemprice[i] = price[i]; taxtable[i] = tax[i]; } itemcombo.addItemListener(this); JLabel company=new JLabe(“SOMSON HARDWARE MART “); JLabel adrs1 = new JLabel(“21-New Street,Chennai-24”); datel = new JLabel(“Date “); date = “ “ + day + “-” + month + “-” + year; datefield = new JLabel(date); namel = new JLabel(“Customer Name”); namef = new JTextField(25); iteml = new JLabel(“Item “); pricel = new JLabel(“Unit Price “); pricef = new JTextField(“ “ + price[0], 6); pricef.setEditable(false); qtyl = new JLabel(“Quantity Sold “); qtyf = new JTextField(“0”, 3); amountl = new JLabel(“Amount Rs. “); amountf = new JTextField(“0”, 6); amountf.setEditable(false); taxl = new JLabel(“Tax Rate “); taxf = new JTextField(“0”, 5); taxf.setEditable(false); costl = new JLabel(“Total Cost Rs. “); costf = new JTextField(“0”, 6); costf.setEditable(false); cal = new JButton(“Calculate”); cal.addActionListener(this); clear = new JButton(“Clear Entry”); clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { namef.setText(“”); qtyf.setText(“”); taxf.setText(“”); amountf.setText(“”); costf.setText(“”); } }); add(company); add(adrs1); add(datel); add(datefield); add(namel); add(namef); 576 Programming in JAVA2 add(iteml); add(itemcombo); add(pricel); add(pricef); add(qtyl); add(qtyf); add(amountl); add(amountf); add(taxl); add(taxf); add(costl); add(costf); add(cal); add(clear); } public void itemStateChanged(ItemEvent ie) { combosource = (JComboBox)ie.getSource(); selectitem = (String)combosource.getSelectedItem(); selectindex = combosource.getSelectedIndex(); pricef.setText(“ “ + itemprice[selectindex]); taxf.setText(“ “ + taxtable[selectindex]); } public void actionPerformed(ActionEvent ae) { try { qtysold = Integer.parseInt(qtyf.getText()); } catch (NumberFormatException ne) { JOptionPane.showMessageDialog(this, “Quantity sold should be an integer”, “Warning”, JOptionPane.WARNING_MESSAGE); } unitprice = itemprice[selectindex]; if (qtysold == 0) JOptionPane.showMessageDialog(this, “Quantity sold is zero. Please check the entry”, “Warning”, JOptionPane.WARNING_MESSAGE); amount = qtysold * unitprice; amountf.setText(“” + amount); taxrate = taxtable[selectindex]; totalcost = amount * (1 + taxrate / 100); costf.setText(“” + totalcost); Swing and GUI Components 577 // write the data to the file String custname = namef.getText(); CreateRecord objrec = new CreateRecord(custname, date, selectitem, unitprice, qtysold, taxrate,amount); new AddRecord(objos, objrec, this); } } class CreateRecord implements Serializable { String customername, itemname, date; double itemcost, taxrate, amount; int qtysold; CreateRecord(String cnam, String dat, String itemnam, double itcost, int qsold, double tax, double amt) { customername = cnam; date = dat; itemname = itemnam; itemcost = itcost; qtysold = qsold; taxrate = tax; amount = amt; } } class AddRecord { AddRecord(ObjectOutputStream ous, Object obj, JPanel jp) { try { ous.writeObject(obj); } catch (IOException ioe) { JOptionPane.showMessageDialog(jp, “File writing problem”); } } } class Dfcomboframe extends JFrame { Container conpan; Dfcomboframe(String str) 578 Programming in JAVA2 { super(str); conpan = getContentPane(); setSize(340, 250); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); conpan.add(new Combopanel()); setVisible(true); } } class Prob191 { public static void main(String args []) { new Dfcomboframe(“BILL PREPARATION “); } } The above program gives the following output screens: (a) Swing and GUI Components 579 (b) Fig.19.53 Output Screens for Program 19.1W Exercise-19 I. Fill in the blanks 19.1 The Swing classes are part of __________ . 19.2 The top level windows in Swing are ______, ______, ______, _____. 19.3 JComponents are added on the __________ . 19.4 JFrame can be closed using Close Window icon. True/False 19.5 Images can be used in creating JButton. True/False 19.6 To arrange the components of a container, all top level containers are to be set with a ___________ . 19.7 In JLabel ________ line(s) of text can be used as label. 19.8 JToggleButton is a ________ state button. 19.9 A JList displays a ________ which can be selected. 19.10 A ScrollPane is used to view _________ of a large text or image. 19.11 A JTextField can handle text with _______ font and ______ color. 19.12 A text in a JList ______ be edited while the text in a JTextField _____ be edited. 19.13 A JComboBox is like the combination of __________ . 19.14 A modal JDialog _________ input to other window. 19.15 Simple pre-configured dialogs can be created quickly using ______. 19.16 For creating dialogs for files and directories ________ is used. 19.17 The amount of work carried out by a process can be displayed using ________ . 580 Programming in JAVA2 II. Write programs for the following problems: 19.18 Create 4 JButtons with labels 1, 2, 3 and 4 and display them on a JFrame window. When you push a button, the number on it is to be displayed on a JLabel. When more number of buttons are pressed, the label on them is to be printed as a single sequence of digits on the JLabel. 19.19 An objective-type question has three choices. One of the choices is the correct answer. There are five objective-type questions. Each selection of correct answer is given 2 marks. A wrong answer is awarded - 1/2 mark. Each question is to be answered in a 30second duration. At the end of the session, the total score is to be displayed. Write a Java program with the use of appropriate JCheckBox to implement the above problem. 19.20 It is required to get the name and date of birth of the user. Put up appropriate JTextField that enables the user to type in his/her name. Make use of separate JComboBox for year, month and date, which are to be selected. After the selection, the selected items are to be displayed on the screen. Write a program to implement the above requirement. 19.21 Set up a text area with a 2-line visible window. Set it as editable. Allow a user to type in 3 to 5 lines. Set up a second text field with a 2-line visible window and make it as non-editable. Select characters in the first text field and form valid English words to appear inside the second text area. Create 10 such words with a blank space between each word. 19.22 Write a program to simulate a calculator using JButton and JTextField. 19.23 Write a program to prepare an electronic spread sheet with as many functions as you can. 19.24 Prepare a monthly calendar for one year with one card per month using CardLayout. 19.25. Write JMenu for the following structure: Swing and GUI Components 581 Subjects Maths Physics Computer Science Languages Basic Computer Organization COBOL Network C++ JAVA 19.26. Set up CardLayout in a panel. Prepare cards to display one question as JLabel, with four JCheckBox. Allow the user to check the boxes. Whenever a choice is checked, a JDialog is to be displayed whether the choice is the correct answer or not. Repeat it for 5 cards and show the cards sequentially. * * * * * * 582 Programming in JAVA2 BLANK 583 Chapter 20 NETWORKING In this chapter, you will learn some basic concepts of networking using Java tools. Transfer of TCP/IP packets in the connection-oriented service and transfer of UDP packets in connectionless service are explained. Java provides a package java.net to handle networking aspects. Most of the tools to deal with internet-related process are handled in this package. Java2 supports TCP/IP, TCP and UDP protocols. The classes in the java.net package are: Authenticator ContentHandler DatagramSocket DatagramSocketImpl HTTPURLConnection InetAddress JarURLConnection MulticastSocket NetPermission PasswordAuthentication ServerSocket Socket SocketImpl SocketPermission URL URLClassLoader URLConnection URLDecoder URLEncoder URLStreamHandler 584 Programming in JAVA2 The interfaces defined in java.net are: ContentHandlerFactory FileNameMap SocketOptions URLStreamHandlerFactory 20.1 InetAddress Every computer connected to the internet has an address called IP(Internet Protocol) address. This address is necessary to establish a connection by a computer with another one. When messages are exchanged, the message packets contain the IP address. The IP address is a 32-bit number and is expressed as a group of four numbers separated by a dot. For example, 132.162.130.128 is an IP address. The IP address is handled in the class InetAddress. The methods defined in this class are : boolean equals(Object ob) Returns true if the object ob contains the same IP address as that of this object byte[] getAddress() Returns the raw IP address of this object; the result is in network byte order. String getHostName() Returns the host name for this IP address String getHostAddress() Returns the IP address in a string form String toString() Returns a string representation of this IP address static InetAddress getByName(String host) Returns the IP address for the given host; the host name can either be a machine name like “ruraluniv.org” or a string representing its IP address “205.31.45.101”. Throws UnknownHostException static InetAddress[] getAllByName(String host) Returns an array of all the IP addresses for the given host; the host name can either be a machine name or its IP address. Throws UnknownHostException static InetAddress getLocalHost() Returns the IP address of the local host; throws UnknownHostException boolean isMulticastAddress() Returns true, if this IP address is a multicast address, i.e., a class D address with first four bits as 1110 Networking 585 Remembering the IP address as a sequence of four numbers is difficult. Therefore, every IP address is associated with a string called domain name. For example, the IP address 192.18.97.71 is associated with www.java.sun.com and IP address 66.33.109.23 is associated with the name www.ruraluniv.org. A server keeps the database of IP addresses and the associated domain names. Such servers are called Domain Name System(DNS). The program 20.1, illustrates some of the methods defined in InetAddress class: Program 20.1 // This program illustrates the use of various // methods in class InetAddress. // somasundaramk@yahoo.com import java.net.*; class Inetadrs { public static void main(String args []) { InetAddress iphost, javasun, ruraluniv; try { javasun = InetAddress.getByName(“java.sun.com”); InetAddress [] yahoo = InetAddress.getAllByName(“yahoo.com”); ruraluniv = InetAddress.getByName(“ruraluniv.org”); System.out.println(“IP address of java.sun.com = “ + javasun); int yahoolen = yahoo.length; for (int i = 0; i < yahoolen; i++) System.out.println(“IP address of yahoo.com = “ + yahoo[i]); System.out.println(“IP address of ruraluniv.org = “ + ruraluniv); iphost = InetAddress.getLocalHost(); System.out.println(“Local host address = “ + iphost); System.out.println(“Name of the host :” + iphost.getHostName()); } catch (UnknownHostException e) { System.out.println(“Host address could not be found “ + e); } } } 586 Programming in JAVA2 The above program gives the following output: IP address of java.sun.com IP address of yahoo.com IP address of ruraluniv.org Local host address Name of the host :ks G = java.sun.com/192.18.97.71 = yahoo.com/66.218.71.198 = ruraluniv.org/66.33.109.23 = ks/202.9.169.168 The address of the computer connected to the internet is called IP (Internet Protocol) address and is 32-bit in length. This number is expressed as a group of four numbers separated by a dot. Example: 132.162.130.225. 20.2 Socket Programming To establish a connection between one host and another in a network, the socket mechanism is used. A socket is used to connect the Java’s I/O to other programs in the same machine or to another host on the network. Once a connection is established, higher-level protocols are used to do the required services. Each protocol is realized through a concept called port. A port is identified by a number that will automatically follow a predefined protocol. For example, port no. 21 is for FTP(File Transfer Protocol), 23 is for Telnet, 80 is for HTTP and so on. G Port numbers are logical numbers that identify a particular protocol. For the client-server system, the socket used for a server is handled by the class ServerSocket and that for client is handled by the class Socket. 20.2.1 ServerSocket(TCP/IP) This class deals with the server sockets. A server socket keeps waiting for request calls from the network. When a request is received, it does some operation appropriate to the request and returns a reply to the caller. The request is processed by methods defined in SocketImp1 class. The connection established is a connection–oriented and governed by TCP. It is a reliable service. Constructors The constructors used to create server socket are given below. All of them throw IOException. Networking 587 ServerSocket(int port) Creates a server socket on a specified port; a port of 0 creates a socket on any free port. The maximum queue length for incoming connection is set to 50. ServerSocket(int port, int q) Creates a server socket on the specified port; the maximum queue length is set to q. ServerSocket(int port, int q, InetAddress address) Creates a server socket on the specified port with a maximum queue length of q; in a multi-homed host, address specifies the IP address to which the socket binds. Methods Some of the methods defined in the ServerSocket are : InetAddress getInetAddress() Returns the local address of this server socket int getLocalPort() Returns the port number on which this socket is listening Socket accept() Listens for a connection to be made to this socket and accepts it; socket is created. It throws an IOException. a new void close() Closes this socket; throws IOException if an I/O error occurs when closing the socket void setSoTimeout(int timeout) Enables/disables SO_TIMEOUT with the specified timeout in milliseconds; with a non-zero timeout, a call to accept() for this ServerSocket will block for only this much amount of time. After the expiry of the timeout, InterruptedIOException is thrown out. This method will also throw SocketException. int getSoTimeout() Returns the SO_TIMEOUT; a 0 value implies that the option is disabled. 20.2.2 Client Socket(TCP/IP) The client socket is implemented in the class Socket. A socket is an end point for communication between two host machines. A client socket establishes a connection with the server socket. The connection is a reliable, connection- 588 Programming in JAVA2 oriented TCP/IP connection. Once a connection is established, methods defined in SocketImpl class are used to carry out the desired task. Constructors Some of the constructors used to create client sockets are given below: Socket(String host, int port) Creates a stream socket and connects it to the specified port number on the specified host; throws an UnknownHostException and IOException Socket(InetAddress address, int port) Creates a stream socket and connects it to the specified port number at the specified IP address; throws an IOException Socket(InetAddress address, int port, InetAddress localadrs, int localport) Creates a socket and connects it to the specified remote address and remote port; the socket binds to the local address and the specified local port. Throws an IOException Methods Some of the methods defined in class Socket are given below. used to manage socket-related operations. They are InetAddress getInetAddress() Returns the remote IP address to which this socket is connected InetAddress getLocalAddress() Returns the local address to which the socket is connected int getPort() Returns the remote port number to which this socket is connected int getLocalPort() Returns the local port number to which this socket is connected InputSream getInputStream() Returns an input stream for reading bytes from this socket; IOException throws an OutputStream getOutputStream() Returns an output stream for writing bytes to this socket; throws an IOException void close() Closes this socket; throws an IOException. Networking 589 20.2.3 Server Sending Message to Client In the following program 20.2, a server socket is created in the local host (with IP address 127.0.0.1) with port number 95. The accept() method keeps listening for a client request. Once a client socket makes a request, it accepts and this process creates a socket in the server side. A connection is established with the client. After that, whatever is typed in the server side is communicated to the client socket. The program 20.3 illustrates a client socket. A client socket is created, connecting to the local host at port 95 acting as server. Once the client socket is connected to the server socket, a communication channel is created. The client side creates an input stream (output of server) and prints out whatever is available at the input. Both programs jointly create a one-way communication from server side to client side. Program 20.2 // This program creates a server socket. // somasundaramk@yahoo.com import java.net.*; import java.io.*; class Servrsoc { public static void main(String args []) throws IOException { ServerSocket ss = null; try { ss = new ServerSocket(95); } catch (IOException ioe) { System.out.println("Error in finding the port 95"); System.exit(1); } Socket ssoc = null; ssoc = ss.accept(); System.out.println("Connection accepted at :" + ssoc); DataOutputStream out = new DataOutputStream(ssoc.getOutputStream()); BufferedReader inp = new BufferedReader(new InputStreamReader(ssoc.getInputStream())); String si, clstr; BufferedReader kybd = new BufferedReader(new InputStreamReader(System.in)); 590 Programming in JAVA2 System.out.println("Ready to send message to client\nType exit to end the sesson"); // read text from keyboard while (!(si = kybd.readLine()).equals("exit")) { int ln = si.length(); for (int i = 0; i < ln; i++) // send the text char by char to the client out.write((byte)si.charAt(i)); out.write(13); out.write(10); out.flush(); } out.close(); kybd.close(); ss.close(); } } Program 20.3 // This program creates client socket. // somasundaramk@yahoo.com import java.net.*; import java.io.*; class Client { public static void main(String args []) throws IOException { Socket cls = null; BufferedReader br = null; try { cls = new Socket(InetAddress.getLocalHost(),95); br = new BufferedReader(new InputStreamReader(cls.getInputStream())); } catch (UnknownHostException uh) { System.out.println(“I dont know the host”); System.exit(0); } String inp, si; while ((inp = br.readLine()) != null) { System.out.println(inp); } Networking 591 br.close(); cls.close(); } } To execute the programs, first run the server program 20.2 in a DOS window. Then create another DOS window and run the client program 20.3. Then, whatever you type in the server side will be displayed in the client side window. The result for the above two programs executed simultaneously is given below: Fig.20.1 Output Screens for Simultaneous Execution of Programs 20.2 and 20.3 Both programs terminate when the string exit is typed on the server side. 20.2.4 Echo-Server and Client The program 20.4 is an echo server. It keeps waiting for a client to attach. It receives the message sent by the client and then retransmits the same message to the client and thus acts as an echo server. Program 20.4 // This program creates a server socket. // somasundaramk@yahoo.com import java.net.*; import java.io.*; class Server2 { public static void main(String args []) throws IOException 592 Programming in JAVA2 { ServerSocket ss = null; try { ss = new ServerSocket(95); } catch (IOException ioe) { System.out.println(“Error in finding the port 95”); System.exit(1); } Socket ssoc = null; try { ssoc = ss.accept(); System.out.println(“Connection accepted at :”+ssoc); } catch (IOException ioe) { System.out.println(“Server failed to accept :”); System.exit(1); } DataOutputStream out = new DataOutputStream(ssoc.getOutputStream()); BufferedReader inp = new BufferedReader(new InputStreamReader(ssoc.getInputStream())); String si; System.out.println(“Server waiting for message from the client”); boolean quit = false; // read text from the client do { String mesg = “”; si = inp.readLine(); int ln = si.length(); if (si.equals(“exit”)) quit = true; for (int i = 0; i < ln; i++) // send the text char by char to the client { mesg = mesg + si.charAt(i); out.write((byte)si.charAt(i)); } System.out.println(“From Client :” + mesg); out.write(13); out.write(10); Networking 593 out.flush(); }while (!quit); out.close(); ss.close(); } } Program 20.5 is a client. It connects to the echo server in the local host machine at port number 95. The client first accepts text typed through the keyboard and sends it to the echo server. It then receives the message back and prints out on the console. It again waits for keyboard input. This sending and receiving continues until the user type exit for which both server and client exit. Program 20.5 /*This program creates a client socket. Whatever is typed is sent to the server. The client then reads the message from the server and prints the message. somasundaramk@yahoo.com */ import java.net.*; import java.io.*; class Client2 { public static void main(String args []) throws IOException { Socket cls = null; String intext = null; BufferedReader input = null; DataOutputStream output = null; BufferedReader kybd = new BufferedReader(new InputStreamReader(System.in)); try { cls = new Socket(InetAddress.getLocalHost(), 95); input = new BufferedReader(new InputStreamReader(cls.getInputStream())); output = new DataOutputStream(cls.getOutputStream()); } catch (UnknownHostException uh) { System.out.println(“Unknown host”); System.exit(0); } System.out.println(“To start the dialog type the messages in this client window\nType exit to end”); 594 Programming in JAVA2 boolean more = true; while (more) { //read message from the keyboard intext = kybd.readLine(); //send message to server output.writeBytes(intext); output.write(13); output.write(10); output.flush(); // receive message from server String inp, si; inp = input.readLine(); System.out.println(“From server : “ + inp); if (inp.equals(“exit”)) break; } input.close(); output.close(); cls.close(); } } First execute the echo server, program 20.4, in DOS window. Then execute the client program 20.5 in another DOS window. The dialog begins only from the client side. A sample output for executing both programs simultaneously is given in fig.20.2. Fig. 20.2 Output Screens for Echo-Server (Program 20.4) and Client (Program 20.5) Networking 595 20.3 Datagram The mechanism seen in section 20.2 deals with exchange of message using connection–oriented TCP/IP protocol. Another way of sending and receiving message is by using datagrams. Datagrams are fire-and-forget type of message packets. They make use of connectionless UDP(User Datagram Protocol). The preparation of datagram packets are handled in DatagramPacket class and the delivery mechanism is handled by DatagramSocket class. 20.3.1 DatagramPacket A message to be transmitted is broken into small message packets of a certain length. The IP address of the destination is also packed into it. The preparation of datagram packets are handled in the Datagrampacket class. Constructors Constructors in DatagramPacket are: DatagramPacket(byte[] buf, int offset, int length) Constructs a datagram packet for receiving packets of byte length length, into the buffer buf starting at offeset in the array DatagramPacket(byte[] buf, int length) Constructs a datagram packet for receiving packets of byte length of length DatagramPacket(byte[] buff, int offset, int length, InetAddress address, int port) Constructs a datagram packet for sending packets of length, length with offset at offset, to the specified port on the specified host of address address DatagramPacket(byte[] buff, int length, InetAddress address, int port) Constructs a datagram packet for sending packets of length, length to the specified port number on the specified host of address, address Methods Some of the methods defined in the DatagramPacket are: InetAddress getAddress() Returns the IP address of the machine to which this datagram is being sent or from which the datagram is received int getPort() Returns the port number on the remote host to which this datagram is being sent or from which the datagram is received 596 Programming in JAVA2 byte[] getData() Returns the data bytes received or the data bytes to be sent int getLength() Returns the length of the data to be sent or the length of the data received void setAddress(InetAddress address) Sets the IP address for this packet void setPort(int port) Sets the port number for this packet void setData(byte[] buf) Sets the data buffer for this packet void setLength(int length) Sets the length in bytes for this packet 20.3.2 DatagramSocket Datagram packets are transmitted or received through datagram socket. The DatagramSocket class implements server and client sockets using connectionless protocol UDP. The datagram packets may follow different routes to reach the destination. Multiple packets sent from a source may reach the destination in any order. Constructors Constructors in this class are: DatagramSocket() Constructs a datagram socket and binds it to any available port on the local host machine; throws SocketException DatagramSocket(int port) Constructs a datagram socket and binds it to the specified port on the local host machine; throws SocketException DatagramSocket(int port, InetAddress ladrs) Creates a datagram socket and binds it to the specified local address and port Methods Some of the methods defined in this class for handling datagram socket are: Networking 597 void connect(InetAddress adrs, int port) Connects the socket to a remote address and remote port; when a socket is connected to a remote address, packets may only be sent to or received from that address. void disconnect() Disconnects the socket InetAddress getInetAddress() Returns the address to which this socket is connected int getPort() Returns the port number to which this socket is connected void send(DatagramPacket p) Sends a datagram packet from this socket; throws an IOException void receive(DatagramPacket p) Receives a datagram packet from this socket; when this method returns, the DatagramPacket’s buffer is filled with the data received. Throws an IOException InetAddress getLocalAddress() Returns the local address to which the socket is bound int getLocalPort() Returns the port number on the local host to which this socket is bound void close() Closes this socket 20.3.3 UDP Server-Client Conversation UDP Server Program 20.6 is a UDP-based server. It waits for the receipt of a UDP message packet. When it receives a message, it displays the message and waits for a keyboard input. The text typed is packed in a datagram and sent to a client in the local host with port number 3456. This process of receiving and sending continues until the message sent or received is “exit”. Program 20.6 /* This program creates a datagram socket. It makes use of DatagramPacket and DatagramSocket classes and the methods defined in them. This program acts like a server. It recevies message packets from another client . The text typed in the keyboard is 598 Programming in JAVA2 sent as a reply datagram to client. somasundaramk@yahoo.com */ import java.net.*; import java.io.*; class Dserver { public static void main(String args []) throws IOException { BufferedReader kybd = new BufferedReader(new InputStreamReader(System.in)); InetAddress localadrs = InetAddress.getLocalHost(); InetAddress remoteadrs = null; DatagramSocket dsocket = new DatagramSocket(3456); int buffersize = 2000; int remoteport; DatagramPacket outgram; System.out.println(“Type replies.\nType exit to quit\n”); boolean more = true; while (more) { byte [] inbuffer = new byte[buffersize]; DatagramPacket ingram = new DatagramPacket(inbuffer, buffersize); byte [] outbuffer = new byte[buffersize]; dsocket.receive(ingram); remoteadrs = ingram.getAddress(); remoteport = ingram.getPort(); String data = new String(ingram.getData()); data = data.trim(); if (data.equals(“exit”)) break; System.out.println(“From client : “ + data); String reply = kybd.readLine(); outbuffer = reply.getBytes(); outgram = new DatagramPacket(outbuffer, outbuffer.length, remoteadrs, remoteport); dsocket.send(outgram); if (reply.equals(“exit”)) break; } dsocket.close(); } } Networking 599 UDP Client Program 20.7 is a UDP-based client. A socket with port number 3457 is created. It waits for the keyboard input. When a user types in a line of text, a UDP packet is prepared. The packet is then sent to the local host with port number 3456. It then waits for the arrival of a packet. When a packet arrives, the data in the packet is extracted and displayed on the monitor. This process of sending and receiving the message continues until the user types the word exit for which both the client and the server terminate. Program 20.7 /* This program creates a datagram socket. It makes use of DatagramPacket and DatagramSocket classes and the methods defined in them. This program acts like a client. It sends message packets to another server . The reply received is printed out. somasundaramk@yahoo.com */ import java.net.*; import java.io.*; class Dclient { public static void main(String args []) throws IOException { BufferedReader kybd = new BufferedReader(new InputStreamReader(System.in)); InetAddress localadrs = InetAddress.getLocalHost(); InetAddress remoteadrs = localadrs; DatagramSocket dsocket = new DatagramSocket(3457); int buffersize = 2000; byte [] outbuffer = new byte[buffersize]; DatagramPacket outgram; System.out.println(“Start the dialog from this client”); boolean more = true; while (more) { byte [] inbuffer = new byte[buffersize]; DatagramPacket ingram = new DatagramPacket(inbuffer, buffersize); String send = kybd.readLine(); outbuffer = send.getBytes(); outgram = new DatagramPacket(outbuffer, outbuffer.length, remoteadrs, 3456); dsocket.send(outgram); 600 Programming in JAVA2 if ((send.trim()).equals(“exit”)) break; dsocket.receive(ingram); String data = new String(ingram.getData()); data = data.trim(); System.out.println(“From server : “ + data); if (data.equals(“exit”)) break; } dsocket.close(); } } Execute both server program 20.6 and client program 20.7 simultaneously, each on a separate DOS window. Figure 20.3 shows a sample output for executing the server and the client. Fig.20.3 Sample Output for UDP-Based Server-Client Conversation (Programs 20.6 and 20.7) 20.4 URL URL stands for Uniform Resource Locator. URL unifies many higher-level protocols and file formats into a single form called web or World Wide Web. Such a web is uniquely identified by an address specified by URL. All web browsers use URL to identify resources in the internet. Examples for URL are : http://www.sun.java.com/ http://www.ruraluniv.org/ http://www.sun.java.com : 80/index.htm Networking 601 The URL format consists of four parts. The first part indicates the protocol to be used. In the above examples http is the protocol. The protocol is delimited by the colon(:). The second part is the domain name enclosed between // and /, as in the first two examples. The third part is the port number, which by default is 80 for http and is optional. Therefore the first and the third examples have the same port number 80. The fourth part is the file name which appears after /. 20.4.1 URL Class This class is used to create URL objects and has methods to process URL. Constructors Some of the commonly used constructors to create URL objects are : URL(String spec) Creates a URL object MalformedURLException from the string specification spec; throws URL(URL context, String spec) Creates a URL by parsing the specification spec within a specified context; if the context is not null and the spec argument is a partial URL specification, any of the string’s missing components are inherited from the context argument. Throws MalformedURLException Methods Some of the methods defined in the URL class are: int getPort() Returns port number of this URL; returns -1 if the port is not set String getProtocol() Returns the protocol name of this URL String getHost() Returns the host name of this URL, if applicable; is an empty string. for “file” protocol, this String getFile() Returns the file name of this URL URLConnection openConnection() Returns a URLConnection object that represents a connection to the remote object referred to by the URL; throws an IOException 602 Programming in JAVA2 final InputStream openStream() Opens a connection to this URL and returns an InputStream for reading from that connection; this method represents a short-hand method for openConnection.getInputstream(). Throws an IOException final Object getContent() Returns the contents of this URL; this is openConnection.getContent(). Throws an IOException equivalent to The following program 20.8 illustrates the creation of a URL and the use of some of the methods defined in URL class. The URL of www.ruraluniv.org is created. The openStream() method creates an input stream. Using that input stream, the contents of the index.html file of this URL is read character by character and printed out. Program 20.8 /* This program illustrates the creation of URL. The use of a few methods in URL is given. An input stream is opened and the contents of a file are read from the specified URL. somasundaramk@yahoo.com */ import java.net.*; import java.io.*; class URLuse { public static void main(String args []) { // The following is the website of Gandhigram // Rural University String gri = “http://www.ruraluniv.ac.in/index.html”; URL myurl = null; InputStream inps; try { myurl = new URL(gri); String proto = myurl.getProtocol(); int griport = myurl.getPort(); System.out.println(“URL used : “ + myurl.toString()); System.out.println(“Protocol :” + proto); System.out.println(“Port used: “ + griport); System.out.println(“File name: “ + myurl.getFile()); Networking 603 Object obj = myurl.getContent(); System.out.println(“Content :” + obj.toString()); // reads the index.html file and prints char // by char inps = myurl.openStream(); System.out.println(“\nContent of index.html file\n”); int c; while ((c = inps.read()) != -1) System.out.print((char)c); inps.close(); } catch (MalformedURLException me) { System.out.println(“URL cannot be created”); } catch (IOException ioe) { System.out.println(“IO Problem”); } } } 20.4.2 URLConnection This is an abstract class. This class is a superclass of all classes that represents an HTTP connection between an application and a web object represented by URL. Objects of this class can be used to read from and write to the URL resource. Methods in this can be used to study about the URL. Constructor The constructor in this class is : URLConnection(URL url) Constructs a URL connection to the specified URL; to the object referenced by the URL is not created. however, connection Methods Some of the methods defined in this class are : abstract void connect() Opens a communication link to this URL; throws an IOException URL getURL() Returns the value of this URLConnection’s URL field 604 Programming in JAVA2 int getContentLength() Returns the content length of the resource that this connection represents or -1 if the content length is not known String getContentType() Returns the content type of the resource that the URL represent or null if not known long getDate() Returns the sending date of the resource that the URL references; value returned is in milliseconds since January 1970. the long getLastModified() Returns the date of the resource that this connection represents was last modified or 0 if not known Object getContent() Retrieves the contents of this URL connection; throws an IOException InputStream getInputStream() Returns an input stream that reads from this connection; IOException throws an OutputStream getOutputStream() Returns an output stream that writes to this connection; IOException throws an After reading this chapter, you should have learned the following: Ü Obtianing IP address of URLs Ü Socket programming for server Ü Socket programming for clients Ü Sending and receiving UDP-based datagrams Ü Accessing URLs and their contents In the next chapter, you will learn how to access databases through Java clients. Networking 605 Exercise-20 I. Fill in the blanks 20.1 IP stands for ________ . 20.2 IP address is a sequence of _____ numbers seperated by a dot. 20.3 Every IP address is associated with a name called _________ . 20.4 DNS is an acronym for ---------------- . 20.5 TCP is a __________ oriented service. 20.6 UDP is a __________ service. 20.7 The very important aspect of a server socket is that it _________ for a request from a client. 20.8 ________ is a number that indicates the protocol to be followed during a transaction. 20.9 Sockets are _______ points of communication. 20.10 The preparation of a datagram is dealt by __________ class. 20.11 URL is an acronym for ____________ . 20.12 The first part of an URL indicates the __________ to be used. II. Write programs for the following problems: 20.13 Write a program to find all the IP addresses and port numbers of the following domain names: sify.com hotmail.com 20.14 Write a server and a client (TCP/IP) program such that message typed in server is displayed on a client and vice versa. 20.15 Write a program using UDP so as to transfer a text file from one host to another. 20.16 Write a program to download the following file: http:://www.java.sun.com/downloads/index.html * * * * * * 606 Programming in JAVA2 BLANK 607 Chapter 21 JDBC In this chapter, programming concepts in Java to handle databases are explained. How to update, modify and execute SQL queries to a database are also discussed. 21.1 JDBC and ODBC The term JDBC is taken as an acronym for Java Database Connectivity, while Java developers state that it is not so. For a reader, JDBC may be taken to represent Java Database Connectivity. The Java Application Program Interface (API) makes a connection between Java application or applet and a database management system (DBMS or RDBMS). A DBMS has its own structure to organize its data. There are different types of DBMS developed by different vendors. Each DBMS has its own distinct structure. Any application written to access a DBMS of one vendor cannot be used to access the DBMS of another vendor. To solve this problem, Microsoft developed a standard called Open Database Connectivity (ODBC), which is free from any vendor-specific DBMS structure. A client using ODBC API can send SQL requests to a database server and get the results. A JDBC client does not make a direct link to a DBMS server. A JDBC makes use of ODBC to connect to DBMS servers. The bridge between a Java program and a database is a JDBC-ODBC driver. A conceptual structure of using a Java API in a client to handle a database in a server is shown in fig.21.1. 608 Programming in JAVA2 Client Fig.21.1 < > JDBC Driver < SQL Request SQL Result > Database Server A Driver That Acts As An Interface Between a Client and Database Server All DBMS or RDBMS need a driver if they are to be accessed from outside their own system. For example, a Java-Oracle driver is needed if Oracle database is to be accessed by a client running a Java application. Java has different types of drivers to access a DBMS. 21.1.1 Types of Drivers The drivers supporting Java language are classified into four types. They are classified based on the technique used to access a DBMS. All the models are supposed to work in a network. The same concept is applicable to a database available in a local machine also. Type I : JDBC-ODBC Bridge Driver Type II : Native-API-Partly-Java Driver Type III : JDBC-Net-All-Java Driver Type IV : Native-Protocol-All-Java Driver Type I : JDBC-ODBC Bridge Driver In this type, a JDBC-ODBC bridge acts as an interface between a client and a database server. An application in a client makes use of the JAVA API to send the requests to a database to the JDBC-ODBC bridge. The JDBCODBC bridge converts the JDBC API to ODBC API and sends it to the database server. The reply obtained from the database server is sent to the client via JDBC-ODBC driver. In this type, the JDBC-ODBC driver has to be installed in the client side. The Type I driver configuration is shown in fig.21.2. JDBC Client 609 Server Client ¯ - JDBC Driver - ¯ Database Server ODBC Driver ¯ Network Interface ¯ Network Interface < - ¯ Network ¯ > Fig.21.2 Type I : The JDBC-ODBC Bridge Driver This driver is available in JDK 1.2. Type II : Native-API-Partly-Java Driver In this type of driver, the JDBC requests are translated to the Call Level Interface(CLI) of the database installed in the client machine to communicate with a database. When the database receives the requests, they are processed and sent back. This result in the native format of the database is converted to JDBC format and presented to the application running in a client. This type of driver offers a faster response than Type I drivers. The configuration of a Type II driver is shown in fig.21.3. Client Server Application ¯ - JDBC Driver ¯ - Native Database Libraries (CLI) ¯ Network Interface < ¯ - Database Server ¯ Network Interface Network - ¯ Fig.21.3 Type II : Native-API-Partly-Java Driver > 610 Programming in JAVA2 Type III : JDBC-NET-ALL-Java Driver It is similar to Type II driver. and Native Database Libraries Communication between the client driver network protocol as shown in The only difference is that JDBC for server (CLI) is stored in the remote server. and the server takes place using a JDBC fig.21.4. Server Client Database Server Application Native Database Libraries(CLI) ¯ - - JDBC Driver Client Side ¯ Network Interface Network Interface JDBC Driver Network Protocol - ¯ ¯ JDBC Driver Server Side - ¯ < ¯ ¯ > Fig.21.4 Type III : JDBC-Net-All-Java Driver The advantage of this driver is that the client need not access any local disk to get the CLI. Hence, an applet can be used to access a database over a network. Type IV : Native-Protocol-All-Java Driver This type of a driver is 100% Java and does not make use of any CLI native libraries. In this type, no translation takes place. A JDBC makes a call directly to the database. It makes use of its own DB Protocol written in Java for network communication (fig.21.5). Client Server Application ¯ - Database Server JDBC Driver - ¯ Network Interface < ¯ Request - Reply - ¯ Network Interface - Request ¯ Reply DB Protocol in Java Fig.21.5 Type IV : Native-Protocol-All-Java Driver > JDBC G 611 A java program needs a link called driver which can understand the JDBC requests and translate them to a format that can be understood by a database and vice versa. 21.1.2 Java SQL Package The classes required to handle a database are contained in a package java.sql. This package contains the following classes: Date DriverManager DriverPropertyInfo SQLPermission Time TimeStamp Types This package contains the following interfaces: Array CallableStatement Connection Driver PreparedStatement ResultSet Savepoint SQLInput Statement Blob Clob DatabaseMetaData ParameterMetaData Ref ResultSetMetaData SQLData SQLOutput Struct We will see the use and methods defined in some of them in the following sections. 21.2 Using a JDBC To use the JDBC in a Java language application or applet, the following steps are to be followed. They are: 1. 2. 3. 4. 5. 6. 7. Import the java.sql package. Load the driver. Establish a connection to the database. Create a statement. Execute the statement. Retrieve the results. Close the connection and statement. 612 Programming in JAVA2 Step 1 : Import sql package. The first step of importing java.sql is the routine procedure. import.java.sql.*; Step 2 : Load the driver. Loading of the driver is done using the following method: Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); The driver specified is available in the JDK1.2. Step 3 : Establish connection. Connection is established with the database using the following method defined in the DriverManager class: Connection connect = DriverManager.getConnection(“jdbc:odbc: database”) where, “jdbc:odbc:database” is the database URL Object specifying the protocol, subprotocol and the database name. Step 4 : Prepare statement. In this step, statement object that is required to send a query to the database is prepared. This statement is prepared using the following method defined in Connection interface: Statement stmnt = conect.createStatement(); Step 5 : Execute query The SQL query that is to be sent to the database is executed by calling the following method on statement object, which returns a ResultSet object: ResultSet reset = stmnt.executeQuery(“select * from database”); Step 6 : Retrieve the result. The results returned by the database to the query executed are extracted from ResultSet using the get method defined in ResultSet interface. while(reset.next()) System.out.println(“Name : “ + reset.getString(“name”); Step 7 : Close the statement and connection. Using the close method, the Statement and Connection are closed : conect.close(); stmnt.close(); The following program 21.1 illustrates the steps explained above. program retrieves an MS-Access database stored in a table “studata”. This JDBC 613 Program 21.1 /* This program demonstrates the creation of JDBC-ODBC connection and shows how to read a database created in MS-Access. somasundaramk@yahoo.com */ import java.sql.*; public class Sqlcon { public static void main(String args []) { Statement stm; ResultSet reset; try { // load the driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //establish connection Connection conect = DriverManager.getConnection(“jdbc: odbc:stud_base”); // create statment stm = conect.createStatement(); // execute the query and get the result reset = stm.executeQuery(“select * from studata “); System.out.println(“Name “ + “ \t” + “R.No” + “ \t” + “C.Org” + “\t” + “Java” + “ \t” + “Multimedia\n”); // retrieve the results while (reset.next()) System.out.println(reset.getString( “name”) + “\t” + reset.getInt(“rgno”) + “\t” + reset.getInt(“comporg”) + “\t” + reset.getInt(4) + “\t” + reset.getInt(5)); stm.close(); conect.close(); } catch (SQLException sqe) { System.out.println(“Sql error”); } catch (ClassNotFoundException cnf) 614 Programming in JAVA2 { System.out.println(“Class Not found error “); } } } The above program gives the following output: Name R.No Somasundaram K 1001 Magesh S 1002 Gomathi S 1003 Kumar S P 1004 C.Org Java Multimedia 65 85 93 90 60 95 97 95 55 75 88 85 21.3 DriverManager - Creating Connection The DriverManager class contains methods to manage the JDBC drivers loaded in your program. The JDBC drivers are loaded using the forName() method. This class has no constructor, but has only static methods. Some of the methods defined in this class are: static Connection getConnection(String url) Creates a connection to the specified SQLException database URL; throws static Connection getConnection(String url, Properties prop) Creates a connection to the specified database URL using the properties specified; throws SQLException static Connection getConnection(String url, String user, String pswd) Creates a connection to the specified database URL using the user name and password; throws SQLException static Driver getDriver(String url) Selects a driver from the specified database url; throws SQLException The Connection objects are used to prepare statement objects, which are presented in the next section 2.4. JDBC URLs In the above methods, the url specified refers to database URLs. database URLs have three components. They are : 1. ProtocolName 2. Sub-protocol 3. Subname The JDBC 615 The syntax of JDBC URL is <protocol> : <subprotocol> : subname Protocol Name The protocol name specifies the protocol to access the database. It should be jdbc. Therefore all JDBC URLs have the form: jdbc : <Sub-protocol> : <subname> Sub-protocol The sub-protocol is used to specify the type of database source, like Oracle, Sybase, etc. With the sub-protocol a JDBC URL may look like: jdbc : Oracle : < subname> Subname The subname specifies the database server. This name depends on the sub-protocol used. Each RDBMS has its own way of locating the source. The subname may be network host name, database listener port number/name or database instance name. 21.4 Connection Interface - Creating Statements The java.sql package contains an interface Connection. A Connection object represents an SQL session with database. This interface contains methods which can be used to prepare statements. These statements by themselves cannot be used, but provide a via medium to send SQL statements to the database. It also has methods to make the changes in the database permanent or roll back to a state before the last change. The important and very often used methods are those that prepare different statements. There are basically three types of statements. They are : Statement PreparedStatement CallableStatement Statement A Statement is used to execute static SQL statements. There are no IN or OUT parameters. When an SQL statement is executed, only one result is returned. PreparedStatement A PreparedStatement object is used to execute dynamic SQL statements with IN parameter. A PreparedStatement is compiled once by the database. 616 Programming in JAVA2 When SQL statements, which are large in size or are used repeatedly, a PreparedStatement can be used, which makes the process faster. CallableStatement A CallableStatement object is used for executing a stored procedure that can be used in an application. A CallableStatement contains an OUT parameter. It can also include IN parameter. The Connection interface has several concrete methods. Some of them are: void close() Releases the Connection object’s database and JDBC resources void commit() Makes all the changes made since the last commit or rollback permanent; throws SQLException Statement createStatement() Creates a Statement object for sending SQL statement to the database; throws SQLException boolean isClosed() Checks whether the connection is closed CallableStatement prepareCall(String sql) Creates a CallableStatement object for calling stored procedure; throws SQLException PreparedStatement prepareStatement(String sql) Creates a PreparedStatement object for sending SQL statement with or without IN parameter; throws SQLException void rollback() Undoes all changes made in the current transaction G Only by using methods in interface, Statement, PreparedStatement and CallableStatement objects are created. 21.5 Statement Interface - Executing Statements In the previous section, we have seen how to create different types of statements, Statement, PreparedStatement and CallableStatement. In this section, we will see how the Statement object created is used for executing static SQL statements. Statement is the simplest one to execute an SQL JDBC 617 statement. The Statement interface has several concrete methods to execute SQL statements. Some of the methods defined in this interface are : void close() Releases the Statement object’s database and JDBC resources boolean execute(String sql) Executes the specified sql statement; the result obtained is to be retrieved using getResultSet() method ResultSet executeQuery(String sql) Executes the given sql statement and returns one ResultSet int executeUpdate(String sql) Executes the specified sql, which may be INSERT, DELETE or UPDATE int getMaxRows() Returns the maximum number of rows that the result set contains ResultSet getResultSet() Retrieves the ResultSet generated by the execute() method So far, we have seen how to create Connection object using DriverManager and Statement objects from Connection interface. In this section, we have seen how to execute Statement objects using methods defined in Statement interface. Now, we will give an example to illustrate the above concepts and to demonstrate some methods defined in Statement interface. The program 21.2 is almost the same as program 21.1, but with different methods to execute the SQL statement. In this program 21.2, we make use of a database created in MS-Access and stored in the table “studata”. It contains 5 fields, name, rgno, comporg, java and multimedia. There are four records (4 rows) in this database. We make the JDBC URL using this MS-Access database. For this, a database source is to be created. This is done using the following steps: 1. Go to Control Panel 2. Click Administrative Tools (Windows 2000) 618 Programming in JAVA2 Fig.21.6 Control Panel with Administrative Tool 3. Then Click Datasources (ODBC) Fig.21.7 DataSource (ODBC) 4. Then You Will Get a Dialog Box Shown Below. Select Add Button. JDBC Fig.21.8 5. ODBC Dialog Box From the Displayed Drivers Select Microsoft Access Driver (*.mdb) and press Finish. Fig.21.9 Creating a New Data Source 619 620 6. Programming in JAVA2 An ODBC Microsoft Access Setup Dialog Appears. In the Data Source Name, type a name of your choice (stu_base). A description can also be given. Then click select. Fig.21.10 Assign a Data Source Name 7. A Select Database Dialog Box Appears To Select the Physical Database. The table studata is stored in db3.mdb, in My Documents directory. Select db3 and press OK for all the remaining dialogs. Fig.21.11 Select the Physical Database To check whether the required jdbc data source has been created, go to the step 4, where the ODBC Data Source Administrator appears. The name “stu_base” is to be in the list. JDBC 621 Program 21.2 /* This program illustrates the use of the methods execute(String sql)and getResultSet() methods defined in the interface Connection. somasundaramk@yahoo.com */ import java.sql.*; public class Conect1 { public static void main(String args []) { Statement stm; ResultSet reset; try { // load the driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //establish connection Connection conect = DriverManager.getConnection(“jdbc: odbc:stu_base”); // create statment stm = conect.createStatement(); // execute the query and get the result stm.execute(“select * from studata “); // Retrieve the results reset = stm.getResultSet(); System.out.println(“Name“ + “ \t” + “R.No” + “ \t” + “C.Org” + “\t” + “Java” + “ \t” + “Multimedia\n”); // print the results while (reset.next()) System.out.println( reset.getString(“name”) + “\t” + reset.getInt(“rgno”) + “\t” + reset.getInt(“comporg”) + “\t” + reset.getInt(4) + “\t” + reset.getInt(5)); //close the statement and connection stm.close(); conect.close(); } 622 Programming in JAVA2 catch (SQLException sqe) { System.out.println(“Sql error”); } catch (ClassNotFoundException cnf) { System.out.println(“Class Not found error “); } } } The above program gives the following output: Name R.No Somasundaram K 1001 Magesh S 1002 Gomathi S 1003 Kumar S P 1004 C.Org Java Multimedia 65 85 93 90 60 95 97 95 55 75 88 85 In the program 21.2, the driver is loaded using the forName() method. The driver sun.jdbc.odbc.JdbcOdbcDriver is available in the JDK1.2. To use other drivers, appropriate drivers are to be installed in the system. A Connection object is created by calling getConnection() method by passing the JDBC URL jdbc:odbc:stu_base. The string “Select * from studata” is the SQL statement, which selects all the records in studata table. A Statement object is created by calling the createStatement() on Connection object. The SQL statement is executed by calling execute() method on Statement object stm. This result created is retrieved using the getResultSet() method. This method returns a ResultSet object. The ResultSet may contain one or more rows of results. To get one row after another, the next() method is called. After obtaining a record(one row), the individual fields are then obtained using getString(“fieldname”) or getString(Column) method, which are defined in ResultSet interface. Comparing program 21.2 with program 21.1, you will notice that to execute a Statement, the execute() method is used in program 21.2. To get the result of the SQL statement, getResultSet() method is used. However, in program 21.1, the executeQuery() method, which is equivalent to the above two methods, is being used. In practice, executeQuery() method is more convenient to use than using the two methods. We now give an example in program 21.3 using executeUpdate() method. This program creates an MS-Access table named “pricelist”, containing JDBC 623 two fields “item” of 20 char width and “price” of type Number. Three records are then inserted into it. The whole table is selected and printed out. The SQL statement used to insert each record is of the form : INSERT INTO pricelist (item, price) VALUES(‘NeemSoap’, 12.50) The string or char type values are placed in single quote. Program 21.3 /* This program illustrates the use of executeUpdate(String sql)method to create a new table named pricelist and inserts 3 records. The table is then printed out. somasundaramk@yahoo.com */ import java.sql.*; public class Insert { public static void main(String args []) { Statement stm; ResultSet reset; String sql, record1, record2, record3; try { // load the driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //establish connection Connection conect =DriverManager.getConnection (“jdbc:odbc:stu_base”); // prepare the SQL statement to create table // named pricelist stm = conect.createStatement(); sql = “create table pricelist (item char(20), price number)”; // execute the table creation sql stm.executeUpdate(sql); // create SQL statement for inserting records record1 = “insert into pricelist(item, price) values(‘Sandal soap’ , 18.75 )”; record2 = “insert into pricelist (item, price) values(‘Neem soap’ , 12.50 )”; record3 = “insert into pricelist (item, price) values(‘Baby soap’ , 20.00 )”; stm.executeUpdate(record1); stm.executeUpdate(record2); 624 Programming in JAVA2 stm.executeUpdate(record3); // make the changes permanent conect.commit(); // prepare SQL to select all records in // pricelist table String select = “select * from pricelist”; reset = stm.executeQuery(select); System.out.println(“Item “ + “ \t\t” + “Price\n”); // print the table while (reset.next()) System.out.println(reset.getString(“item”) + “\t” + reset.getDouble(“price”)); //close the statement and connection stm.close(); conect.close(); } catch (SQLException sqe) { System.out.println(“Sql error”); } catch (ClassNotFoundException cnf) { System.out.println(“Class Not found error “); } } } The above program gives the following output: Item Price Sandal soap Neem soap Baby soap 18.75 12.5 20.0 In the following program 21.4, we show how to use the SQL statement, which links two tables of MS-Access and extracts the required fields from them. The two tables used are “studata” with fields, name, rgno, comporg, java, multimedia and “pricelist” with fields, item and price. The SQL statement used is: JDBC 625 SELECT name, item FROM studata, pricelist WHERE rgno = 1002 AND item = ‘Sandal Soap’ The executeQuery method is used to execute the SQL statement. The commit() method makes the insertions made permanent. rollback() when called after this is of no use unless new transactions are made. Program 21.4 /* This program illustrates how to link two tables and extract data from them which satisfy a given condition. somasundaramk@yahoo.com */ import java.sql.*; public class Select { public static void main(String args []) { Statement stm; ResultSet reset; String sql; try { // load the driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //establish connection Connection conect =DriverManager.getConnection (“jdbc:odbc:stu_base”); // prepare the SQL statement to select name // and item stm = conect.createStatement(); sql = “select name,item from studata, pricelist where rgno =1002 AND item = ‘Sandal soap’ “; reset = stm.executeQuery(sql); System.out.println(“Name “ + “ \t” + “Soap Used\n”); // print the result while (reset.next()) System.out.println(reset.getString(“name”) + “\t” + reset.getString(“item”)); 626 Programming in JAVA2 //close the statement and connection stm.close(); conect.close(); } catch (SQLException sqe) { System.out.println(“Sql error”); } catch (ClassNotFoundException cnf) { System.out.println(“Class Not found error “); } } } The above program gives the following output: G Name Soap Used Magesh S Sandal Soap In Statement interface, the SQL statements are executed by passing the SQL statements as arguments to execute(), executeQuery() and executeUpdate() methods. The executeQuery() method returns the results of the query in ResultSet object. 21.6 PreparedStatement Interface A PreparedStatement object can be used to execute a dynamic SQL statement with IN parameter. A PreparedStatement can be precompiled and used repeatedly. This interface contains methods to handle PreparedStatement objects. The PreparedStatement object is created using prepareStatement() method in Connection class. Before we look into the methods, we will see how to define IN parameters in the Java SQL statements. Setting IN Parameters An IN parameter is used to execute a dynamic SQL statement. In situations, where the actual value of a parameter is to be passed to an SQL statement are different for each transaction, then such values can be specified by placing a “?” in the SQL statement. The actual value can be passed using the setXXX() method at the time of execution. The “?” in a Java SQL statement standing for an input parameter to be supplied after using setXXX() method. For example, the following statements show how an IN parameter is defined. JDBC 627 String sql = “select * from studata where rgno > ?”; PreparedStatement pstm = conect.prepareStatement(sql); pstm.setInt(1,1002); ResultSet rst = pstm.executeQuery(); In the first line an SQL statement is defined. The ? mark stands for an IN parameter. In the second line, the PreparedStatement object is created. In the third one, we define that the IN parameter is an integer, which is the first IN parameter in the PreparedStatement. The general form of setting an IN parameter is: setXXX(int index, type value); where xxx - is the value type, index - is the position of IN parameter in the SQL statement, value - is the value to be supplied in place of ? We will now see some of the methods defined in PreparedStatement interface. All the methods throw SQLException. boolean execute() Executes the SQL statement in this object; one must use getResult() method to retrieve the result ResultSet executeQuery() Executes the SQL statement in this object and returns ResultSet object int executeUpdate() Executes the SQL statement in this object; an SQL insert, update and delete statement the SQL statements must be ResultSetMetaData getMetaData() Retrieves a ResultSetMetaData object that contains information about the columns of the ResultSet object that will be returned when this object is executed void setBigDecimal(int index, BigDecimal x) Sets the parameter specified by the index to the BigDecimal value void setBlob(int index, Blob x) Sets the specified parameter to the given Blob object void setBoolean(int index, boolean x) Sets the specified parameter to the boolean value void setByte(int index, byte x) Sets the specified parameter to the byte value 628 Programming in JAVA2 void setClob(int index, Clob x) Sets the specified parameter to the Clob object void setDate(int index, Date x) Sets the specified parameter to the Date value void setDouble(int index, double x) Sets the specified parameter to the double value void setFloat(int index, float x) Sets the specified parameter to the float value void setInt(int index, int x) Sets the specified parameter to the int value void setLong(int index, long x) Sets the specified parameter to the long value void setObject(int index, Object x) Sets the specified parameter to the Object void setShort(int index short x) Sets the specified parameter to the short value void setString(int index String x) Sets the specified parameter to the String value In the following program 21.5, we show how the IN parameter is used in a PreparedStatement. The program makes use of an MS-Access table “studata”, with fields, name, rgno, comporg, java, and multimedia. The SQL statement used is: SELECT * FROM studata WHERE comporg > ? AND java > ? and is defined in the sql string as : sql = “select * from studata where comporg > ? and java > ?”; The two ? marks stand for two IN parameter values. The IN parameters are both integers which are set using the following Java statements: pstm.setInt(1, 80); pstm.setInt(2,90); The first statement sets the first IN parameter to the value 80. second statement sets the second IN parameter to the value 90. The The JDBC 629 executeQuery() method executes the PreparedStatement object. The SQL statement is passed as an argument to the method prepareStatement() itself unlike statement object where the SQL statement is passed as an argument to the executeQuery() method. Program 21.5 /* This program illustrates the use of PreparedStatement() method. somasundaramk@yahoo.com */ import java.sql.*; public class Prepare1 { public static void main(String args []) { PreparedStatement pstm; ResultSet reset; String sql; try { // load the driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //establish connection Connection conect = DriverManager.getConnection(“jdbc: odbc:stu_base”); // define the SQL statement to create a // PreparedStatement sql = “select * from studata where comporg > ? and java > ? “; // create the PreparedStatement pstm = conect.prepareStatement(sql); // set the IN parameters pstm.setInt(1, 80); pstm.setInt(2, 90); // execute the PreparedStatement and get the // results reset = pstm.executeQuery(); // print the results System.out.println(“Name “ + “ \t” + “R.No” + “ \t” + “C.Org” + “\t” + “Java” + “ \t” + “Multimedia\n”); 630 Programming in JAVA2 while (reset.next()) System.out.println( reset.getString(“name”) + “\t” + reset.getInt(“rgno”) + “\t” + reset.getInt(“comporg”) + “\t” + reset.getInt(“java”) + “\t” + reset.getInt(“multimedia”)); //close the statement and connection pstm.close(); conect.close(); } catch (SQLException sqe) { System.out.println(“Sql error”); } catch (ClassNotFoundException cnf) { System.out.println(“Class Not found error “); } } } The above program gives the following output: Name R.No C.Org Java Multimedia Gomathi S Kumar S P 1003 1004 93 90 97 95 93 93 21.7 CallableStatement Interface A CallableStatement object is used to execute SQL stored procedures defined in the RDBMS. A procedure with OUT parameter can be executed only in this CallableStatement. A CallableStatement can also contain IN parameter. An OUT parameter has to be registered prior to executing the stored procedure. An OUT parameter in the stored procedure is represented by the ?. An OUT parameter is registered using the registerOutParameter() method. This method declares the type of the OUT parameter. After the CallableStatement is executed, the OUT parameters are to be obtained using the getXXX() method. The general form of registering OUT parameters other than NUMERIC and DECIMAL is: registerOutParamet( int index, Type type) where index - is the relative position of OUT parameter in the SQL statement type - is the SQL data type of OUT parameter. JDBC 631 The following example illustrates the use of CallableStatement and registering OUT parameter. CallableStatement cstm = conect.prepareCall(EXECUTE PAY_ROLL (?, ?, ?)); There are 3 parameters. Let us say, the first two are IN parameter and the third is an OUT parameter. The IN and OUT parameters are defined in the following way: cstm.setString(1, “Raman”); cstm.setInt(2, 5000); cstm.registerOutParameter(3, Types.LONGVARCHAR); The CallableStatement is executed by calling the execute methods. ResultSet rst = cstm.executeQuery(); The registered OUT parameter can be retrieved using getxxx() method in CallableStatement interface. An example is : String outstr = cstm.getString(3); The CallableStatement interface has several methods inherited from Statement and PreparedStatement interfaces and some of its own. Some of them are : BigDecimal getBigDecimal(int index) Retrieves the OUT parameter of JDBC NUMERIC type at the specified index as BigDecimal object byte getByte(int index) Retrieves the OUT parameter of JDBC NUMERIC type at the specified index location as a byte Date getDate(int index) Retrieves the OUT parameter of JDBC DATE type at the specified index location as a Date double getDouble(int index) Retrieves the OUT parameter of type JDBC DOUBLE at the specified index location as a double float getFloat(int index) Retrieves the OUT parameter of type JDBC FLOAT at the specified index location as a float 632 Programming in JAVA2 int getInt(int index) Retrieves the OUT parameter of type JDBC INTEGER at the specified index location as an int long getLong(int index) Retrieves the OUT parameter of type JDBC LONG at the specified index location as an int String getString(int index) Retrieves the OUT parameter of type JDBC CHAR, VARCHAR or LONGVARCHAR at the specified index location as a String The following program 21.6 illustrates the use of CallableStatement: Program 21.6 /* This program illustrates the use of CallableStatement() method. somasundaramk@yahoo.com */ import java.sql.*; import java.io.*; public class ppro { public static void main(String[] args) throws Exception { int in_sregno; int ret_code ; Connection conn = null; try { Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String url=”jdbc:odbc:stu”; conn=DriverManager.getConnection(url, ”scott”,”tiger”); in_sregno = 1111; CallableStatement pstmt = conn.prepareCall(“{call pdisp(?,?,?,?)}”); pstmt.setInt(1, in_sregno); pstmt.registerOutParameter(2, Types.VARCHAR); pstmt.registerOutParameter(3, Types.INTEGER); pstmt.registerOutParameter(4, Types.INTEGER); pstmt.executeUpdate(); String o_sname = pstmt.getString(2); int o_m1 = pstmt.getInt(3); int o_m2 = pstmt.getInt(4); System.out.println(“”); System.out.println(“The output of this program is “); JDBC 633 System.out.println(“”); System.out.println(“======”+”\t” +”==== “ + “\t\t” + “=====” +”\t” +”=====”); System.out.println(“sregno”+”\t” +”name “ +”\t\t” + “mark1” +”\t” +”mark2"); System.out.println(“======”+”\t” +”==== “ + “\t\t” + “=====” +”\t” +”=====”); System.out.println(in_sregno+”\t” +o_sname +”\t” + o_m1+”\t” +o_m2); pstmt.close(); conn.close(); } catch (SQLException e) { ret_code = e.getErrorCode(); System.err.println(ret_code + e.getMessage()); conn.close(); } } } The above program gives the following output: The output of this program is ====== sregno ====== 1111 ==== name ==== Arumugam ===== ===== mark1 mark2 ===== ===== 90 80 The above program 21.6, makes a call to the following SQL program 21.7 stored in the Oracle database named “pdisp”. Program 21.7 The following SQL procedure is called in the above program 21.6: CREATE OR REPLACE PROCEDURE pdisp( in_sregno NUMBER, out_sname OUT varchar2, out_m1 OUT number, out_m2 OUT number ) is temp_sregno number; temp_sname VARCHAR2(10); temp_m1 NUMBER; temp_m2 number; 634 Programming in JAVA2 BEGIN SELECT sregno, sname,m1,m2 INTO temp_sregno, temp_sname, temp_m1, temp_m2 FROM mark WHERE sregno=in_sregno; out_sname := temp_sname; out_m1 := temp_m1; out_m2 := temp_m2; END; G CallableStatement is the only object that can execute a stored procedure with OUT parameter. A stored procedure is passed as an argument to the prepareCall() method. The executeQuery() and execucte() methods do not take any argument. 21.8 ResultSet Interface The executeQuery() and getResultSet() methods when called on Statement, PreparedStatement and Callablestatement return objects of type ResultSet. The ResultSet objects contain results after the execution of SQL statements. The ResultSet object maintains a cursor pointing to the current row of results. The next() method moves cursor to the next row of result set. The ResultSet interface has many methods to get the results from the result set. Some of them are given below: boolean absolute(int row) Moves the cursor to the specified row number in this result set void afterLast() Moves the cursor to the end of the result set just after the last row void close() Releases the object’s database void deleteRow() Deletes the current row of this result set boolean first() Moves the cursor to the first row BigDecimal getBigDecimal(int columnIndex) Retrieves the value of the specified column as BigDecimal JDBC boolean getBoolean(int columnIndex) Retrieves the value of the specified column as boolean boolean getBoolean(String columnName) Retrieves the value of the specified column name as boolean byte getByte(int columnIndex) Retrieves the value of the specified column as a byte byte getByte(String columnName) Retrieves the values of the specified column name as a byte Date getDate(int columnIndex) Retrieves the value of the specified column as a Date Date getDate(String columnName) Retrieves the value of the specified column name as a Date double getDouble(int columnIndex) Retrieves the value of the specified column as a double double getDouble(String columnName) Retrieves the value of the specified column name as a double float getFloat(int columnIndex) Retrieves the value of the specified column as a float float getFloat(String columnName) Retrieves the value of the specified column name as a float int getInt(int columnIndex) Retrieves the values of the specified column as an int int getInt(String columnName) Retrieves the values of the specified column name as an int long getLong(int columnIndex) Retrieves the values of the specified column as a long long getLong(String columnName) Retrieves the value of the specified column name as a long ResultSetMetaData getMetaData() Returns the properties of the ResultSet object int getRow() Returns the current row number 635 636 Programming in JAVA2 Statement getStatement() Returns the statement object which produced the ResultSet String getString(int columnIndex) Retrieves the value of the specified column as a String String getString(String columnName) Retrieves the value of the specified column name as String boolean isFirst() Checks whether the cursor is in first row boolean isLast() Checks whether the cursor is in the last row boolean last() Moves the cursor to the last row boolean next() Moves the cursor to the next row boolean previous() Moves the cursor to the previous row After reading this chapter, you should have learned the following concepts: Ü JDBC-ODBC Driver Ü Creating database tables Ü Executing SQL statements using: Statement, PreparedStatement and CallableStatement. In the next chapter you will learn about Servlets used in JAVAEE5(J2EE). JDBC 637 Worked Out Problems-21 Problem 21.1w A payroll database contains two tables. One table contains the permanent details of all employees with the following fields: Name Employee code Designation Basic pay - Character Number Character Number Another table contains monthly transactions with the details: Medical allowance Transport allowance Income tax Provident fund Housing loan - Number Number Number Number Number In addition to basic pay, an employee will be paid DA and House Rent Allowance (HRA) at the following rates: DA = HRA = 53% of Basic bay 10% of basic pay The total salary of an employee is calculated as follows: Total pay = Basic pay + HRA + DA + Medical allowance + Transport allowance Deduction = Income tax + Provident fund + Housing loan Net Pay = Total pay - Deduction Write a Java program to make monthly transactions and slip for each employee and display it on the screen. prepare a pay 638 Programming in JAVA2 Program 21.1w /* This program illustrates how to make a payroll system for a company. It has two tables, master and month-transaction. This program has the following modules: 1. A module to enter monthly details 2. A module for preparing the payslips somasundaramk@yahoo.com */ import import import import import java.awt.*; java.awt.event.*; javax.swing.*; java.util.*; java.sql.*; class Monthpanel extends JPanel implements ActionListener { JTextField namef, codef, transportf, medicalf, pff, loanf, itf; JLabel namel, codel, transportl, medicall, pfl, loanl, itl; boolean more; // The following are values to be obtained from the // database table employee_month String empname; int empcode; int transport, medical, pf, loan, it; JButton cal, clear; // date variables int day, month, year; String date; JLabel datel, datefield; Monthpanel(NextRecord obj) { // creating current date GregorianCalendar calendr = new GregorianCalendar(); day = calendr.get(Calendar.DATE); month = calendr.get(Calendar.MONTH); month += 1; // January is 0 hence this conversion year = calendr.get(Calendar.YEAR); date = “ “ + day + “-” + month + “-” + year; JDBC setLayout(new GridLayout(11, 2)); empcode = 0; transport = 0; medical = 0; pf = 0; loan = 0; it = 0; empname = obj.empname; empcode = obj.empcode; transport = obj.transport; medical = obj.medical; pf = obj.pf; loan = obj.loan; it = obj.it; JLabel maintitle = new JLabel(“ PAYROLL”); JLabel monthtitle = new JLabel(“ - MONTHLY DETAIL ENTRY “); datel = new JLabel(“Date “); datefield = new JLabel(date); namel = new JLabel(“Name”); namef = new JTextField(empname); namef.setEditable(false); codel = new JLabel(“Employee Code “); codef = new JTextField(“” + empcode); transportl = new JLabel(“Tranport “); transportf = new JTextField(“” + transport); medicall = new JLabel(“Medical”); medicalf = new JTextField(“” + medical); pfl = new JLabel(“Provident Fund “); pff = new JTextField(“” + pf); loanl = new JLabel(“Loan “); loanf = new JTextField(“” + loan); itl = new JLabel(“Income Tax “); itf = new JTextField(“” + it); JButton clr = new JButton(“CLEAR ENTRY”); clr.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { transportf.setText(“” + 0); medicalf.setText(“” + 0); pff.setText(“” + 0); loanf.setText(“” + 0); itf.setText(“” + 0); } }); JButton upd = new JButton(“UPDATE RECORD”); 639 640 Programming in JAVA2 add(maintitle); add(monthtitle); add(datel); add(datefield); add(namel); add(namef); add(codel); add(codef); add(transportl); add(transportf); add(medicall); add(medicalf); add(pfl); add(pff); add(loanl); add(loanf); add(itl); add(itf); add(clr); add(upd); upd.addActionListener(this); JButton ext = new JButton(“EXIT”); add(ext); ext.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { System.exit(0); } }); } public void actionPerformed(ActionEvent ae) { // get the updated values String empnam = namef.getText(); int empcod = Integer.parseInt(codef.getText()); int trans = Integer.parseInt(transportf.getText()); int medi = Integer.parseInt(medicalf.getText()); int pfamt = Integer.parseInt(pff.getText()); int lon = Integer.parseInt(loanf.getText()); int intax = Integer.parseInt(itf.getText()); //update the records in the database try { //Register the JDBCODBC driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); JDBC 641 Connection conect = DriverManager.getConnection(“jdbc: odbc:stu_base”); String sql=“update employe_month set transport =?, medical = ?, pf=?,loan=?,it=? where emp_code=?”; PreparedStatement pstm = conect.prepareStatement(sql); pstm.setInt(1, trans); pstm.setInt(2, medi); pstm.setInt(3, pfamt); pstm.setInt(4, lon); pstm.setInt(5, intax); pstm.setInt(6, empcod); pstm.executeUpdate(); conect.commit(); } catch (SQLException sqe) { System.out.println(“Sql error in update “); } catch (ClassNotFoundException cnf) { System.out.println(“Class Not found error “); } } } class NextRecord { String empname; int empcode; int transport, medical, pf, loan, it; ResultSet rst; NextRecord(ResultSet rset) { try { rst = rset; empname = rst.getString(1); empcode = rst.getInt(2); transport = rst.getInt(3); medical = rst.getInt(4); pf = rst.getInt(5); loan = rset.getInt(6); it = rst.getInt(7); } catch (SQLException sqe) { 642 Programming in JAVA2 System.out.println(“Sql error in NextRecord”); } } } class Editframe extends JFrame { Container conpan; Statement stm; ResultSet reset; boolean processed = false; NextRecord nxtrec; Connection conect; Editframe(String str) { super(str); conpan = getContentPane(); setSize(340, 350); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); JButton nxt = new JButton(“NEXT RECORD”); conpan.setLayout(new BorderLayout()); try { //Register the JDBCODBC driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); conect = DriverManager.getConnection(“jdbc: odbc:stu_base”); stm = conect.createStatement(); // select all records from employee_month table reset = stm.executeQuery(“select * from employe_month “); while (reset.next()) { nxtrec = new NextRecord(reset); conpan.add(new Monthpanel(nxtrec), BorderLayout.NORTH); conpan.add(nxt, BorderLayout.SOUTH); setVisible(true); JDBC 643 while (!processed) { nxt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { processed = true; } }); } processed = false; } // while end } catch (SQLException sqe) { System.out.println(“Sql error in EditFRame class”); } catch (ClassNotFoundException cnf) { System.out.println(“Class Not found error “); } } } class Paypanel extends JPanel { JTextField namef, codef, designf, bpayf, totalf, deductionf, netpayf, transportf, medicalf, pff, loanf, itf; JTextField hraf, daf; JLabel payl1, payl2, dedl1, dedl2, dal, hral; JLabel namel, codel, designl, bpayl, totall, deductionl, netpayl, transportl, medicall, pfl, loanl, itl; // The following are values to be obtained from the // database table employee_month String empname, design; int empcode; int transport, medical, pf, loan, it; int bpay, hra, da, deduction, totalpay, netpay; // date variables int day, month, year; String date; JLabel datel, datefield; 644 Programming in JAVA2 Paypanel(Payrec obj) { // creating current date GregorianCalendar calendr = new GregorianCalendar(); day = calendr.get(Calendar.DATE); month = calendr.get(Calendar.MONTH); month += 1; // January is 0 hence this conversion year = calendr.get(Calendar.YEAR); date = “ “ + day + “-” + month + “-” + year; setLayout(new GridLayout(19, 2)); empname = obj.ename; empcode = obj.ecode; design = obj.design; bpay = obj.bpay; transport = obj.trans; medical = obj.medi; pf = obj.pfam; loan = obj.loanam; it = obj.itam; totalpay = obj.totalpay; netpay = obj.netpay; hra = obj.hra; da = obj.da; deduction = obj.deduction; JLabel maintitle = new JLabel(“ PAYROLL”); JLabel monthtitle = new JLabel(“ -PAYSLIP “); datel = new JLabel(“Date “); datefield = new JLabel(date); payl1 = new JLabel(“ PAY DETAILS”); payl2 = new JLabel(“ Rs. “); namel = new JLabel(“Name”); namef = new JTextField(empname); namef.setEditable(false); codel = new JLabel(“Employee Code “); codef = new JTextField(“” + empcode); codef.setEditable(false); designl = new JLabel(“Designation”); designf = new JTextField(design); designf.setEditable(false); bpayl = new JLabel(“Basic Pay”); bpayf = new JTextField(“” + bpay); bpayf.setEditable(false); hral = new JLabel(“House Rent “); hraf = new JTextField(“” + hra); hraf.setEditable(false); dal = new JLabel(“Dearness Allowance”); daf = new JTextField(“” + da); daf.setEditable(false); transportl = new JLabel(“Transport “); JDBC transportf = new JTextField(“” + transport); transportf.setEditable(false); medicall = new JLabel(“Medical”); medicalf = new JTextField(“” + medical); medicalf.setEditable(false); totall = new JLabel(“Total Pay”); totalf = new JTextField(“” + totalpay); totalf.setEditable(false); dedl1 = new JLabel(“DEDUCTIONS”); dedl2 = new JLabel(“ Rs.”); pfl = new JLabel(“Provident Fund “); pff = new JTextField(“” + pf); pff.setEditable(false); loanl = new JLabel(“Loan “); loanf = new JTextField(“” + loan); loanf.setEditable(false); itl = new JLabel(“Income Tax “); itf = new JTextField(“” + it); itf.setEditable(false); deductionl = new JLabel(“Total Deduction”); deductionf = new JTextField(“” + deduction); deductionf.setEditable(false); netpayl = new JLabel(“Net Pay”); netpayf = new JTextField(“” + netpay); netpayf.setEditable(false); add(maintitle); add(monthtitle); add(datel); add(datefield); add(payl1); add(payl2); add(namel); add(namef); add(codel); add(codef); add(designl); add(designf); add(bpayl); add(bpayf); add(hral); add(hraf); add(dal); add(daf); add(transportl); add(transportf); add(medicall); add(medicalf); add(totall); add(totalf); 645 646 Programming in JAVA2 add(dedl1); add(dedl2); add(pfl); add(pff); add(loanl); add(loanf); add(itl); add(itf); add(deductionl); add(deductionf); add(netpayl); add(netpayf); JButton ext = new JButton(“EXIT”); add(ext); ext.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { System.exit(0); } }); } } class Payrec { String ename, design; int ecode, bpay, trans, medi, pfam, loanam, itam; int hra, da; int totalpay, deduction, netpay; Payrec(ResultSet pobj) { try { ename = pobj.getString(1); ecode = pobj.getInt(2); design = pobj.getString(3); bpay = pobj.getInt(4); trans = pobj.getInt(5); medi = pobj.getInt(6); pfam = pobj.getInt(7); loanam = pobj.getInt(8); itam = pobj.getInt(9); hra = (int)(bpay * 0.10); da = (int)(bpay * 0.53); totalpay = bpay + hra + da + trans + medi; deduction = pfam + loanam + itam; netpay = totalpay - deduction; } catch (SQLException sqe) JDBC 647 { System.out.println(“Sql error in NextRecord”); } } } class Payframe extends JFrame { Container conpan; Statement stm; ResultSet reset; boolean processed = false; Payrec rec; Connection conect; Payframe(String str) { super(str); conpan = getContentPane(); setSize(340, 600); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); JButton nxt = new JButton(“NEXT PERSON”); conpan.setLayout(new BorderLayout()); try { //Register the JDBCODBC driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); conect = DriverManager.getConnection(“jdbc: odbc:stu_base”); stm = conect.createStatement(); // select allrecords from employee_month and //employee_master tables reset = stm.executeQuery(“select ems.emp_name, ems.emp_code, ems.design, ems.basic_pay, em.transport, em.medical, em.pf,em.loan, em.it from employee_master ems,employe_month em where ems.emp_code= em.emp_code “); 648 Programming in JAVA2 while (reset.next()) { rec = new Payrec(reset); conpan.add(new Paypanel(rec), BorderLayout.NORTH); conpan.add(nxt, BorderLayout.SOUTH); setVisible(true); while (!processed) { nxt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { processed = true; } }); } processed = false; } // while end } catch (SQLException sqe) { System.out.println(“Sql error in Payframe class”); } catch (ClassNotFoundException cnf) { System.out.println(“Class Not found error “); } } } // Thread class class Editthread implements Runnable { String title; Thread th; Editthread(String str) { title = str; th = new Thread(this, “editthread”); th.start(); JDBC 649 } public void run() { new Editframe(title); } } class Paythread implements Runnable { String title; Thread th; Paythread(String str) { title = str; th = new Thread(this, “Paythread”); th.start(); } public void run() { new Payframe(title); } } class Mainmenu extends JFrame { Container conpan; JPanel mp; Mainmenu(String str) { super(str); conpan = getContentPane(); conpan.setLayout(new GridLayout(3, 2)); setSize(300, 150); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); JLabel editl = new JLabel(“Edit the monthly detail”); JButton edit = new JButton(“EDIT RECORDS”); 650 Programming in JAVA2 JLabel payl = new JLabel(“Prepare payslips “); JButton pay = new JButton(“DISPLAY PAYSLIPS”); JLabel extl = new JLabel(“Exit the payroll system”); JButton exit = new JButton(“EXIT”); conpan.add(editl); conpan.add(edit); edit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { new Editthread(“EDIT RECORDS”); } }); conpan.add(payl); conpan.add(pay); pay.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { new Paythread(“PAYSLIP PREPARATION “); } }); conpan.add(extl); conpan.add(exit); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { System.exit(0); } }); setVisible(true); } } class Probtest { public static void main(String args []) { new Mainmenu(“PAYROLL PREPARATION “); } } JDBC The above program gives the following output: (a) (b) 651 652 Programming in JAVA2 Fig.21.12 (c) Output Screens for Program 21.1W (a) Main Screen (b) Monthly Transactions Screen (c) Payslip Screen JDBC 653 Exercise-21 I. Fill in the blanks 21.1 The ODBC standard enables database connectivity to databases, independent of the vendor. ________ 21.2 A JDBC driver act as a _________ between the Java client and the database server. 21.3 There are ______ types of drivers of JDBC. 21.4 The _____ object establishes a connection between the Java client and the database server. 21.5 A JDBC is loaded in the program using the __________ method. 21.6 A database URL contains _______, _______ and _______ . 21.7 To execute a static SQL statement ___________ is used. 21.8 To execute a dynamic SQL statement _______ or ______ can be used. 21.9 An SQL statement with OUT parameter is handled in __________ . 21.10 When an SQL statement is executed, the results are stored in ________ object. II. Write Java programs for the following problems: 21.11 Write a Java program to create a table with the following fields and insert 5 sets of records into it: Name 25 Characters Designation 10 Characters Basic Pay Number 21.12 In problem 21.11, increase the basic pay by 25% for all those whose basic pay is < Rs 5000. 21.13 In problem 21.11, delete all records when the Basic pay = 0. 21.14 A database table contains the following fields Name Character Age Number Income Number It is required to find all the names, when income < ? - Set the IN parameter to the integer 25000 and display the list. 21.15 In problem 21.14, insert a row with values “Tagore”, 75, 65000. * * * * * * 654 Programming in JAVA2 BLANK Chapter 22 SERVLETS Servlets are server side programs. They are used for developing web applications in a client-server architecture. Servlets are part of Java Enterprise Edition5 (JAVAEE5). In this chapater you will learn how to write servlet programs, deploy them in Sun Java Application Server Platform Edition and invoke them through POST and GET type requests from client browsers. You will also learn about cookies and session tracking. 22.1 Servlets A servlet is a server side Java program in a client-server architecture. It is analogous to applets for client side. A servlet resides in a server and respond to the requests coming from clients. Servlets are used in web applications and are mostly used in multitier enterprise architecture of J2EE. Presently this technology is called Java platform Enterprise Edition5(JAVAEE5). Servlets are more efficient in handling multiple requests coming from clients than programs written in CGI(Common Gateway Interface) or Perl. 656 Programming in JAVA2 In a client-server architecture (see Fig.22.1) a client makes a request, using HTTP protocol, to a web server requesting for a web page or some resource available in that server. The server process the request, usually locates the requested web page or retrieve the requested data from a database, or other services available in that server, and sends a response to the client. A servlet performs the role of a server. The servlet sends its response to the client in the form of a dynamic HTML document and can be viewed through a web browser like Mozilla Firefox or Internet Explorer. The requests to a server come from HTML documents executed by a browser running in a client. Therefore, a knowledge of the structure of the HTTP requests and the Java classes that are used to build a servlet is necessary to write a servlet program. In the following sections, these two topics are discussed. Client request Server response Client: executing an HTML document Server Fig.22.1 Client-Server Architecture. 22.2 The HTML(Hyper Text Markup Language) An HTML document embeds any request that is to be sent to a server. When a browser on the client side executes the HTML document, the HTTP request is sent to the server. The server process the request and sends a reply to the client. As the scope of this chapter is to illustrate how to build and use servlets, we give only those HTML documents that are needed for examples discussed in this section. Those who are not familiar with HTML documents may need to read a book on designing web pages using HTML. The program 22.1 is a simple HTML document that gives a welcome note. Program 22.1 introhtml.html <html> <head> <title>Introduction</title> </head> <body> <h1>Welcome to HTML</h1> <p>An HTML document can be prepared as per the HTTP specification. To view (execute) an HTML document a browser is needed. SERVLETS 657 What you see is an HTML document given in Program 22.1 viewed in a Mozilla Firefox browser.</p> <p>Program by Dr.K.Somasundaram</p> <p>somasundaramk@yahoo.com</p> </body> </html> The output of the program 22.1 when viewed with Mozilla Firefox browser is given in Fig.22.2 Fig.22.2 Screen showing the output of program 22.1 by Mozilla Firefox. 22.3 Interface Servlet The methods that help to build a servlet are defined in the interface Servlet. The methods defined in a Servlet interface and their functions are given in Table 22.1. The methods init(), service() and destroy() are known as life cycle methods. All the methods are automatically called when a servlet is executed. Table 22.1 Methods defined in a Servlet Interface. Method Purpose of the Method void init(ServletConfig config) This method is called automatically, once, when the servlet is executed, to initialize the servlet. ServletConfig getServletConfig() Returns a ServletConfig object which contains initialization and startup parameters for the servlet. 658 Programming in JAVA2 void service(ServletRequest req, ServletResponse res) This is the method called first on a servlet to respond to a request from a client. String getServletInfo() Returns a string that contains the information about the servlet like author, version and copyright. void destroy() This method is called when a servlet is terminated. This method cleans up all resources that are held by the servlet, like memory, files and threads. The Servlet interface is implemented in two abstract classes javax.servlet.GenericServlet and javax.servlet.http.HttpServlet. The GenericServlet class defines protocol-independent servlet, while the HttpServlet class can be used create an HTTP servlet suitable for web applications. Therefore, in the following section the HttpServlet class is explained. 22.4 HttpServlet Class An HttpServlet is an abstract class and is a subclass of GenericServlet class. A servlet is created by subclassing this HttpServlet class and overriding one or more of the methods defined in it. The most useful methods to create a servlet are doGet() and doPost(). The types of HTTP requests sent from a client to a servlet are GET and POST. The GET request is to get an information from the server. The POST request is to send an information to the server. However, the POST request can also be used to get information from the server. The doGet() method is used to handle the GET request and the doPost() method is used to handle the POST request. The POST request is used when a large amount of data is to be sent to the server from a client(browser). The GET requests are cached in the client machine while the POST requests are not. The general form of using these two methods are: void doGet(HttpServletRequest req, HttpServletResponse res) void doPost(HttpServletRequest req, HttpServletResponse res) where, req – an object of the type HttpServletRequest that contains the request the client has made, res – an object of the type HttpServletResponse that contains the response that the servlet sends to the client. Both the HttpServletRequest and HttpServletResponse objects are created by the web server executing the servlet and pass them to the doGet() and doPost() methods as parameters. SERVLETS Some of the useful methods that can HttpServletRequest object are given in Table 22.2. be called 659 on an Table 22.2 Some of the methods that can be called on an HttpServletRequest object. Method Purpose of the Method 1. String getContentType() Returns the MIME type of the body of the request, or null if the type is not known. 2. String getParameter(String name)Returns the value associated with a parameter sent to the servlet, in the GET or POST request. Here, name is the name of the parameter. 3. Enumeration getParameterNames() Returns an Enumeration of String object containing the names of all parameters in the request. 4. String[ ] Returns an array of string objects getParameterValues(String name) containing the values of a specified parameter in the request. 5. String getServerName() Returns the host name of to which the request was sent. the server 6. Cookie[ ] getCookies() Returns an array of Cookie object stored on the client by the server. 7. HttpSession getSession(Boolean create) Returns an HttpSession object associated with the client’s browsing session. If create is set to true, it creates an Http Session for the client. Some of the methods that can be called on an HttpServletResponse object are given in Table 22.3. Table 22.3 Method Some of the methods that can be called on an HttpServletResponse object. Purpose of the method 1. void flushBuffer() Forces any content in the buffer to be written to the client. 2. int getBufferSize() Returns the actual buffer size used for the response. If no buffering is used, this method returns 0. 660 Programming in JAVA2 3. ServletOutputStream getOutputStream() Returns a ServletOutputStream suitable for writing binary data in byte form to the client. 4. PrintWriter getWriter() Returns a PrintWriter object that can send character text to the client. 5. void setContentType(String type) Sets the content type of the response being sent to the client. The type specifies the MIME type of the content. For example “text/html” specifies that the response is an HTML document. G An HttpServlet class is used to create a servlet. There are two types of HTTP requests POST and GET. These requests are serviced by doPost() and doGet() methods defined in HttpServlet class. 22.5 Servlet Programs Before we start writing servlets, it is necessary to know about Web application. A web application is a collection of HTML documents, applets, servlets, java classes and other supporting resources. These components are placed in a package called Web Archive(WAR). This WAR file can be created manually or by using a software tool. After creating a WAR file it has to be placed in a web server. For both purposes, the Deploy tool available in the Sun Java System Application Server Platform Edition 8.1 Q2005Q1 is used. 22.5.1. A Simple Servlet Having seen what a servlet is and the classes used for creating a servlet, we now write a simple servlet. This servlet in program 22.2 when invoked sends a welcome note to the client. This program makes one way communication from server to client. Program 22.2 /* Program to illustrate servlet somasundaramk@yahoo.com */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Welcomserv extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) SERVLETS 661 throws IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head><title>First Servlet</title></head>"); out.println("<body>"); out.println("<h1>Welcome to Servlet Programming</h1>"); out.println("</body>"); out.println("</html>"); } } 22.5.2 Compiling a Servlet To compile a servlet you need the java compiler javac.exe and the servlet.jar file. The javac.exe file can be found in the JDK and can be downloaded from java.sun.com. For all the examples in this Chapter, jdk1.2.4 has been used. For servlet.jar file Tomcat 4.1\Common\lib\servlet.jar has been used. For compiling in command line, you need to set the path to the location of javac.exe file and CLASSPATH to the location of the servlet.jar file. For the directories I have used, the following setting has been done. C>PATH=C:\jdk1.2.4\bin C>Set CLASSPATH=C:\Program Files\ApacheGroup\Tomcat4.1\Common\lib\servlet.jar Then the compilation is done as usual using the following command. C>javac Welcomserv.java After compiling, you will get Welcomeserv.class file. This servlet can be executed using a web server. For all the examples in this chapter, Sun Java System Application Server Platform Edition 8.1 2005Q1 is used to package, deploy and execute the servlets. For this you need to download j2eesdk-1_4_02 and install it in your system. After installation, you test the installation by starting the server. To start the server, use the following command in Windows : Start à Program à Sun Microsystems à Application Server PE à Start Default Server After starting the server, open a browser, and type http://localhost:8080 in the address bar. The browser will show the status of the server as shown in Fig.22.3. 662 Programming in JAVA2 Fig.22.3 22.5.3. Screen showing the server running. Deploying and Executing a Servlet The servlet is executed using the Sun Java Web server. The various steps involved to execute a servlet are explained below. 1. Start the Sun Default Web Server by issuing the following command (in Windows). Start à Programs à Sun microsystems à Application Server PE à Start Default Server. 2. Start the Deploytool by issuing the following command. Start à Programs à Deploytool. Sun microsystems à Application Server PE à You will get a Deployment tool screen as shown in Fig.22.4. SERVLETS Fig.22.4 3. 663 Screen showing the Deployment tool. In Deployment Tool, select File à New à Web Component. You will get a screen. In the screen, select Next. You will get a screen titled New Web Application Wizard as shown in Fig.22.5. In WAR Naming, select a location for WAR file. The location can be anywhere. You will get a pop up window when you click Browse. In the pop up window, called Create Module File, you must give the file name as examples (Sun Specific). Then click Create Module file. Now WAR Display Name will show an entry examples. In Context Root, you must give context root as examples (Fig.22.5). Fig.22.5 Screen Showing the Web Application Wizard. 664 Programming in JAVA2 Now click Edit contents. You will get a screen: Edit contents of examples. Find the directory, where the compiled Welcomserv.class is located. From the option Available Files, select the Welcomserv.class file, and select Add button, and then click Ok (see Fig. 22.6). Note that the Welcomserv.class is added in WEB-INF / classes directory. Fig.22.6 Screen Showing Edit Content Option. You will be returning back to the Web Application Wizard. Now click Next. 4. Now you will get a screen : New Application Wizard-Choose Component Type. Select Servlet (Fig.22.7) and click Next. Fig.22.7 Screen Showing the selection of Servlet. SERVLETS 5. 665 Now you will get a screen: New Web Application Wizard - Component General Properties. In this, select Servlet class entry as Welcomserv.class. After selecting this, your screen will appear as in Fig.22.8. Now select Next. In the next screen click Finish. You will be back in the main window of DeployTool. Fig.22.8 Screen Showing the Component General Properties. 6. Now, on the left panel of Deployment Tool select Welcomserv. Then select Aliases on the right panel. You will get a screen as shown in Fig.22.9. Fig.22.9 Screen showing the setting of aliases to Welcomserv as welcome. 666 Programming in JAVA2 Now click add. On the Aliases column, type a name that you like to call in a browser. Now type /welcome. Only this name is used to invoke the servlet. 7. On the left panel of Deployment Tool, select examples. Select Tools à Verify J2EE Compliance You will get a verify specification compliance screen as shown in Fig.22.10. In that click OK. After the report is generated click close. Fig.22.10 Screen showing the verification of Window Options. 8. On the left panel of Deployment Tool select examples. Then Select tools à Deploy The dialog will ask for User name and Password. Supply these items (which were supplied during installation of Application server) and click Ok. As a response, the Deployment tool will start creating the necessary entries, in the web server and give a message : operation completed successfully, along with other report. Now the servlet is ready for accepting requests. 9. Open a Web browser. In the address bar type : http://localhost:8080/examples/welcome You will get the result as shown in Fig.22.11 SERVLETS 667 Fig.22.11 Screen showing the output of Welcomserv servlet, having an aliase name as welcome. Now you may like to see the directories and files created in the web server for this example. For the above application, the root directory for the Sun Java System Application Server Platform Edition 8.1 Q12005 will look like: C:\Sun\AppServer\domains\domain1\application\j2ee-modules\examples The other directories and files are : root\META-INF\Manifest.MF root\WEB-INF\Classes\Welcomserv.class root\WEB-INF\Web.xml root\WEB-INF\Sun-web.xml The source files (*.java) and *.class files, as usual, will be in the directory where you created and compiled. · G · A Servlet is a component in JavaEE5. After compiling the servlet program, it has to be packaged in Web Archive(WAR). This can be done manually or using Deploytool in Sun Java Application platform which is the web server. · When a request comes from a client, the web server creates an HttpRequest object and an HttpResponse object and pass them to the doPost() or doGet() method. 22.5.4. Deploying an HTML Document in a Web Server The servlet class files are web components. Other files like HTML document, images are not web components. They can also be placed in the web server and used along with the servlets. Now we will show, as an example, how to deploy the introhtml.html document in the web server. To deploy this document, the following steps are used. 668 1. Programming in JAVA2 Start the Deploytool using the command given section 2.5.3(2) On the left panel of the Deployment Tool, select examples. On the right panel of the Deployment Tool, under General select Edit contents. You will get a new window titled: Edit contents of examples. In the top panel, under starting Directory, select the introhtml.html file and click Add. And then click Ok to close the window. The Deployment Tool window will show the entry of introhtml.html file as shown in Fig.22.12. Note that this file is outside WEB-INF directory. Fig.22.12 Deployment tool screen after adding introhtml.html document. 2. 3. You need to redeploy the examples.WAR file to include the introhtml.html in the Web Server. In the Deployment Tool window, select examples, then from Tools Option select Deploy. After successful deployment, open a browser and type : http://localhost:8080/examples/introhtml.html. You will get an output as shown in Fig.22.13. Fig.22.13 Screen showing the introhtml.html document served through the web server. SERVLETS 22.5.5 669 Sending Data – HTML Form with GET In the previous section 2.5.4 we have seen how a static HTML document was served by the web server and viewed in a web browser. Now we will create an HTML document that will prompt the user to feed some details of the user. For collecting the data in the HTML document, FORM tag is used. This HTML page sends the collected data to the servlet named “Myname”, in the web server, using GET method. The welcomehtm.html document given in program 22.3 shows the statements used in HTML program to collect data from the user. This is a client side program. Program 22.3 welcomehtm.html <HTML> <HEAD> <TITLE>Welcome</TITLE> </HEAD> <BODY> <H1>Welcome to Servlet Programming</H1> <FORM METHOD="GET" ACTION="myname"> <p>Please provide the following details</p> <p> Name :<INPUT TYPE ="text" NAME="name"></p> <p> Place:<INPUT TYPE ="text" NAME ="place"></p> <p> District:<INPUT TYPE ="text" NAME ="district"></p> <p> State:<INPUT TYPE ="text" NAME ="state"></p> <INPUT TYPE="SUBMIT" VALUE= "Submit"> </FORM> </BODY> </HTML> Deploy HTML document given in Program 22.3 as explained earlier. Open a web browser and type : http://localhost:8080/examples/welcomehtm.html. The output screen, viewed in the Mozilla Firefox browser, is given in Fig.22.14. Fig.22.14 The output screen when the program 22.3 is viewed through a Mozilla Firefox browser after the user had filled in the form. 670 Programming in JAVA2 When the user press the Submit button, the values for the four parameters name, place, district and state are sent to the servlet with aliase name “myname” in the web server. The HTTP request made in the HTML page to the servlet is in GET type. 22.5.6 Servlet with doGet() Method In the previous section 22.5.5 we have seen how a client had sent a request to the servlet with four parameters. In this section we will see how a servlet is receiving these requests and sends a response. The client side program 22.3, makes the GET type HTTP request, to the server. The web server creates req object of type HttpServletRequest and res object of type HttpServletResponse. The req object contains the details of the request made to the server by the client. The res object contains the details to be sent to the client as a response. The server executes the servlet named “Myname” which calls its doGet() method by passing the two objects res and req as parameters as shown in Program 22.4. The getParameter() method returns the values of the parameters, name, place, district and state. These four parameters are then returned to the client using the res object. The getWriter() method is called on the res object to get a PrintWriter object. The println() method is called to send the parameters and a text, in an HTML format. The setContentType() method sets the output type as HTML. Program 22.4 /* This program illustrates how a GET type request from a client is serviced by a servlet. The request is accompanied by four values of four parameters, name,place,district and state.This servlet reads the data and sends them back to the client as a response. somasundaramk@yahoo.com */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Myname extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Get the name parameter String name = req.getParameter("name"); // Get the place parameter String place = req.getParameter("place"); // Get the district parameter String district = req.getParameter("district"); // Get the state parameter String state = req.getParameter("state"); SERVLETS 671 out.println("<html>"); out.println("<head><title>"+name+"s Response</title></ head>"); out.println("<body>"); out.println("<h1>Welcome " +name +"</h1>"); out.println("<h2>You are from " +place ); out.println("which is in " +district+" District of" ); out.println(state +" in India. Great to meet you.</h2>"); out.println("</body>"); out.println("</html>"); } } Compile the program 22.4 and deploy it using Deployment Tool of Sun Java System Application Server. During deployment set “myname” aliases for Myname.class. The response of the servlet in program 22.4 when user clicks the “Submit” button (Fig.22.14) in program 22.3 is shown Fig.22.15. the as the in Fig.22.15 Screen showing the output of program 22.4 for the request made through program 22.3. On the address bar of the browser, you will notice the data sent to the server in “name=value” pair, which appears after ? symbol. This data will be stored as URL in the computer and can be reused again. There is a limit for this name-value pairs. Hence, amount of data POST method in HTML form is to be used. 22.5.7 for sending large HTML Form with POST Method The preferred method for sending data to a server is POST. An HTML form with POST method, which does the same function as that of program 22.3 is given in program 22.5 except that the data is sent to the server using POST method. 672 Programming in JAVA2 Program 22.5 <HTML> <HEAD> <TITLE>Welcome</TITLE> </HEAD> <BODY> <H1>Welcome to Servlet Programming</H1> <FORM METHOD="POST" ACTION="mypost"> <p>Please provide the following details</p> <p> Name :<INPUT TYPE ="text" NAME="name"></p> <p> Place:<INPUT TYPE ="text" NAME ="place"></p> <p> District:<INPUT TYPE ="text" NAME ="district"></p> <p> State:<INPUT TYPE ="text" NAME ="state"></p> <INPUT TYPE="SUBMIT" VALUE= "Submit"> </FORM> </BODY> </HTML> Program 22.5 when viewed with a browser gives the same result as given in Fig.22.14. 22.5.8 Servlet with doPost() Method We have seen in section 22.5.6 how a servlet receives data using doGet() method. Now we will see how a doPost() method is used to receive data from a client which sends data using POST method. The servlet given in program 22.6 shows how a doPost() method is implemented. Program 22.6 does exactly the same functions as that given in program 22.4. Program 22.6 /* This program illustrates how a POST type request from a client is serviced by a servlet. The request is accompanied by four values of four parameters, name,place,district and state.This servlet reads the data and sends them back to the client as a response. somasundaramk@yahoo.com */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Mypost extends HttpServlet{ public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Get the name parameter String name = req.getParameter("name"); // Get the place parameter String place = req.getParameter("place"); SERVLETS 673 // Get the district parameter String district = req.getParameter("district"); // Get the state parameter String state = req.getParameter("state"); out.println("<html>"); out.println("<head><title>"+name+"s Response</title></ head>"); out.println("<body>"); out.println("<h1>Welcome " +name +"</h1>"); out.println("<h2>You are from " +place ); out.println("which is in " +district+" District of" ); out.println(state +" in India. Great to meet you.</h2>"); out.println("</body>"); out.println("</html>"); } } In the output screen you will notice that there are no other entries excepting the (aliases) name, mypost, of the servlet. 22.5.9 Servlet with doGet() and doPost() Methods If a servlet has to respond to both GET and POST methods of the client, then it has to implement the doGet() and doPost() methods respectively. Alternatively the doGet() method be implemented first and be called in doPost() method, if identical responses are required. Program 22.7 is a servlet which combines the functions of programs 22.4 and 22.6. Program 22.7 /* This program illustrates how a GET and POST type requests from a client are serviced by a servlet. Each request is accompanied by four values of four parameters, name,place,district and state.This servlet reads the data and sends them back to the client as a response. somasundaramk@yahoo.com */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Mygetpost extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Get the name parameter String name = req.getParameter("name"); // Get the place parameter String place = req.getParameter("place"); 674 Programming in JAVA2 // Get the district parameter String district = req.getParameter("district"); // Get the state parameter String state = req.getParameter("state"); out.println("<html>"); out.println("<head><title>"+name+"s Response</title></ head>"); out.println("<body>"); out.println("<h1>Welcome " +name +"</h1>"); out.println("<h2>You are from " +place ); out.println("which is in " +district+" District of" ); out.println(state +" in India. Great to meet you.</h2>"); out.println("</body>"); out.println("</html>"); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException{ doGet(req,res); } } G When identical requests are sent from a client in POST type or GET type requests, then the servlet may implement doGet() method and call it in doPost() method. 22.5.10 Servlet Receiving Numbers We have seen in the previous examples how String type data sent by a client through an HTML document is processed by a servlet. An HTML document supports a data type of String only. There is no data type in HTML which handles numeric type data. Therefore, when a string (text) containing numeric value is received by a servlet, the string value is to be converted to a numeric type. The HTML document given in program 22.8 shows the statements used to collect the name, height and weight of a person. Program 22.8 <HTML> <HEAD> <TITLE>Your weight</TITLE> </HEAD> <BODY> <H1>Test your Weight</H1> <FORM METHOD="GET" ACTION="Weightsrv"> <p>Provide your height in meters and weight in kg </p> <p> Name-------------:<INPUT TYPE ="text" NAME="name"></p> <p> Height(in meter)-:<INPUT TYPE ="text" NAME ="height"></p> SERVLETS 675 <p> Weight(in kg)----:<INPUT TYPE ="text" NAME ="weight"></p> <INPUT TYPE="SUBMIT" VALUE= "Submit"> </FORM> </BODY> </HTML> The output screen, when the program 22.8 deployed in the web server and invoked through Mozilla Firefox browser is given in Fig.22.16 Fig.22.16 Screen showing the output for program 22.8 when executed by Sun Application server and viewed through Mozilla Firefox, after the user had filled in the form. Now we will see how a servlet handles the numeric data type. The getParameter() method of HttpServletRequest object returns a String type value. When the string consists of only numerical value, it can be converted to any of the corresponding numeric types, int, long, float, double etc. Methods like Integer.ParseInt(), Double.parseDouble(), Float.parseFloat() are used to convert String type to int, double and float type respectively. The servlet given in program 22.9 receives a few string type data from a client and converts them to double type. The problem dealt in the program 22.9 is estimating the expected weight of a person, which is 23 times the square of the height of that person, measured in meters. It then compares the weight supplied by the user with the estimated weight (maxweight) and returns a message “within the limit” or “over weight”. 676 Programming in JAVA2 Program 22.9 /* This program illustrates how a GET type request from a client is serviced by a servlet. The request is accompanied by three values of three parameters, name,height and weight. The String type values are then converted to double type value using parseDouble() method. The standard weight of a person is given by 23 times the square of the height in meters.The servlet then sends the appropriate message to the client as a response. somasundaramk@yahoo.com */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Weightsrv extends HttpServlet{ String name,height,weight,mesg1,mesg2; double dheight,dweight,maxweight; public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Get the name parameter name = req.getParameter("name"); // Get the height parameter height = req.getParameter("height"); // Get the weight parameter weight = req.getParameter("weight"); // convert string to double dheight=Double.parseDouble(height); dweight=Double.parseDouble(weight); maxweight =Math.ceil(23.0*dheight*dheight); mesg1="<p>Expected weight of a person is "; mesg1= mesg1+"23 times the square of the height in meters"; mesg1= mesg1+" which is "+maxweight +" Kg for you.<p> "; if(dweight<=maxweight) mesg2 ="You are within the limit. Keep it up"; else mesg2 ="You are over weight. Try to reduce"; out.println("<html>"); out.println("<head><title>"+name+"s Weight</title></ head>"); out.println("<body>"); out.println("<h1>Welcome " +name +"</h1>"); out.println( mesg1); out.println("<p>"+mesg2 +"<p>" ); out.println("</body>"); out.println("</html>"); } } Compile the program 22.9, deploy it in the Sun Application Server with an aliase name “Weightserv”. SERVLETS 677 The output screen generated by the program 22.9 when the user clicks the submit button (Fig.22.16) in program 22.8 is given in Fig.22.17. Fig.22.17 Output screen for the program 22.9 when the Submit button of program 22.8 is clicked by the user. G To convert String type data to numerical type, use methods like Integer.parseInt(), Double.parseDouble(), Float.parseFloat() etc. See Chapter 10 for more details. 22.5.11 The getParameterNames() and getParameterValues() Methods A data sent by a client, by executing an HTML document, is collected by a servlet using getParameter() method. It is also possible to get the parameter names and the parameter values as an array and the individual parameter name and parameter value can be obtained from the array. The parameter names are obtained using getParameterNames() method and the parameter values using getParameterValues() method from the array. The program 22.10 is an HTML document used as the client side program to collect the data from the user and send it to the servlet Pvaluessrv. Program 22.10 <HTML> <HEAD> <TITLE>Address</TITLE> </HEAD> <BODY> <p><U>Please provide the following details</U></p> <FORM METHOD="GET" ACTION="Pvaluessrv"> <p> Name :<INPUT TYPE ="text" NAME="name"></p> <p> Age:<INPUT TYPE ="text" NAME ="age"></p> 678 Programming in JAVA2 Sex <UL> <INPUT TYPE ="RADIO" NAME="sex" VALUE="male">Male<br> <INPUT TYPE ="RADIO" NAME="sex" VALUE="female">Female<br> </UL> <p> Street:<INPUT TYPE ="text" NAME ="street"></p> <p> City:<INPUT TYPE ="text" NAME ="city"></p> <p> PIN:<INPUT TYPE ="text" NAME ="pin"></p> <p> State:<INPUT TYPE ="text" NAME ="state"></p> <INPUT TYPE="SUBMIT" VALUE= "Submit"> <INPUT TYPE="RESET" VALUE= "Reset"> </FORM> </BODY> </HTML> The output screen when the program 22.10 is executed by Mozilla Firefox browser at the client side is shown in Fig.22.18. Fig.22.18 Output screen when program 22.10 is viewed by Mozilla Firefox, after the user had filled in the form. The servlet given in program 22.11 collects the data from the client using getParameterNames() and getParameterValues() methods. The array elements are then separated into individual elements. SERVLETS 679 Program 22.11 /* This program illustrates how a GET type request from a client is serviced by a servlet. The getParameterValues() and getParameterNames() methods are used to collect the data from the client. The collected data is returned to the client as a response. somasundaramk@yahoo.com */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class Pvaluessrv extends HttpServlet{ String pvalues[]; public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE> Detail</TITLE></HEAD>"); out.println("<body>"); // STRONG is used to get bold type out.println("<STRONG>getParameterNames()"); out.println(" and getParameterValues() </ STRONG><BR><BR>"); out.println("<EM>This is what you supplied </ EM><BR><BR>"); out.println("<TABLE BORDER=\"1\">"); out.println("<THEAD><TR><TH>Param. Name </TH>"); out.println("<TH>Param. Values </TH></TR></THEAD>"); out.println("<TBODY>"); // Get all the parameter names Enumeration pnames = req.getParameterNames(); // get one parameter name while(pnames.hasMoreElements()) { String pname=(String)pnames.nextElement(); //get one parameter value and store pvalues=req.getParameterValues(pname); //print one parameter name out.println("<TR><TD ALIGN=\"CENTER\">"+pname+"</TD>"); //print one parameter value int pn = pvalues.length; out.println("<TD ALIGN=\"CENTER\">"); for(int i=0;i<pn;out.print(pvalues[i++]); out.println("</TD></TR>"); } out.println("</TBODY></TABLE>"); out.println("</body>"); out.println("</html>"); } } 680 Programming in JAVA2 When the getParameterNames() and getParameterValues() methods are used to collect data, the order in which the servlet reproduces them is not the same order in which the client had sent. The servlet then returns the collected data to the client as a table. The output screen for program 22.11 after the user had clicked Submit button (Fig.22.18) of program 22.10 is shown in Fig.22.19. Fig.22.19 Output screen for program 22.11. G The order of parameters given by the client to the servlet is not the same that is produced by the servlet using getParameterNames() method. 22.6 Servlet with I/O File In the previous sections we have seen how servlets handled the GET and POST requests from clients. The data received by a servlet are handled by variables within the servlet program itself. Now we will see how data received from a client is stored in files, retrieved and transmitted to the client. The problem handled is a survey done on the height of male and female. The users height and sex type (male/female) are received and added to the data collected earlier and stored in a file. The file contains the average height and total number of persons involved in computing the average for each sex type. After computing the new average height, the new average height and the updated count for each sex type are written to a file and are also sent to the client. Program 22.12 shows the client side HTML document used for collecting the users name, sex and height. SERVLETS 681 Program 22.12 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional// EN"> <html> <head> <title>Height Survey</title> </head> <body> <h1>Welcome to Height Survey</h1> <u>Please fill the form below</u> <form method="GET" action="Filesrv"> <p> Name-:<input type="text" name="name"></p> <p>Sex <UL ><input type="radio" name="sex" value ="m" checked>Male</p> <input type="radio" name="sex" value ="f">Female</p></UL> <p>Height(in meters)-:<input type="text" name="height"></p> <input type="SUBMIT" value="Submit"> <input type ="RESET" value ="Reset"> </form> </body> </html> The output screen for the program 22.12 when executed with Mozilla Firefox is shown in Fig.22.20. Fig.22.20 Output screen for program 22.12 when viewed with Mozilla Firefox after the user had filled in the form. The servlet that handles the GET request from program 22.12 is given in program 22.13. 682 Programming in JAVA2 Program 22.13 /*---------------------------------------------------------This program collects sex and height of the user from the client HTML documnet. It then reads the previous total male count, male average height, female count and female average height from the file. Using this data the new average height of the corresponding sex is computed. The new average height computed is sent to the client. The new count and new average values are again stored in the file. somasundaramk@yahoo.com ----------------------------------------------------------- */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class Filesrv extends HttpServlet{ double height; String name; String sex; int male_count; int female_count; double male_avg ,female_avg; public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Collect the name, sex and height of the user name=req.getParameter("name"); sex = req.getParameter("sex"); String sheight = req.getParameter("height"); height = Double.parseDouble(sheight); out.println("<HTML>"); out.println("<HEAD><TITLE> Average Height</TITLE></HEAD>"); out.println("<body>"); //Read the male_count,male_avg,female_count,female_avg //from the file try{ File fin =new File("height.dat"); DataInputStream dins= new DataInputStream(new FileInputStream(fin)); male_count = dins.readInt(); male_avg = dins.readDouble(); female_count = dins.readInt(); female_avg = dins.readDouble(); dins.close(); }catch(FileNotFoundException e){ male_count=female_count =0; male_avg = female_avg = 0.; System.out.println("<P>File not found/Starting a new series</P>"); SERVLETS 683 }catch(IOException e){ System.out.println("<P>IO Error</P>"); } if (sex.equals("m")) { male_avg = (male_avg*male_count+height/(male_count +1); ++male_count; } else { female_avg = (female_avg*female_count+height)/ (female_count +1); ++female_count; } try{ File fou =new File("height.dat"); DataOutputStream dos= new DataOutputStream(new FileOutputStream(fou)); dos.writeInt(male_count); dos.writeDouble(male_avg); dos.writeInt(female_count); dos.writeDouble(female_avg); }catch(IOException e){ System.out.println("<P>IO Error</P>"); } // STRONG is used to get bold type out.println("<STRONG>Thank you "+name+" for taking part in the survey </STRONG><BR><BR>"); out.println("<STRONG>Average Height </STRONG><BR>"); out.println("<P>Average height of Male = "); out.println(male_avg +"</P>"); out.println("Total male "+male_count +" <BR>"); out.println("<P>Average height of Female = "); out.println(female_avg+" </P>"); out.println("Total female "+female_count +" <BR>"); out.println("</body>"); out.println("</html>"); } } The client’s data for parameters name, sex and height are received by the servlet using the getParameter() method. The previously computed values male_count, male_avg, female_count and female_avg are read from a file “height.dat” in DataInputStream. The data are then processed by including the new data to compute the average height up to the current user. The count is incremented for the respective type and written to the same file in DataOutputStream. The same data is returned to the client. The output screen for program 22.13 is shown in Fig.22.21. 684 Programming in JAVA2 Fig.22.21 The output screen for program 22.13 after the user clicks the Submit button of program 22.12. You can locate the data file height.dat in: C:\Sun\AppServer\domains\domain1\Config\height.dat 22.7 Servlet with JDBC There are problems in which a client database or may sent data to be stored in a such problems, a server has to handle a architecture. The browser acting as first tier, and the database acting as the third tier. In handle a database in a servlet. may request for data from a database at the server side. In database. This is a three tier the servlet acting as second tier this section we will see how to The problem handled is the same as in section 22.5. The only difference is in the data storage method. In this program all the data received by the servlet are stored in a database. The database is handled using JDBC. The JDBC technology is given in chapter 21. The database is created in M.S. Access. The database is db3.mdb and is registered as student. The data is handled in a table named “hittable”. This table has three fields name, sex and height. The client side HTML is the same as that is given in program 22.12, except the action statement in FORM is set as action = “Insertsrv”, where Insertsrv is the servlet’s aliases name. Program 22.14 shows a servlet that accepts the data from a client and inserts it into the table. After inserting the data, all the records are read out and the average height of male and female are computed seperately and are printed out. Note carefully the syntax of sql statement record1 that is used to insert the values. SERVLETS 685 Program 22.14 /* This program demonstrates how a database is handled by a servlet. The program receives data from a client through GET request. The parameters received are name,sex and height(double type). The received data are inserted into a table named hittable (height table)in a database with DNS name student. All the data in the table are taken out and the average height of male and female are computed somasundaramk@yahoo.com */ import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class Insertsrv extends HttpServlet{ String name,sex,height; int mcount,fmcount; double dheight,mtotheight,fmtotheight; double mavgh,fmavgh; public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Read the parameter values name = req.getParameter("name"); sex = req.getParameter("sex"); height = req.getParameter("height"); dheight = Double.parseDouble(height); Statement stm; ResultSet reset ; String sql,record1; try { // load the driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //establish connection Connection conect = DriverManager.getConnection("jdbc:odbc:student"); // prepare the SQL statement stm = conect.createStatement(); // create SQL statement for inserting records record1 = "insert into hittable (name, sex, height )"; record1 += " values(\'"+name+"\' , \'"+sex+"\',\'"+dheight+"\')"; stm.executeUpdate(record1); // make the changes permanent conect.commit(); // prepare SQL to select all records in hittable String select = "select * from hittable"; reset = stm.executeQuery(select); 686 Programming in JAVA2 out.println("<HTML><HEAD><TITLE>JDBC Demo</TITLE></ HEAD>"); out.println("<BODY>"); out.println("<TABLE BORDER = \"1\">"); out.println("<THEAD> Persons Participated in "); out.println("Height Survey</THEAD>"); out.println("<TR><TH>Name</TH><TH>Sex</TH><TH>Height</ TH></TR>"); // print the table out.println("<TBODY>"); mcount=0; fmcount=0; mtotheight=0.0; fmtotheight=0.0; while(reset.next()) { String nme= reset.getString("name"); String sx = reset.getString("sex"); double ht = reset.getDouble("height"); if(sx.equals("m")) { mcount++; mtotheight += ht; } if(sx.equals("f")) { fmcount++; fmtotheight += ht; } out.println("<TR><TD>"+nme+"</TD>"); out.println("<TD>"+sx+"</TD><TD>"+ht+"</TD></TR>"); } out.println("</TBODY>"); out.println("</TABLE>"); mavgh=mtotheight/mcount; mavgh=(int)(mavgh*100); mavgh=mavgh/100.0;//reduce the decimal digits to2 fmavgh = fmtotheight/fmcount; fmavgh=(int)(fmavgh*100); fmavgh=fmavgh/100.0; out.println("Average Male height = "+mavgh+"<P>"); out.println("Average Female height = "+fmavgh+"<P>"); out.println("Thank you "+name+" for taking <BR>"); out.println("part in the height survey <P>"); //close the statement and connection stm.close(); conect.close(); }catch(SQLException sqe){ out.println("Sql error"); }catch(ClassNotFoundException cnf){ out.println("Class Not found error "); out.println("</BODY></HTML>"); } } } SERVLETS 687 The client side HTML document when executed through the web browser Mozilla Firefox is shown in Fig.22.22. Fig.22.22 The output screen for the client side program executed through Mozilla Firefox, after the user had filled in the data. The response of the servlet given in program 22.14 is shown in Fig.22.23. Fig.22.23 The output screen generated by program 22.14 when the Submit button in the client side is clicked. You can locate the database file db3.mdb in root directory. 688 Programming in JAVA2 22.8 Session Handling In a client/server architecture, a client makes a request to the server, which in turn gives a reply. This request-reply process may continue until the client’s requirement is over. This sequence of request-reply, until the client stops the request, is called a session. The HTTP is a stateless protocol. This protocol contains no information about the client which makes a request to the server. For every request from the client, the server gives a reply and the session is over. There is no link between the current request and the previous requests made by the same client to a server. However, there are occasions, in which the server need to identity which client is making a request. There are several methods that are used to identify the client browsers. Some of the methods are : a. Cookies b. Session Tracking c. URL Rewriting In the following sections, we will discuss Cookies and Session Tracking. 22.8.1.1 Cookies A Cookie is a small message sent by a server to a client browser. The message is stored in the client browser. Whenever a client makes a request to the server which has sent the cookie, the cookie message is sent with the header of the HTTP request. The server reads the cookie message in the header of the request and identifies the client. A cookie will be returned only to the server which had created the cookie in the client’s browser. Therefore, the browser in the client may contain separate cookie for each of the web server to which it had made requests. A browser can store 20 cookies for each web server, 300 in all, each cookie of 4 kb size. G A Cookie is a small message sent by a server and stored in a client browser. A browser sends cookies only to the server which had created it. A cookie helps to identify a client by a server. A cookie contains a name, a value, expiry time, path, comment and version information. The servlet sends the cookie using the HttpServletResponse object. The cookie is defined in the javax.servlet.http.Cookie class. The constructor for the Cookie class is: Cookie(String name, String value) where, name is the name of the cookie, value is the value of the cookie. SERVLETS 689 Some of the methods defined in Cookie class are given in Table 22.4. Table 22.4 Some of the methods defined in Cookie class. Method Purpose of the method 1. String getComment() Returns the comment purpose of the cookie. describing the 2. int getMaxAge() Returns the maximum age of the cookie, specified in seconds. By default, -1 indicates that the cookie will expire when the browser is shut down. 3. String getName() Returns the name of the cookie. 4. String getPath() Returns the path of the server to which the browser return the cookie. 5. String getValue() Returns a string containing the cookie’s value. 6. void setComment(String purpose) Specifies the comment that describes the cookie’s purpose. 7. void setMaxAge(int expiryTime) Sets the maximum age specified in expiryTime in seconds. A positive value indicates that the cookie will expire after that many seconds. Negative value means that the cookie will be deleted when the web browser shuts down. A zero value causes the cookie to be deleted. 8. void setPath(String uri) Sets the path, specified in uri, for the cookie, to which the client should return the cookie. 9. void setValue(String value) Sets the value, specified in value, to the cookie, after it is created. Values should not contain white space, brackets, parentheses, equal signs, commas, double quotes, slashes, question marks, @ signs, colons and semi colons. A cookie is sent to the client through the HttpServletResponse object using the following method, defined in HttpServletResponse interface. void addCookie(Cookie cooki) 690 Programming in JAVA2 This method is to be called on the HttpServletResponse object before setting the content type and calling getWriter() method. A cookie returned by a HttpServeletRequest object using HttpServletRequest interface. browser can the following be obtained from method defined in Cookies[ ] getCookies() Returns an array containing all of the Cookie objects the client has sent with this request. Returns null if the request has no cookies. G 22.8.1.2 A Cookie is added to a browser using HttpServletResponse object. A Cookie is returned to the server by a browser through HttpServletRequest object. This Cookie helps a servlet to identify a client’s browser. Using Cookies In the following program 22.15 we will show how to add cookies to the response sent to the client and read cookies from the request sent from the client to the server. A client makes a request through the HTML document given in the program 22.16 to the servlet Cookiesrv. The servlet reads the request using getCookies() method. If no cookie is sent by the client, then the a new cookie is created with a name “name”, and with a value “sun” and attach it to the response using addCookie() method. A message is also sent to the client stating that a cookie is added to the client’s browser. If there are cookies in the request, then the servlet extract the cookie name and cookie value in to two arrays cname and cvalue, by calling getName() and getValue() methods on the Cookie object. Then the cookie name-value pair is returned to the client. Program 22.15 /* This program illustrates the use of Cookie in a servlet. If there is no cookie in the client a cookie is added otherwise this servlet reads the cookies returned by the client(browser) and display it to the user. somasundaramk@yahoo.com */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Cookiesrv extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException{ Cookie cki[]=null; String cname[] = new String[20]; String cvalue[] = new String[20]; //Read the cookies from the request cki = req.getCookies(); SERVLETS 691 // If no cookie is returned by the client, add a cookie to // this client if(cki==null ) { Cookie ck1 = new Cookie("name","sun"); ck1.setMaxAge(45678912); res.addCookie(ck1); } //otherwise read all the cookie and store them else{ for (int i=0;i<cki.length;i++) { cname[i]=cki[i].getName(); cvalue[i] = cki[i].getValue(); } } res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head><title>"+"Cookie Lesson"+" </title></ head>"); out.println("<body>"); out.println("<h1>Welcome to Cookie Lesson </h1>"); if(cki==null) { out.println("<p> You are visiting our site for the first time <p>" ); out.println("Have a good day<p>"); out.println(" A cookie is added to your browser <p>"); } else{ out.println("The following cookies are found in your browser<p>"); for(int i=0;i<cki.length;i++) out.println(cname[i]+ " " +cvalue[i]+"<p>"); } out.println("</body>"); out.println("</html>"); } } Program 22.16 <HTML> <HEAD> <TITLE>Cookie Lesson</TITLE> </HEAD> <BODY> <p><U>Welcome to Cookie</U></p> <FORM METHOD="GET" ACTION="Cookiesrv"> When you press Submit button<p> a cookie will be added to this browser<p> or if there is a cookie stored in your<p> browser , it will be displyed<p> So, try it out.<p> <INPUT TYPE="SUBMIT" VALUE= "Submit"> <INPUT TYPE="RESET" VALUE= "Reset"> </FORM> </BODY> </HTML> 692 Programming in JAVA2 The output screen, when the program 22.16 is executed through the browser is shown in Fig.22.24. Fig.22.24 Output screen when the program 22.16 is executed through Mozilla Firefox. The output screen for program 22.15 when the client browser sends the request to the server for the first time is shown in Fig.22.25(a). The output screen, when the client sends request for the second and subsequent time is shown in Fig.22.25(b). (b) (a) Fig.22.25 (a) Output screen produced by servlet program 22.15 when the client program 22.16 is invoked in the browser for the first time. (b) Output screen when the browser sends the request for the second and subsequent time to the servlet. SERVLETS 693 22.8.2 Session Tracking Session tracking is another method of identifying the clients by a server. In session tracking technique a client is remembered by the server only during a session. During a session a client may visit a website many times. When a session is over, i.e., when the browser is shutdown, the client identification is lost. In a cookie, a browser is identified till the cookie expires, which may span several sessions. Session tracking can be used where a browser do not accept cookies or cookies are disabled in the browser. In session tracking, a session object is created for every session created by the client browser. A session is built on top of cookies or URL-rewriting. A HttpSession object is obtained from HttpServletRequest object by calling getSession() method. A client ID is obtained from the HttpSession object. If the getSession() returns null, it means the client is starting a new session. The session objects have built-in data structure to store any number of attribute-value pair. G The attributes used in a session are remembered only during a session. All the data stored will be lost when the session expires. 22.8.2.1 HttpSession Interface The methods that can be called on an HttpSession object are defined in HttpSession interface. Some of the methods are given in Table 22.5. Table 22.5 Some of the methods defined in HttpSession Interface. All the methods may throw IllegalStateException. Method Purpose of the Method 1. Object getAttribute(String name) Returns the object bound with the specified name in this session, or null if no object is bound under the name. 2. Enumeration getAttributeNames() Returns an Enumeration of String objects specifying the names of all the objects bound to this session. 3. long getCreationTime() Returns a long, specifying when this session was created, measured in milli seconds, since 01-01-1970 GMT. 4. String getId() Returns a String containing the unique identifier assigned to this session. This identifier is assigned by the servlet container. 694 Programming in JAVA2 5. long getLastAccessedTime() Returns a long in milliseconds giving the last time the client has sent a request associated with the current session. 6. int getMaxInactiveInterval() Returns an integer specifying the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. After this interval, the servlet container invalidates this session. 7. void removeAttribute (String name) Removes the object bound with the specified name from this session. 8. void setAttribute(String name, Object value) Binds an object specified by the value to this session, using the specified name. 9. void setMaxInactiveInterval (int interval) Sets the time in seconds between client requests before the servlet container invalidates this session. A negative time indicates that the session should never time out. 22.8.2.2 Using Session In this section we will see how to use the HttpSession. The servlet given in program 22.17 creates two attributes for the session. One attribute named visitcount, stores the number of visits made by the user to this page. The second attribute, named author, stores the name of the author of the program, in the session. Whenever the user visits the page for second and subsequent time, the attribute values are displayed to the user. The getSession() method is called on the HttpServletRequest object to get the session. The session identification value is obtained by calling the getId() method on the session object. The visitcount value is set to 1 for the first time. This value is incremented by 1 whenever the client sends a request to the servlet. The values of the two attributes are returned by the client whenever the user visits this page for the second and subsequent visits. The setMaxInactiveInterval() is used to set the maximum inactive time for the user to use the browser to 10 seconds. When the user does not do any activity for 10 seconds, the session expires and all the values stored as attributes will be lost. To obtain the current time, the Date class in java.util package is used. The time at which the session was created is obtained by calling getCreationTime(). All the time values are in milliseconds since January 1970. The time at which the user visited this page last was obtained by calling the getLastAccessedTime() method. The current time is obtained by calling getTime() method on Date type object. SERVLETS 695 Program 22.17 /* This program illustrates the use of HttpSession in a servlet. If there are no session attributes,it creates two attributes. One attribute, named visitcount, counts the number of times the user visited this page in a session.The second attribute, named author, stores the name of the author of this program. If the user is not using the browser to visit this page for more than 10 seconds, the session expires and a new session is created.The values of the attributes are displayed when the user visits the page for the second and subsequent visits. somasundaramk@yahoo.com */ import java.util.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Sessionsrv extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException{ Date date; long createdtime,currenttime; int vcount=1; String sid, svcount,auname; HttpSession session; //Get the session object from the request session = req.getSession(true); // Get the session id for this session sid = session.getId(); // Find the current time date = new Date(); currenttime= date.getTime(); //Get the time of creation of this sesssion createdtime = session.getCreationTime(); // set maximum inactive time to 10 seconds session.setMaxInactiveInterval(10); // Get the attribute value with name visitcount svcount = (String)session.getAttribute("visitcount"); // Get the attribute value with name author auname= (String)session.getAttribute("author"); //Check if any attribute is already is set for this session if(svcount==null ) { session.setAttribute("visitcount",""+vcount); session.setAttribute("author","K.Somasundaram"); } else { vcount = Integer.parseInt(svcount) +1; session.setAttribute("visitcount",""+vcount); } res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head><title>"+"Seesion Tracking"+" </ title></head>"); 696 Programming in JAVA2 out.println("<body>"); out.println("<h1>Welcome to Session Tracking </h1>"); if(svcount==null) { out.println("You are visiting this page for the first time <br>" ); out.println("Have a good day<br>"); out.println("The session id is : "+sid+ "<br>"); out.println("Two attributes are created for this session <br>"); } else { out.println("The following information were taken from your browser<br>"); out.println("You are visiting this page for the "+vcount +" time<br>"); out.println("Author of this session is :"+auname +"<br>"); } out.println("The session was created at-: "+createdtime+"<br>"); out.println("Last time you visited at-----:" +session.getLastAccessedTime()+"<br>"); out.println("Current time in msec is-----:" +currenttime+"<br>"); out.println("If you are inactive for 10 seconds this seesion will expire <br>"); out.println("</body>"); out.println("</html>"); } } The program 22.18 shows the HTML document which is used to send the requests to the servlet sessionsrv. Program 22.18 <HTML> <HEAD> <TITLE>Session Tracking</TITLE> </HEAD> <BODY> <p><U>Welcome to Session Tracking</U></p> <FORM METHOD="GET" ACTION="Sessionsrv"> When you press the Submit button, a session will be created to this browser. If no attributes are avilable in the session two attributes are set. One attribute is used to count the number of visits made by the user to this page in this session. Another attribute sets the name of the author of the program. These two attributes will be read from the session and displayed when the user visits this page for the second and subsequent visits. The session will expire if the browser is inactive for 10 seconds or more.<p> Try it out.<p> <INPUT TYPE="SUBMIT" VALUE= "Submit"> <INPUT TYPE="RESET" VALUE= "Reset"> </FORM> </BODY> </HTML> SERVLETS 697 The output screen when the program 22.18 is called in the browser is shown in Fig.22.26. Fig.22.26 The output screen when the program 22.18 is viewed through the Mozilla Firefox browser. The output screen generated by program 22.17 when the submit button shown in Fig.22.26 is clicked for the first time is given in Fig.22.27. Fig.22.27 Output screen generated by the program 22.17 when the user visits the servlet for the first time. 698 Programming in JAVA2 The output screen, when the user visits the same page, by pressing the submit button (or reload option of the browser after seeing the first output from the servlet) for the third time, is given in Fig.22.28. Fig.22.28 Output screen generated by program 22.17 when the user visits this servlet page for the 3rd time (in a different session). After reading this chapter, you should have learned the following concepts: Ü Ü Ü Ü Ü Ü Ü POST and GET type requests. implementing doPost() and doGet() methods. writing HTML documents with POST and GET type requests. writing servlets in two tier architecture. deploying servlet and web components in Sun Java Application Server. writing servlets with Cookies. writing servlets for session tracking. In the next chapter, the basics of RMI is explained. SERVLETS 699 Worked out Problem-22 Problem: 22.1w It is required to maintain a telephone directory in a database and use it to find the address of a person. This system should contain two options one to add new numbers and another to find the address of a person if the phone number is given. Each record in the telephone directory contains the following details. Name Phone Number Address1 Address2 PIN State The design of this telephone directory system is done by dividing the whole problem into modules, in a client/server style. For this we have designed one HTML document maintdr.html, and three Servelets Select.java, Phoneadd.java and Phoneenq.java. The functional diagram of this system is shown in Fig.22.29. Server Add Enquiry Select.java Client.Add Client.Enquiry Select.java Select.java Client Maintdr.html Start Server Server Phoneadd.java Phoneenq.java Database Fig.22.29 Functional diagram for problem 22.W1. The function of each program and the sequence of execution of these programs are given below. 700 Programming in JAVA2 The HTML document maintdr.html given in program 22.19 when executed gives two options Add a new telephone number or Enquiry to find the address of a given phone number. It is the first program to be invoked. When the option is selected, it invokes Select.java. The servlet Select.java checks which option(Add or Enquiry) has been selected by the user and makes a branching to generate a client HTML document either for adding a new number or for making an enquiry. When the Add option is selected, the Phoneadd.java is invoked. The Phoneadd.java, receives a new phone entry with address and inserts it into a phone table of a database named phonesys, using JDBC. The control then takes the user to maintdr.html. For Enquiry option the Phoneenq.java is invoked, which receives a phone number and search for the address corresponding to that number and displays the result. The control then takes user to the maintdr.html. Program 22.19 maintdr.html <! Model html doc for writing Servlet> <HTML> <HEAD> <TITLE>eTelephone Directory</TITLE> </HEAD> <BODY> <p><U>SOMS ONLINE TELEPHONE DIRECORY </U></p> <FORM METHOD="GET" ACTION="Select"> <UL> <INPUT TYPE ="RADIO" NAME="request" VALUE="add" checked>ADD NEW NUMBERS<br> <INPUT TYPE ="RADIO" NAME="request" VALUE="enq">ENQUIRY<br> </UL> <INPUT TYPE="SUBMIT" VALUE= "Submit"> <INPUT TYPE="RESET" VALUE= "Reset"> </FORM> </BODY> </HTML> Program 22.20 /*------------------------------------------------This program receives data for the variable select from a client. It checks the value of select. If the value of select is "add" an HTML documnent for a client side is generated. If the value of select is "enq" an HTML document for telephone enquiry is generated. somaunsdramk@yahoo.com ----------------------------------------------------- */ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; SERVLETS 701 public class Select extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); // read the form data String selection ; selection=req.getParameter("request"); if(selection.equals("add")) {// add begins out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>eTelephone Directory</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<p><U>SOMS ONLINE TELEPHONE DIRECTORY </U></p>"); out.println("<p><U>ADD NEW NUMBER</U></p>"); out.println("<FORM METHOD=\"GET\" ACTION=\"Phoneadd\">"); out.println("<UL>"); out.println("<p> Name:<INPUT TYPE = \"text\"NAME= \"name\"></p>"); out.println("<p> Phone Number:<INPUT TYPE = \"text\" NAME = \"number\"></p>"); out.println("<p> Adress1:<INPUT TYPE = \"text\" NAME =\"adrs1\"></p>"); out.println("<p> Adress2:<INPUT TYPE = \"text\" NAME =\"adrs2\"></p>"); out.println("<p> PIN:<INPUT TYPE = \"text\" NAME =\"pin\"></p>"); out.println("<p> State:<INPUT TYPE = \"text\" NAME =\"state\"></p>"); out.println("<INPUT TYPE=\"SUBMIT\" VALUE= \"Submit\">"); out.println("<INPUT TYPE=\"RESET\" VALUE= \"Reset\">"); out.println("</FORM>"); out.println("</BODY>"); out.println("</HTML>"); } // add ends if(selection.equals("enq")) {// Enquiry begins out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>eTelephone Directory</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<p><U>SOMS ONLINE TELEPHONE DIRECTORY </U></p>"); out.println("<p><U>Enquiry For Address</U></p>"); out.println("<FORM METHOD=\"GET\" ACTION=\"Phoneenq\">"); out.println("<UL>"); out.println("<p>Type the Phone Number:<INPUT TYPE =\"text\" NAME =\"number\"></p>"); out.println("<INPUT TYPE=\"SUBMIT\" VALUE= \"Submit\">"); out.println("<INPUT TYPE=\"RESET\" VALUE= \"Reset\">"); out.println("</FORM>"); out.println("</BODY>"); out.println("</HTML>"); 702 Programming in JAVA2 }//Enqiry ends } } Program 22.21 /* This program receives telphone details of an user and stores it in a phone table of phonesys (of phonedbs) database. somasundaramk@yahoo.com */ import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class Phoneadd extends HttpServlet{ String pname,padrs1,padrs2,pnumber,pstate,spin; public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Read the parameter values pname = req.getParameter("name"); pnumber = req.getParameter("number"); padrs1 = req.getParameter("adrs1"); padrs2 = req.getParameter("adrs2"); spin = req.getParameter("pin"); pstate = req.getParameter("state"); Statement stm; ResultSet reset ; String sql,record1; try { // load the driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //establish connection Connection conect = DriverManager.getConnection("jdbc:odbc:phonesys"); // prepare the SQL statement stm = connect.createStatement(); record1 = "insert into phone(name, numb, adrs1, adrs2, pin, state)"; record1 +="values(\'"+pname+"\',\'"+pnumber+"\',\'"+padrs1 ; record1 += "\',\'"+padrs2+"\',\'"+spin+"\',\'"+pstate+"\')"; stm.executeUpdate(record1); // make the changes permanent conect.commit(); // prepare SQL to select all records in phone String select = "select * from phone"; reset = stm.executeQuery(select); out.println("<HTML><HEAD><TITLE>Phone add</ TITLE></HEAD>"); out.println("<BODY>"); out.println("<TABLE BORDER = \"1\">"); SERVLETS 703 out.println("<THEAD>The following record is added"); out.println("</THEAD>"); out.println("<TR><TH>Name</TH><TH>number</ TH><TH>Adrs1</TH>"); out.println("<TH>Adrs2</TH><TH>Pin</TH><TH>State</TR>"); // print the table out.println("<TBODY>"); out.println("<TR><TD>"+pname+"</TD>"); out.println("<TD>"+pnumber+"</TD><TD>"+padrs1+"</TD>"); out.println("<TD>"+padrs2+"</TD><TD>"+spin+"</ TD><TD>"+pstate+"</TD></TR>"); out.println("</TBODY>"); out.println("</TABLE>"); out.println("<p> </p>"); out.println("<FORM METHOD=\"GET\" ACTION = \"maintdr.html\">"); out.println("<INPUT TYPE=\"SUBMIT\" VALUE= \"Press to continue\">"); out.println("</FORM>"); out.println("</BODY></HTML>"); //close the statement and connection stm.close(); conect.close(); }catch(SQLException sqe){ out.println("Sql error"); }catch(ClassNotFoundException cnf){ out.println("Class Not found error "); } } } Program 22.22 /*-----------------------------------------------------This program receives telphone number and finds the address from the database somasundaramk@yahoo.com --------------------------------------------------------*/ import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class Phoneenq extends HttpServlet{ String pname,padrs1,padrs2,pnumber,pstate,spin; public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); //Read the parameter values pnumber = req.getParameter("number"); PreparedStatement pstm; int rec; ResultSet reset ; try { // load the driver 704 Programming in JAVA2 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //establish connection Connection conect = DriverManager.getConnection ("jdbc:odbc:phonesys"); // prepare SQL to select the record where the received // phonenumb == phone number in phone table String select = "select * from phone where numb = ?"; pstm = conect.prepareStatement(select); pstm.setString(1,pnumber); reset = pstm.executeQuery(); out.println("<HTML><HEAD><TITLE>Phone Enquiry</TITLE></HEAD>"); out.println("<BODY>"); out.println("<TABLE BORDER = \"1\">"); out.println("<THEAD><h2>Address of the phone number</h2> "); out.println("</THEAD>"); out.println("<TR><TH>Name</TH><TH>number</TH><TH>Adrs1</TH>"); out.println("<TH>Adrs2</TH><TH>Pin</TH><TH>State<TH></TR>"); // Print the table out.println("<TBODY>"); rec=0; while(reset.next()) { rec +=1; pname= reset.getString("name"); pnumber = reset.getString("numb"); padrs1 = reset.getString("adrs1"); padrs2 = reset.getString("adrs2"); spin = reset.getString("pin"); pstate = reset.getString("state"); out.println("<TR><TD>"+pname+"</TD>"); out.println("<TD>"+pnumber+"</TD><TD>"+padrs1+"</TD>"); out.println("<TD>"+padrs2+"</TD><TD>"+spin+"</ TD><TD>"+pstate+"</TD></TR>"); } if(rec==0) out.println("<p><h2>Sorry thers is no such number in the directory</h2></p>"); out.println("</TBODY>"); out.println("</TABLE>"); out.println(""); out.println("<FORM METHOD=\"GET\" ACTION=\"maintdr.html\">"); out.println("<INPUT TYPE=\"SUBMIT\" VALUE= \"Press to continue\">"); out.println("</FORM>"); out.println("</BODY></HTML>"); //close the statement and connection pstm.close(); conect.close(); }catch(SQLException sqe){ out.println("Sql error"); }catch(ClassNotFoundException cnf){ out.println("Class Not found error "); } } } SERVLETS The output screen when maintdr.html is executed given in Fig. 22.30 Fig.22.30 Output screen for program 22.19. (a) 705 706 Programming in JAVA2 (b) Fig.22.31 Output screen for program 22.20 when the submit button in program 22.19 (Fig.22.30) is clicked for Add option. (a) Initial Screen (b) After the user filled in the data Fig.22.32 Output screen for program 22.21 when the Submit button of program 22.20(Fig 22.31(b)) is clicked. SERVLETS (a) (b) Fig.22.33 Output screen for program 22.20 when Submit button of program 22.19 is clicked for Enquiry option. (a) Initial Screen (b) After the data is filled in. 707 708 Programming in JAVA2 Fig.22.34 Output screen for Program 22.22 when Submit button of program 22.20(Fig.22.33(b)) is clicked. * * * * * * SERVLETS 709 Exercise–22 I. Fill in the blanks : 22.1 22.2 22.3 22.4 22.5 22.6 22.7 22.8 22.9 22.10 22.11 22.12 22.13 22.14 22.15 22.16 22.17 II. Servlets are __________ side programs. The methods init(), service() and destroy() defined in servlet interface are called as ________ methods. The types of HTTP requests are _________ and _________. The most commonly used methods in HttpServlet class are ________ and ________ . The components of web application like HTML document, servlet are to be packed in a package called _________ file. The requests going from a client to a servlet are embedded in _______ documents. The HttpResponse object is created by the __________ . A servlet program is executed by the _______ . The ________ method of HTML is to get data from the Server. The _______ method of HTML is to send data to the server. To create a servlet, _________ class is to be subclassed. The ________ is a stateless protocol. _________ is a small message sent by a server and stored in a client. _______ is a sequence of request-reply between a server and a client, until the client stops the request. ________ , ________ and ________ helps a server to identify a client. Using ________ multiple sessions can be tracked. Using ________ only a single session can be tracked. Write Servlet and Clients for the following: 22.18 22.19 22.20 22.21 A mark list containing Name, RegNo and marks for Maths, Physics and Chemistry for 5 students are given. A student will be declared as “PASS” when the marks of Maths, Physics and Chemistry are 40 or more otherwise as “FAIL”. Write client side HTML program to input data one student at a time. When the data for 5 students are over, the servlet must display result in a table form with Name, Reg.No. and Result. Write a Servlet/client programs to input the student details as given in problem 22.18 and store them in “mark-rec” table of a database. Write a Servlet / Client to read the student details from the database created in problem 22.9 and declare the results as given in problem 22.18. Write a Servlet/Client programs to store the data in a file named “student.dat”. * * * * * * 710 Programming in JAVA2 BLANK Remote Method Invocation 711 Chapter 23 REMOTE METHOD INVOCATION (RMI) Remote Method Invocation(RMI) mechanism enables methods in one machine to call on a Java object residing in another machine. An RMI system looks like a client-server architecture and they differ in their functionality compared to the normal client-server configuration. The basic concept of RMI and the different steps involved in creating an application using RMI are explained in this chapter. We have seen in the previous chapters how Java methods were called on objects residing in the same machine. Java also provides a mechanism to call a method of an object residing at a remote machine. This mechanism is known as Remote Method Invocation(RMI). The remote machine executes the method and returns a result. The object that calls the method acts like a client and the object in the remote machine that executes the method and returns the result acts like a server. Thus, using Java an application distributed across several machines can be developed. An RMI differs from the conventional client/server in its operation. In the conventional client/server, the request are sent through an intermediate layer, like HTTP request, whereas in RMI, one Java object directly communicates with another Java object in a remote machine through a remote method. In this chapter we briefly explain how to create an application using RMI. 712 Programming in JAVA2 23.1 Creating an RMI Application In an RMI system, the server which provides the service, register its service and location in a register called RMI Registry. A client which needs the service, first looks at the RMI registry and finds the location of the server which contains the object that provides the required service. The client then calls the method on the object residing in the remote machine. The remote object carry out the required process and returns the result to the client. The client-server architecture of RMI is shown in Fig.23.1. (1) Server (remote object) ^ RMI Registry Registering ) ) (3 (4 st ue q Re rep ly Finding the location of the server (2) ^ ^ Fig.23.1 ^ Client RMI Architecture. The numbers 1 to 4 inside the parenthesis give the sequence of activities in making a remote method call. The steps involved to create an application using RMI are given below. 1. 2. 3. 4. 5. 6. 7. 8. 9. Create an interface. Create a server class by implementing this interface. Create a class to register the server with a RMI registry. Create a client class that calls a method defined in the interface and implemented in the server class. Compile the classes. Run the RMI compiler. Start the RMI registry. Run the Server program Run the Client program In the following sections each step is explained in detail. To illustrate each step, we consider a problem. The problem is to check whether the given number is a prime number or not. A number is called as prime number, if it can be divided without a remainder by 1 and by that number only. The client calls the method on the object in the remote server(object). The server checks whether the number is prime or not and returns a reply to the client. Now we will see how to create this client/server application. Remote Method Invocation Step 1 : 713 Create an Interface To create an RMI application, an interface has to be declared. This interface contains a method which a client can make use of. This interface has to extend Remote class defined in java.rmi package. Any class that implements this interface can be used to create a remote object. Any method defined in this interface becomes a remote method and it can throw RemoteException. For our problem the Ifprime.java given in program 23.1 is the interface. Program 23.1 /* This is an interface that extends the class Remote. Any class that implements Remote can create a remote object. This interface is the first step to create a RMI application. somasundaramk@yahoo.com */ import java.rmi.*; public interface Ifprime extends Remote{ String Checkprime(int n)throws RemoteException; } This interface defines a remote method Checkprime(). This method takes an int as parameter and returns a String type. This Checkprime() method can throw RemoteException. The next step is to create a server class. Step 2 : Create a server class The server class is created by implementing the interface Ifprime. This class must extend the UnicastRemoteObject class defined in java.rmi.server package. This inheritance is necessary to make a link with the RMI system. When a class extends UnicastRemoteObject class, it must define a no argument constructor that throws RemoteException. This constructor must call the super class constructor. This process invokes code in the UnicastRemoteObject that makes RMI linking and remote object initialization. By this process the remote object starts listening and ready to accept calls from clients. The program 23.2 shows how the interface is implemented. Program 23.2 /* This is a server program that acts as a remote object and the Checkprime method in it will check if the argument passed to it is a prime number or not and return an appropriate message. somasundaramk@yahoo.com */ import java.rmi.*; 714 Programming in JAVA2 import java.rmi.server.*; public class Srvprime extends UnicastRemoteObject implements Ifprime { int i; boolean test = true; public Srvprime() throws RemoteException{;} public String Checkprime(int gn){ for(i=2;i<gn ;i++) if( gn%i ==0 ) return gn + " is not a prime number"; return gn+" is a prime number"; } public static void main(String args[]){ try{ Srvprime svp = new Srvprime(); Naming.bind("Srvprime",svp); System.out.println("Srvprime bound"); }catch(Exception e){ System.out.println("Error in Srvprime"); } System.out.println("Srvprime End"); } } This program implements the Checkprime() method which tests whether the given number is prime or not and returns a string message. Step 3 Register the Server The next step is to create a class to register the RMI server with an RMI Registry. In our case, the registering is done in the main() method of the program 23.2. For this, bind() method of the Naming class is called. Only when a server is registered with the RMI registry, the client can look for the service and identify the remote object. Step 4 Create the Client The next step is to create a client program. This program first locates the remote object on which it can call the remote method. For this purpose it calls lookup() method of the Naming class. The lookup() method requires an URL that specifies the server hostname and the required service(object). The URL takes the following form: rmi://<host-name>[<service-port-no>]/<service-name> where, host-name is the name recognized on the network, and the service-portno is the port on which the service is running. The default port number is 1099. Remote Method Invocation 715 In our example the client is given in program 23.3. It first finds the address of the local host as we are going to keep the remote object also in the same machine. Then it constructs the URL. Then it calls lookup() method and gets a reference for the remote object. Then it reads an int type supplied by the user and calls the Checkprime() method to test whether the given number is prime or not. Program 23.3 /* This is a client program of RMI application. In this a user is asked to input an integer. Checkprime method of the remote method is called to check whether the given number is prime or not. somasundaramk@yahoo.com */ import java.rmi.*; import java.net.*; import java.io.*; public class Cliprime { public static void main(String args[])throws Exception{ Ifprime ifp; String answer=""; InputStreamReader ins = new InputStreamReader(System.in); BufferedReader br= new BufferedReader(ins); InetAddress ia= InetAddress.getLocalHost(); String ip = ia.toString().substring(ia.toString().indexOf('/')+1); String url = "rmi://"+ip+"/Srvprime"; System.out.println("Check wether the number is prime or not"); System.out.println("Type an int to test for Prime:"); ifp = (Ifprime)Naming.lookup(url); String sn= br.readLine(); int n = Integer.parseInt(sn); System.out.println( ifp.Checkprime(n)); } } Step 5 Compile the classes We will assume that all the classes, Ifprime.java, Srvprime.java and Cliprime.java are in the same directory, say c:\jdk1.2.4\bin\rmi. Set the classpath and compile all the java programs using javac compiler. Step 6 Run the RMI Compiler Now run the RMI compiler by issuing following command. C:\jdk1.2.4\bin\rmi>rmic Srvprime This command Srvprime_stub.class. will create two files Srvprime_skel.class and 716 Programming in JAVA2 Step 7 Start the RMI Registry From now on the execution of the RMI application begins. RMI registry by issuing the following DOS command. C:\jdk1.2.4\bin\rmi>start Now start the rmiregistry A new window will appear. Minimize it. Step 9 Run the Server Now run the server program Srvprime, by using the java command: C:\jdk1.2.4\bin\rmi>java Srvprime The output of running this program is shown in Fig.23.2. second active DOS Window. Fig.23.2 This is the Output screen for program 23.2. Now open another DOS window and run the client program. Step 10 Run the Client This is the last step of this RMI application. is run by using the java command: The client program Cliprime C:\jdk1.2.4\bin\rmi>java Cliprime This is the third active DOS window. The output screen after running the Cliprime is shown in Fig.23.3(top). The output screen, when the user types the number 13 is shown in Fig.23.3(bottom). Remote Method Invocation Fig.23.3 717 Output screens for program 23.3. Top: Initial Output Bottom: Output when the user typed 13 23.2 Running the Client from a different directory The application can be executed, by running the client in a different directory of the same computer. For this, copy the Ifprime.class, Cliprime.class and Srvprime_stub.class to a new directory, say d:\APTITUDE, and run the client program. The output screen is shown in Fig.23.4. Fig.23.4. Output screen for program 23.3 when it is run in another directory of the same machine. 718 Programming in JAVA2 To develop an RMI application, a remote interface is to be created, by extending Remote class. G A server class is created by implementing the remote interface and extending the UnicastRemoteObject class. A remote object is to be registered to an RMI registry, using bind() method of Naming class. An RMI Client identifies the remote object using lookup() method of Naming class. After reading this chapter you should have learned the following concepts: Ü How an RMI functions Ü How to create a remote interface Ü How to create an RMI server class Ü How to create an RMI client Ü How to compile and run an RMI application in the same computer. In the next Chapter some of the utility classes are explained. * * * * * * Remote Method Invocation 719 Exercise–23 I. Fill up the blanks 23.1 23.2 23.3 23.4 The first step in developing an RMI application is to define an ———. A remote interface must extend __________ class. The classes that implement remote _______ can create remote object. A server class has to subclass __________ class to produce a remote object. 23.5 In order to make known about the availability of a remote object to the clients it must be _____ to the RMI registry. 23.6 Registering of a remote server is done using ________ method of ________ class. 23.7 The client is able to locate the availability of a server using the _________ method. II. Write a program to the following problem 23.8 It is required to sort the given double type array in descending order. The client will pass the given array as parameter to the remote method. The remote object must sort the array and return the sorted array to the client. Write an RMI application for this. * * * * * * 720 Programming in JAVA2 BLANK Chapter 24 UTILITY CLASSES There are a number of utility classes available in Java2. These utilities help to carry out certain task like finding the date, time, getting input from console, formatting the output etc. The most useful classes for a beginner to get input from the console are Scanner and Console. We discuss four classes, GregorianCalendar, Scanner and Formatter defined in java.util and Console defined in java.io which are useful for general applications, in this chapter. Java has a number of utility classes that can be used for various applications, like processing the time, days, months and years in a calendar, generating random num bers, formatting the output etc. These classes are contained in a package java.util of J2SE. More and more classes are being added in every release of J2SE which enables programmers to write codes easily. For example, the Scanner class introduced in J2SE5, helps the 722 Programming in JAVA2 developers to write simple statements to get an input from a console or a file. Perhaps this is one of the most useful feature of the J2SE5(JDK1.5). To make console based input / output easier a new useful class Console is introduced in J2SE6(JDK1.6) and is packaged in java.io. In this chapter, we discuss four classes, GregorianCalendar, Scanner and Formatter defined in java.util and Console class defined in java.io. 24.1 GregorianCalendar Class GregorianCalendar is a subclass of Calendar class. This class can be used to handle calendar systems. It supports Julian and Gregorian calendar systems. The GregorianCalendar class has the following fields which are constants. They can be used as parameters in the get() and set() methods defined in the GregorianCalendar class. Some useful constants are : int AM - Value of AM_PM field indicating the period of the day from midnight to just before noon. int AM_PM - Field number for get() and set() methods indicating whether the HOUR is before or after noon. E.g.: at 10:04:15 PM, the AM_PM is PM . int JANUARY ( FEBRUARY to DECEMBER is also available) - Value of the MONTH field indicating the first month of the year. This value is available for all the remaining 11 months. int DATE - Field number for get() and set() methods, indicating the day of the month. It is synonym for DAY_OF_MONTH . int DAY_OF_MONTH - Field number for get() and set() methods, indicating the day of the month. int DAY_OF_WEEK - Field number for get() and set() methods, indicating the day of the week. This field takes value from SUNDAY to SATURDAY . int DAY_OF_YEAR - Field number for get() and set() methods, indicating the day number within the current year. The first day of the year is 1. int HOUR - Field number for get() and set() methods, indicating the hour of the morning or afternoon. HOUR is used for the 12 hour clock, 0 to 11. Noon and midnight are Utility Classes 723 represented by 0. E.g., 10:04:15 PM, the HOUR is 10. int HOUR_OF_DAY - Field number for get() and set() methods, indicating the hour of the day in 24 hour clock. E.g. at 10.04:5 PM, the HOUR_OF_DAY is 22. int MINUTE - Field number for get() and set() methods, indicating the minute within the hour. E.g. at 10:04:15 PM, the MINUTE is 4. int MONDAY (to SUNDAY) - Value of the DAY_OF_WEEK field indicating Monday (to Sunday). int MILLISECOND - Field number for get() and set() methods, indicating the millisecond within the second. int MONTH - Field number for get() and set() methods, indicating the month. First month of the year is JANUARY which is 0. int PM - Value of the AM_PM field indicating the period of the day from noon to just before midnight. int SECOND - Field number for get() and set() methods, indicating the second within the minute. long time - The currently set time for this calendar expressed in milliseconds since January 1, 1970. int YEAR - Field number for get() indicating the year. int WEEK_OF_YEAR - Field number for get() and set() methods, indicating the week number within the year. and set() methods, Constructors Some of the constructors used to create the objects are: 1. GregorianCalendar() Constructs a default GregorianCalendar using the current time in the default time zone. 2. GregorianCalendar(int year, int month, int dayOfMonth) Constructs a GregorianCalendar with the given data set in the default time zone, where, 724 Programming in JAVA2 year - the value used to set the YEAR field. month - the value used to set the MONTH field. dayOfMonth - the value used to set the DAY_OF_MONTH field. Methods Some of the methods defined in the GregorianCalendar and the inherited methods are : int get(int field) Returns the value of the given calendar field. void set(int field, int value) Sets the given calendar field to the given value. boolean isLeapYear(int year) Returns true if the given year is a leap year. TimeZone getTimeZone() Gets the time zone. G The MONTH field take values from 0 for Jauary to 11 for December. In the following program 24.1, the use of some of the fields and methods are illustrated. Program 24.1 /* This program illustrates the use of some of the fields and methods defined in GregorianCalendar. somasundaramk@yahoo.com */ import java.util.*; class Calndr{ public static void main(String args[]){ String smonth; GregorianCalendar cal = new GregorianCalendar(); System.out.println(" YEAR: " + cal.get(cal.YEAR)); int month = cal.get(cal.MONTH); switch(month){ case 0:smonth="0-January"; break; case 1:smonth="1-February"; break; case 2:smonth="2-March"; break; case 3:smonth="3-April"; break; case 4:smonth="4-May"; Utility Classes 725 break; case 5:smonth="5-June"; break; case 6:smonth="6-July"; break; case 7:smonth="7-August"; break; case 8:smonth="8-September"; break; case 9:smonth="9-October"; break; case 10:smonth="10-November"; break; case 11:smonth="11-December"; default : smonth= "month not defined "; } System.out.println(" MONTH: " + smonth); System.out.println(" WEEK_OF_YEAR: " + cal.get(cal.WEEK_OF_YEAR)); System.out.println(" WEEK_OF_MONTH: " + cal.get(cal.WEEK_OF_MONTH)); System.out.println(" DATE: " + cal.get(cal.DATE)); System.out.println(" DAY_OF_MONTH: " + cal.get(cal.DAY_OF_MONTH)); System.out.println(" DAY_OF_YEAR: " + cal.get(cal.DAY_OF_YEAR)); System.out.println(" DAY_OF_WEEK: " + cal.get(cal.DAY_OF_WEEK)); System.out.println(" AM_PM: " + cal.get(cal.AM_PM)); System.out.println(" HOUR: " + cal.get(cal.HOUR)); System.out.println(" HOUR_OF_DAY: " + cal.get(cal.HOUR_OF_DAY)); System.out.println(" MINUTE: " + cal.get(cal.MINUTE)); System.out.println(" SECOND: " + cal.get(cal.SECOND)); System.out.println(" MILLISECOND: " + cal.get(cal.MILLISECOND)); } } The above program gives the follwoing ouput. YEAR: 2007 MONTH: 1-February WEEK_OF_YEAR: 7 WEEK_OF_MONTH: 3 DATE: 11 DAY_OF_MONTH: 11 DAY_OF_YEAR: 42 DAY_OF_WEEK: 1 AM_PM: 0 HOUR: 11 726 Programming in JAVA2 HOUR_OF_DAY: 11 MINUTE: 40 SECOND: 0 MILLISECOND: 875 24.2 Scanner Class The Scanner class is added in JDK1.5. This class provides methods that can be used to get input from console and files. This class enables the user to get input from console in the simplest form compared to the classes defined in java.io packages. The Scanner breaks the input string into tokens(words) using a delimiter, which by default is a white space. Each token can be parsed and can be converted to its basic types. The tokens can be inspected to look for a particular type and read. You need to use JDK1.5 or higher version to use this class. Constructors The constructors defined in the Scanner class are : Scanner(File source) throws FileNotFoundException Constructs a new scanner that produces values scanned from the specified file. Bytes from the file are converted into character using the underlying platforms default character set. Scanner(Inputstream source) Constructs a new scanner that produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the underlying platform’s default character set. Scanner(Inputstream source, String charsetName) Constructs a new scanner that produces values scanned from the spcified input stream. Bytes from the stream are converted into characters using the specified character set. Scanner(String source) Constructs a new scanner that produces values scanned from the specified string. Scanner(ReadableByteChannel, source) Constructs a new scanner that produces values scanned from the specified channel. Bytes from the source are converted into characters using the underlying platform’s default character set. Scanner(ReadableByteChannel source, String charsetName) Constructs a new scanner that produces values scanned from the specified channel. Bytes from the source are converted into characters using the spcified character set. Utility Classes 727 Scanner(Readable source) Constructs a new scanner that produces values scanned from the specified source. Methods The Scanner class has a number of methods. Some of them are: void close() Closes this scanner. Pattern delimiter() Returns the pattern this scanner is using to match delimiters. String findLine(Pattern pattern) Attempts to find the occurence of the speicified pattern ignoring delimiters. If the pattern is found before the next line separator, the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is detected in the input up to the next line separator, then null is returned and the scanner’s position is unchanged. String findLine(String pattern) Attempts to find the next occurence of the specified string, ignoring delimiters. boolean hasNext() Returns true if the scanner has another token in its input. boolean hasNext(String pattern) Returns true if the next token matches the pattern specified in the string. boolean hasNextBoolean() Returns true if the next token in this scanner’s input can be interpreted as a boolean value using a case insensitive pattern created from the string “true/false”. String next() Find and returns the next complete token from this scanner. String next(String pattern) Returns the next token if it matches the pattern specified in the string. boolean nextBoolean() Scans the next token of the input into a boolean value and returns the value. byte nextByte() Scans the next token of the input as a byte. 728 Programming in JAVA2 byte nextByte(int radix) Scans the next token of the input as a byte using the specified radix. double nextDouble() Scans the next token of the input as a double. float nextFloat() Scans the next token of the input as a float. int nextInt() Scans the next token of the input as an int. int nextInt(int radix) Scans the next token of the input as an int using the specified radix. String nextLine() Advances this scanner past the current line and returns the input that was skipped. long nextLong() Scans the next token of the input as a long. long nextLong(int radix) Scans the next token of the input as a long using the specified radix. short nextShort() Scans the next token of the input as a short. short nextShort(int radix) Scans the next token of the input as a short using the specified radix. int radix() Returns this scanner’s default radix. Scanner skip(String pattern) Skips the input that matches a pattern specified in the string. Scanner useDelimiter(String pattern) Sets the scanner’s delimiting pattern to the pattern specified in the string. Scanner useRadix(int radix) Sets this scanner’s default delimiter. G The Scanner breaks the input string into tokens. Each token can be inspected and parsed. Utility Classes 729 24.2.1 Scanning a String within the program In the following program 24.2 we show how to use the methods defined in the Scanner class. The input for the scanner is defined inside the program itself. In the first part of the program, the given input string is scanned and the total tokens in the string is counted. The next() method takes the scanner past the token. When all the tokens are counted, the scanner has reached past all the tokens and therefore no scan process can further be done on this scan object. Therefore, to illustrate other methods of the Scanner class, another scanner object scan1 is created and other methods are called on the scanner object scan1. Program 24.2 /* This program illurstates some of the methods defined in the Scanner class. To run this program jdk1.5 or higher version is needed. somasundaramk@yahoo.com */ import java.util.*; class Scandemo{ public static void main(String args[]){ String txt= "37 true 78.9 is embedded in this text"; Scanner scan = new Scanner(txt); int tokencount=0; while(scan.hasNext()) { scan.next(); tokencount++; } System.out.println("The total tokens in the input is: " +tokencount); scan.close(); //doing other operations for the same input Scanner scan1 = new Scanner(txt); System.out.println("The integer in the input is: " +scan1.nextInt()); System.out.println("The boolean in the input is: " +scan1.nextBoolean()); System.out.println("The double in the input is: " +scan1.nextDouble()); System.out.println("The remaining part is: " +scan1.nextLine()); scan1.close(); } } The above program gives the following output. The total tokens in the input is: 8 The integer in the input is: 37 The boolean in the input is: true 730 Programming in JAVA2 The double in the input is: 78.9 The remaining part is: is embedded in this text 24.2.2 Scanning a Console Now, we will write another program in which a data is obtained from the console. The standard input, console(key board), is referred as System.in. The program 24.3 takes an int(n) from the console and computes the first n Fibonacci numbers(F 0=1, F 1=1; F n = F n-1 + F n-2). Program 24.3 /* This program finds the Fibonacci numbers between 1 and the given number. This program needs JDK 1.5 or above to compile. somasundaramk@yahoo.com */ import java.util.*; class Conscan{ public static void main(String args[]){ int fib1=1,fib2=1,fib3 ; int n; int fibn; Scanner scan = null; scan = new Scanner(System.in); System.out.println("How many Fibonacci numbers?"); fibn=scan.nextInt(); System.out.println("The first "+fibn +" Fibonacci numbers are: "); System.out.println(fib1+"\n"+fib2); for (n = 3; n<=fibn ; ++n) { fib3=fib1+fib2; System.out.println(fib3); fib1=fib2; fib2=fib3; } } } The above program gives the following output. How many Fibonacci numbers? 12 The first 12 Fibonacci numberse are: 1 1 2 3 5 Utility Classes 731 8 13 21 34 55 89 144 24.2.3 Scanning a File Disk files can also be handled using Scanner class. We have already seen in chapter 13, how files were handled in FileInputStream and FileOutputStream classes in java.io package. In the following program 24.4, we will show how files are read using Scanner class. The file “stu.dat” has four fields, register_no, name, mark1 and mar2 with a white space as delimiter between them. The program reads the file and display them on the screen. Program 24.4 /* This program reads data from a file "stu.dat" using Scanner class. To run this program jdk1.5 or higher version is needed. somasundaramk@yahoo.com */ import java.util.Scanner; import java.io.*; class Filescan{ public static void main(String args[]){ int regno,mark1,mark2; String name; File fin; try{ fin = new File("stu.dat"); Scanner fscan = new Scanner(fin); System.out.println("The default delimiter = " +fscan.delimiter()); //read the file System.out.println("The following data are read from the file\n"); System.out.println("Reg.No\t Name \t\t Mark1 \t Mark2\n"); while(fscan.hasNext()) { regno = fscan.nextInt(); name = fscan.next(); mark1 = fscan.nextInt(); mark2 = fscan.nextInt(); // print the file System.out.println(regno+"\t"+name+"\t"+mark1+"\t"+mark2); } }catch(IOException fnf){ 732 Programming in JAVA2 System.out.println("The file stu.dat is not found"); } } } The above program gives the following output. The default delimiter = \p{javaWhitespace}+ The following data are read from the file Reg.No Name Mark1 Mark2 1001 1002 1003 1004 S.Magesh S.P.Kumar K.Ramesh M.Manoj 95 85 65 85 85 75 75 75 24.3 Formatter Class The Formatter class defined in java.util package helps to format the basic type data sent to the output stream. This class is available from JDK1.5 onwards. It contains flags, conversion characters, width and precision specifiers. They are like the conversion specifier in C language. For example to specify an integer output, the character ‘d’ is used and to format a floating point number the character ‘e’ or ‘f’ is used. For numerical data, even the precision, the required number of digits after the decimal point can be specified. 24.3.1 Format Syntax The conversion and the related format specifier are generally categorised in the following six types. 1) 2) 3) 4) 5) 6) General Character - may be applied to any argument type may be applied to basic types which represent Unicode characters: char, Character, byte, Byte, short, Short. Numeric i) Integral - may be applied to integral types : byte, Byte, short, Short, int, Integer, long, Long. ii) Floating point - may be applied to floating point types: float, Float, double, Double. Date/Time - may be applied to types which are capable of encoding a date or time: long, Long, Calendar and Date. Percent (%) - produces a literal Line separator(%n)- produces a line separator The format specifiers for general, character and numeric types have the following syntax: Utility Classes 733 %[argument_index$][flags][width][precision]conversion Those items written within [] are optimal. argument_index - is a decimal integer indicating the position of the argument in the argument list. The first argument is represented by 1$, the second by 2$, etc. flags - is a set of characters that modify the output format. width - is a non-negative decimal integer, indicating the minimum number of characters to be written to the output. precision - is a none-negative decimal integer usually used to restrict the number of characters. The specific depends on the conversion. conversion - is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument’s data type. The format specifiers for date and time have the following syntax: %[argument_index$} [flags][width] conversion The conversion is to be preceeded by ‘t’ or ‘T’. 24.3.2 Conversion Characters for Numeric Type The conversion characters for general and numberic type are given in Table 24.1. Table 24.1 Argument type Conversion Characters for general and numeric type Conversion Character Result general b or B If the argument is null then the result is false. If the arg is a boolean then the result is the string returned by String.valueOf(), otherwise the result is true. general s or S The result is formatted as a string. character c or C The result is a unicode character. integer d The result integer. is formatted as a decimal 734 Programming in JAVA2 integral 0 The result is formatted as an octal integer. integral x or X The rsult is formatted as an hexadecimal integer. floating point e or E The rsult is formatted as number in scientific notation. a decimal floating point f The result is formatted as number in fractional form. a decimal floating point g or G The rsult is formatted as a decimal number in scientific notation or in fractional form. floating point a or A The result is formatted as a hexadecimal floating-point. date/time t or T Prefix for characters. percent % The result is a literal. line separator n The result is a line separator. date and time conversion 24.3.3 Conversion Characters for Date and Time Time Some of the Conversion characters used for formatting time are: H - Hour of the day for the 24-hour clock formatted as two digits i.e. 00-23. I - Hour for the 12-hour clock formatted as two digits i.e. 01-12 K - Hour of the day for 24-hour clock, i.e. 0-23 l - Hour of the day for 12-hour clock, i.e. 1-12 M - Minutes within the hour formatted as two digits, i.e. 00-59 S - Seconds within the minute formatted as two digits, i.e. 00-60 p - am or pm z - abbreviation for time zone. Date The conversion characters used for formatting Date are: B - Full name of the month, e.g. January b - Abbreviated name of the month, e.g. Jan A - Full name of the day, e.g. Monday Utility Classes a - Short name of the day, e.g. Mon Y - Year formatted to 4 digits, i.e. 2007 y - Last two digits of the year, i.e. 07 j - Day of the year, formatted as three digits, i.e. 001-366 m - Month formatted as two digits, i.e. 01-12 d - Day of month, formatted as two digits, i.e. 01-31 e - Day of month, formatted as two digits, i.e. 1-31 735 Date & Time The Conversion characters used for formatting common date/time are: R Time formatted for the 24-hour clock as “%tH : %tm” T Time formatted for the 24-hour clock as “%tH : % tM : % tS” r Time formatted for the 12-hour clock as “%tI : %tM : %tS %tp” D Date formatted as mm dd yy F ISO 8601 date formatted as yyyy mm dd c Date and time formatted as “%ta %tb %td %tT %tz %ty” e.g. “Sun Jul 20 16 : 17:00 EDT 1969” Flags Flags that modify the formatted output generated by the Conversion characters are: - The rsult is left justified. Applicable to all types of Conversions. # The rsult is conversion dependent alternate form Applicable to general, integral and floating point types. + The rsult will always include sign Applicable to numeric types. blank Include a leading space. 0 Include a leading zero Applicable to numeric types , Include a “ , ” separator. Applicable to numeric types. ( Include a parenthesis for negative numbers. numeric types. Applicable to 736 Programming in JAVA2 G The Conversion specifiers for date and time are to be prefixed with t or T. Constructors Some of the constructors defined in Formatter class are: Formatter() Constructs a new formatter. Formatter(File file) throws FileNotFoundException Constructs a new formatter with the specified file as the destination for this formatter. Formatter(PrintStream ps) Consntructs a new formatter with the specified print stream as the destination for this formatter. Formatter(OutputStream os) Constructs a new formatter with the specified output stream as the destination for this formatter. Methods Some of the methods defined in this class are : Locale locale() Returns the locale set by the construction of this formatter. Appendable out() Returns the destination for the output. String toString() Returns the result of invoking the toString() method on the destination for the output. void flush() Flushes this formatter. Flushing a formatter writes any buffered output in the destination to the underlying stream. void close() Closes this formatter. Formatter format(String format, Object args) Writes a formatted string to this objects destination using the specified format for the argument args. Utility Classes format - args - 737 is a format string as specified in the format specification syntax. arguments for which formatting has been done. 24.3.4 Formatting numbers Now we will show how the various conversion characters are used to format the output. Program 24.5 shows some of the conversion characters used for formatting int type, double tpe and String type. We make five Formatter objects form1 to form5 which do not have any output stream. Each object is used to format the output using format() method. The formatted result is converted to a string using toString() method and sent to System.out and printed using println method. In form1 object, formatting is done for three double types. The specifier 5.3f tells that the output is to be in atleast 5 column width, out of which 3 digits must appear after decimal point and ‘f’ indicates that the number is to be printed in fractional form. In the specifier +7.2e, ‘+’ is a flag indicating that the sign symbol + or - must appear before the number, the output is to be in atleast 7 column width, out of which 2 digits must appear after decimal point, and e indicates the number is to be printed in scientific notation. The conversion character ‘n’ indicates that a new line is to be created. Using form3 object, the printing order is changed using the argument index, for three int type variables p, q and r. In the specifier 3$5d, 3$ refers to te third argument r, 5 indicates that the output is to be printed in atleast 5 column width and d indicates that this is a decimal integer. Similarly in the specifier 2$5d, the 2$ referes to the second argument q. Using form4 object the integer p is formatted in three different formats. The specifier d indicates that the number is to be printed in decimal integer. In the second specifier #x, x tells that the number is to be formatted as hexadecimal number, and the flag “#” produces OX as prefix. In the third specifier #0, 0 indicates that the integer is to be formatted as octal number and the flag # produces a prefix 0 to the number. Program 24.5 /* -----------------------------------------------------This program illustrates the use of the converion specifiers in Formatter to format numbers and string. This needs jdk1.5 or higher version. somasundaramk@yahoo.com ----------------------------------------------------------- */ import java.util.*; class Fmtnum{ public static void main(String args[]){ double a=22/7.0; double b=-3.23455e12; 738 Programming in JAVA2 double c = 76.23456; int p=45678, q= 78934, r= 986; String name= "Dr.K.Somasundaram"; //create Formatter objects Formatter form1,form2,form3,form4,form5; form1 = new Formatter(); form2 = new Formatter(); form3 = new Formatter(); form4 = new Formatter(); form5 = new Formatter(); // Format the numbers using format. + flag is for sign form1.format(" a = %5.3f b = %+7.2e c = %5.2f%n",a,b,c); //Convrt the Formatter object to string , using toString() //and print the string System.out.println(" Printed using Formatter " +form1.toString()); //format another argument form2.format("Printed using Formatter. Math.PI = %5.3f%n", Math.PI); System.out.println(form2.toString()); form3.format("Rearranged print order: r = %3$5d q = %2$5d p = %1$5d %n",p,q,r); System.out.println(form3.toString()); // The # flag is to represent the number in proper format form4.format("The int %d converted to hexadecimal is %#x%n and in octal form is %#o ", p,p,p); System.out.println(form4.toString()); form5.format(" The string name is: %s",name); System.out.println(form5.toString()); } } The above program gives the following output. Printed using Formatter a = 3.143 b = -3.23e+12 c = 76.23 Printed using Formatter. Math.PI = 3.142 Rearranged print order: r = 986 q = 78934 p = 45678 The int 45678 converted to hexadecimal is 0xb26e and in octal form is 0131156 The string name is: Dr.K.Somasundaram 24.3.5 Formatting Output to Console In the previous section we have seen how an output is formatted independent of a destination stream. Now we will see how to format an output meant for an output stream System.out, the display console. In program 24.6, a Formatter object form is created by passing System.out as argument. Hence when an output is formatted by calling the format() method, the output is sent to the System.out automatically and no println method is needed. The same object is used for sending any number of output. In the last format, only one Utility Classes 739 argument p is given, but we obtain three outputs. This is done by specifying 1$ for all the three conversion specifiers, indicating that the first argument is to be formatted. Program 24.6 /* -----------------------------------------------------This program illustrates the use of Formatter class. This Formatter is used to format the output meant for the standarad output System.out. You can use the same object for all your console output. This needs jdk1.5 or higher version. somasundaramk@yahoo.com ----------------------------------------------------------- */ import java.util.Formatter; class Fmtout{ public static void main(String args[]){ double a = 22/7.0; double b = -3.23455e12; double c = 76.23456; int p = 45678; String name = "Dr.K.Somasundaram"; //create a Formatter object for System.out Formatter form = new Formatter(System.out); //Print a message .No need to use println form.format("Formatter for System.out%n%n"); //Format the numbers and print. Note the + flag form.format("a = %3.2f b = %+7.2e c = %5.2f%n%n",a,b,c); //use the same Formatter to print another result form.format("Printing a String :%s%n%n",name); form.format("The int %1$d in hex form is %1$#x%n%n and in octal form is %1$#o%n",p); form.close(); } } The above program gives the following output. Formatter for System.out a = 3.14 b = -3.23e+12 c = 76.23 Printing a String :Dr.K.Somasundaram The int 45678 in hex form is 0xb26e and in octal form is 0131156 24.3.6 Formatting Date and Time In this section some of the conversion characters used for formatting date and time are illustrated. In program 24.7 an object gc of GregorianCalendar class is created. This object gc is formatted in various forms using the conversion characters defined for date and time. All the output is sent to the standard output System.out. 740 Programming in JAVA2 Program 24.7 /* -----------------------------------------------------This program shows how to format the Date and Time using the convesrion specifiers defined in Formatter. Date and time are obtained from the GregorianCalendar object. This program needs jdk1.5 or higher version. somasundaramk@yahoo.com ----------------------------------------------------------- */ import java.util.Formatter; import java.util.GregorianCalendar; class Fmtdate{ public static void main(String args[]){ GregorianCalendar gc = new GregorianCalendar(); // create a Formatter object for System.out Formatter form = new Formatter(System.out); // Print a message .No need to use println form.format("Formatter for Date and Time using System.out%n"); // 1. Date from day, month and year from calendar int dd = gc.get(gc.DAY_OF_MONTH); int mm = gc.get(gc.MONTH)+1; //Jan is 0 and hence 1 is added int yy = gc.get(gc.YEAR); form.format("Date assembled: %d:%d:%d %n", dd,mm,yy); // 2. Date using e,m,y conversions form.format("Date using e,m,Y converions: %1$te:%1$tm:%1$tY%n", gc); // 3. Date using D conversion form.format(" Date using D conversion : %tD%n",gc); // 4. Date using F conversion form.format(" Date using F conversion : %tF%n",gc); // 5. Date using c conversion form.format(" Date using c conversion : %tc%n",gc); // 1. Time from hour,minute and second int h= gc.get(gc.HOUR); int m= gc.get(gc.MINUTE); int s= gc.get(gc.SECOND); form.format("Time Assembled : %d:%d:%d%n",h,m,s); // 2. Time using R conversion form.format(" Time using R conversion : %TR%n",gc); // 3. Time using T conversion form.format(" Time using T conversion : %TT%n",gc); // 4. Time using r conversion form.format(" Time using r conversion : %Tr%n",gc); form.close(); } } The above program gives the following output. Formatter for Date and Time using System.out Utility Classes 741 Date assembled : 27:2:2007 Date using e,m,Y converions : 27:02:2007 Date using D conversion : 02/27/07 Date using F conversion : 2007-02-27 Date using c conversion : Tue Feb 27 08:14:33 IST 2007 Time Assembled : 8:14:33 Time using R conversion : 08:14 Time using T conversion : 08:14:33 Time using r conversion : 08:14:33 AM 24.4 Console Class This Console Class is added in the java.io package in J2SE6. It has methods that help read / write package in J2SE6. It has methods that help on the console. The console refers to the standard input System in, the key board and standard output System.out, the monitor. One of the methods printf() defined in Console class helps to format the output similar to C language. Those who are used to C language will find this memthod as more convenient than using the Java’s traditional println() method. A Console type object is obtained by calling the System.Console() method. There is no constructor for this class. Methods The methods defined in Console class are: void flush() Flushes the console and forces and buffered output to be written immediately. Console format(String fmt, object args) Writes a formatted string to this console’s output stream using the specified format string and arguments, where fmt - is a format string as defined in Format string syntax args - are the arguments referred in fmt. Console printf(String fmt, Object args) Writes a formatted string to this console’s output stream using the specified format string and arguments, where fmt - is a format string as defined in Format string syntax, args - are the arguments referred in fmt. Both format() and printf() methods behave in the same way. Reader reader() Retrieves the unique Reader object associated with this console. 742 Programming in JAVA2 String readLine() Reads a single line of text from the console. String readLine(String fmt, Object args) Provides a formatted prompt, then reads a single line of text from the console. Char[] readPassword() Reads a password from the console without echoing. Char[] readPassword(String fmt, Object args) Provides a formatted prompt then reads a password from the console without echoing. PrinteWriter writer() Retrieves the unique PrintWriter object associated with this consolve. G 24.4.1 The format() and printf() methods give the same result. The printf() is a convenient method. Using readPassword, format and printf Methods We illustrate some of the methods defined in Console class in the following program 24.8. First the System.console() method is called to create the Console object as no constructor is defined for this Console class. The format() and printf() methods give the same result. However printf() method has a close resembelence to the conventional println() method and is recommended for use than the format() method. The readLine() and printf() methods do not throw any exception, unlike in the other classes in java.io package. Program 24.8 /* -----------------------------------------------------This program illustrates the use of some of the methods defined in Console class contained in java.io package to handle input and output. This program needs jdk1.6 or higher version. somasundaramk@yahoo.com ----------------------------------------------------------- */ import java.io.Console; class Consnum{ public static void main(String args[]){ double a=22/7.0; double b=-3.23455e12; double c = 76.23456; double weight; Utility Classes 743 int p=45678, q= 78934, r= 986; String name ,sweight; char psword[] = new char[35]; //get Console instance Console con = System.console(); // Read a line of text name=con.readLine(" Type in your name:"); //read a Password field psword=con.readPassword(" Password:"); //convert char[] to String String pword= new String(psword); // Get the weight in string form sweight = con.readLine(" Type in your weight in kg:"); weight = Double.parseDouble(sweight); // Print the name string using printf con.printf(" Printed using printf : %s%n",name); // Print the name string using format con.format(" Printed using format : %s%n",name); con.printf(" Your Password is : %s%n",pword); con.printf("Your weight is : %5.2f %s %n",weight,"Kg"); //Print the numbers using format. The + flag is for sign con.format("a = %5.3f b = %+7.2e c = %5.2f%n", a,b,c); con.printf("Rearranged print order: r = %3$5d q = %2$5d p = %1$5d %n", p,q,r); } } The above program gives the following output: Type in your name:S.Magesh Password: Type in your weight in kg:59.5 Printed using printf : S.Magesh Printed using format : S.Magesh Your Password is : mag007 Your weight is : 59.50 Kg a = 3.143 b = -3.23e+12 c = 76.23 Rearranged print order: r = 986 q = 78934 p = 45678 24.4.2 Using reader and writer methods In the following program 24.9, we show how to use the reader() and writer() methods. The reader() method returns a Reader type object and is used to read input. The writer() method returns a PrintWriter object and is used for output. By calling the methods defined in these objects the required input / output process is done. 744 Programming in JAVA2 Program 24.9 /* -----------------------------------------------------This program illustrates the use reader() and writer() methods defined in Console class to handle input and output. This program needs jdk1.6 or higher version. somasundaramk@yahoo.com ----------------------------------------------------------- */ import java.io.Console; import java.io.Reader; import java.io.PrintWriter; import java.io.IOException; class Conspwr{ public static void main(String args[]){ double a=22/7.0; double b=-3.23455e12; double c = 76.23456; double weight; int p=45678, q= 78934, r= 986; String name=null ,sweight, pword=null; char cname[] = new char[30]; char cweight[] = new char[5]; char psword[] = new char[35]; // get the Console instance Console con = System.console(); PrintWriter out = con.writer(); Reader in = con.reader(); // read a char array as name try{ out.printf(" Type in your name :"); in.read(cname); name= new String(cname); // read a Password field with a prompt psword=con.readPassword(" Password:"); pword= new String(psword); // read the weight in char array form out.printf(" Type in your weight in Kg:"); in.read(cweight); }catch(IOException ioe){;} sweight= new String(cweight); weight = Double.parseDouble(sweight); out.printf(" Your name is : %s%n",name); out.printf(" Your Password is : %s %n",pword); out.printf("Your weight is:%5.2f %s %n",weight,"Kg"); // The + flag is for sign out.printf("a = %5.3f b = %+7.2e c = %5.2f%n", a,b,c); out.printf("Rearranged print order: r = %3$5d q = %2$5d p = %1$5d %n", p,q,r); } } The above program gives the following output. Utility Classes 745 Type in your name :S.Magesh Password: Type in your weight in Kg :59.5 Your name is : S.Magesh Your Password is : mag007 Your weight is : 59.50 Kg a = 3.143 b = -3.23e+12 c = 76.23 Rearranged print order: r = 986 q = 78934 p = 45678 After reading this chapter you should have learned the following concepts. Ü using GregorianCalendar for finding time and date related values. Ü doing read operations using Scanner class and distinquish from java.io classes. Ü formatting the output bound data using conversion characters for numeric, string, date and time values using Formatter class. Ü using C language like printf() method defined in Console class. Workedout problem–24 Problem 24w1 Given the date of birth of a person, find the day of the week in which the person was born. Use a Scanner class to obtain the date of birth. Program 24.1w /* This program finds the day of the week for the given date of birth of a person. somasundaramk@yahoo.com */ import java.util.*; import java.io.Console; class Prob241{ public static void main(String args[]){ String sdob, salute,name; int day,month,year,ampm; Scanner in = new Scanner(System.in); Console con = System.console(); 746 Programming in JAVA2 GregorianCalendar gcal = new GregorianCalendar(); // Read the name of the user con.printf(" Type in your name: "); name = in.nextLine(); // Find out whether it is AM or PM of the day ampm = gcal.get(gcal.AM_PM); switch(ampm){ case 0: salute = " Good Morning"; break; case 1: salute = " Good Evening"; break; default: salute = " Good day"; } con.printf("%s %s%n ",salute,name); // Read the date of birth in a single line con.printf("Type in your date of birth as dd mm yyyy:"); sdob = in.nextLine(); // Separate the single line text into day, month, and year Scanner indob= new Scanner(sdob); day = indob.nextInt(); month = indob.nextInt()-1;// Jan is 0 year = indob.nextInt(); // Create a Calendar for that year GregorianCalendar dobcal = new GregorianCalendar(year, month,day); // Find the day using the date conversion specifers con.printf("You were born on %TA" , dobcal); } } The above program gives the following output: Type in your name: S.Magesh Good Morning S.Magesh Type in your date of birth as dd mm yyyy: 24 07 1990 You were born on TUESDAY * * * * * * Utility Classes 747 Exercise-24 Fill in the blanks 24.1 The GregorianCalendar class supports __________ and _________ calendar Systems. 24.2 The MONTH field takes the value from ___________ to ___________ . 24.3 The time in the calendar system is calculated since _________ . 24.4 The default delimiter in Scanner class is __________ . 24.5 The scanner breaks the input string into _________ . 24.6 The scanner can be used for output process (True/False) 24.7 The character in between % and # in a format specifier represents __________ . 24.8 The conversion specifiers for date and time must be prefixed by _______ or _______ . 24.9 The conversion specifier %#x formats the argument integer in _______ form with ______ as prefix. 24.10 The printf and format() methods produce _________ result in the output. Write programs for the following problems 24.11 Write a program to get the address of a person and print it out on the console, using Scanner and Console Class. 24.12 Find the log10(x) of x from 1.0 to 10.0 and print out x and log10(x) as a table. The log values are to be with exactly 4 decimal digits. (Use Mathe.log10(x) method to find log) 24.13 A mark list with the following details is given. Reg.No. : integer Name : string Maths : integer Physics : integer Chemistry : integer Write a program to input data for 10 students using Scanner class, find the average mark for each student and store it in a file using Formatter class. The average mark contains only one decimal digit. * * * * * * 748 Programming in JAVA2 REFERENCE BOOKS 1. Core Java, Volume 1 - Fundamentals, C.S. Horstmann and G. Cornell, Pearson Education Asia Pvt. Ltd., New Delhi, India, 2004. 2. http://java.sun.com 3. Inside the Java Virtual Machine, Bill Venners, Tata McGraw-Hill Edition, New Delhi, 1998. 4. J2EE 1.4, The Big Picture, Solveig Haugland et al, Pearson Education, New Delhi, 2005. 5. Java2 Mastering the JFC, Volume II : Swing, D.M. Geary, Sun Microsystems, 3rd Edition, Addison Wesley Longman, Singapore, 1999. 6. Java2 Programming, Black Book, Steven Holzener et al, Paraglyph Press / dreamTech Press, New Delhi, 2006. 7. Teach Yourself, J2EE in 21 Days, Martin Bond et al., Pearson Education, Second Edition, New Delhi, 2005. 8. The Complete Reference Java2, Herbert Schildt, Tata McGraw Hill, Fifth Edition, New Delhi, 2003. Answer to Questions 749 Answer to Questions Exercise-1 1.1 Encapsulation, inheritance and polymosphism 1.2 Encapsulation 1.3 Class 1.4 Class 1.5 Safe 1.6 True 1.7 Operating system 1.8 Applet, operating system 1.9 Application Program Interface (API) 1.10 Class 1.11 Independent 1.12 Software Exercise-2 2.1 Literals 2.2 Ox 2.3 Octal 2.4 Do not depend 2.5 8 2.6 char 2.7 Block 2.8 Mat-value, float, 1class 2.9 double 2.10 Escape sequence 2.11 Null 2.12 double Exercise-3 3.1 Of { and } 3.2 ; 3.3 Main 3.4 3 3.5 int 3.6 Type casting 3.7 Block 3.8 Block 3.9 Class 3.10 Not be 3.11 float Exercise-4 4.1 4 4.2 3 4.3 1.5 4.4 50 4.5 Invalid 4.6 False 4.7 >>> 4.8 True 4.9 True 4.10 True Exercise-5 5.1 Branching 5.2 Nested 5.3 Many 5.4 Literal 5.5 do...while 5.6 Beginning 5.7 True 5.8 False 5.9 Loop, switch 5.10 Break Exercise-6 6.1 Like typed 6.2 Object 6.3 new 6.4 Variable 6.5 Not required Exercise-7 7.1 Class 7.2 Class 7.3 Object 7.4 Instance 7.5 new, reference 7.6 Object reference variable 7.7 Reference 7.8 Dot(.) 7.9 Constructor 7.10 True 7.11 Instance variable or constructor 750 7.12 7.13 Programming in JAVA2 Overloading Data type Exercise-8 8.1 extends 8.2 super 8.3 false 8.4 Overloading 8.5 Overriding 8.6 Overloading, overriding methods 8.7 final 8.8 final 8.9 static 8.10 static 8.11 static 8.12 abstract 8.13 abstract Exercise-9 9.1 Class 9.2 Same 9.3 import 9.4 Access modifier 9.5 protected 9.6 Package 9.7 Package 9.8 java.lang 9.9 Interfaces 9.10 Without 9.11 final 9.12 Implemented 9.13 Any 9.14 abstract Exercise-10 10.1 basic 10.2 Can 10.3 Number 10.4 java.lang 10.5 parseByte() Exercise-11 11.1 java.lang 11.2 ceil() 11.3 floor() Exercise-12 12.1 Exception 12.2 RuntimeException 12.3 Error, not to 12.4 finally() 12.5 Sub 12.6 Throwable 12.7 throws 12.8 Checked Exercise-13 13.1 byte, character 13.2 False 13.3 FileInputStream, FileOutputStream 13.4 ByteArrayInputStream, ByteArrayOutputStream 13.5 Filter 13.6 Serialization 13.7 CharArrayReader, CharArrayWriter 13.8 byte, character 13.9 True 13.10 flush Exercise-14 14.1 String 14.2 StringBuffer 14.3 java.lang 14.4 is Not 14.5 equals 14.6 16 14.7 The number of characters in it 14.8 Length + 16 14.9 Freezed, string Exercise-15 15.1 Multitasking 15.2 Multithreading 15.3 Thread 15.4 Runnable 15.5 run() 15.6 new 15.7 start() 15.8 Blocked Answer to Questions 15.9 15.10 15.11 15.12 15.13 One synchronized synchronized Operating system Lower Exercise-16 16.1 Applet, application 16.2 Byte code 16.3 Web browser 16.4 java.applet.Applet 16.5 Graphics 16.6 main 16.7 Applet tag, HTML 16.8 init() 16.9 stop() 16.10 destroy() 16.11 Codebase 16.12 Documentbase Exercise-17 17.1 Window 17.2 Panel, Frame 17.3 Panel, Frame 17.4 Closed 17.5 drawPolyline() 17.6 X0RMode 17.7 style Exercise-18 18.1 Mouse 18.2 Source 18.3 Delegation event 18.4 Listener 18.5 Register, source 18.6 requestFocus() 18.7 Adapter 18.8 All 18.9 addTypeListener() Exercise-19 19.1 Java Foundation Classes (JFC) 19.2 JFrame, JApplet, JDialog, JWindow 19.3 19.4 19.5 19.6 19.7 19.8 19.9 19.10 19.11 19.12 19.13 19.14 19.15 19.16 19.17 751 ContentPane False True Layout manager One Two List of items A part One, one Can not, can JList and JTextField Prevents JOptionPane JFileChooser JProgressBar Exercise-20 20.1 Internet Protocol 20.2 Four 20.3 Domain name 20.4 Domain Name System 20.5 Connection 20.6 Connectionless 20.7 Waits 20.8 Port 20.9 End 20.10 DatagramPacket 20.11 Uniform Resource Locator 20.12 Protocol Exercise-21 21.1 All 21.2 Link or bridge 21.3 Four 21.4 Connection 21.5 Class.forName() 21.6 Protocol name, sub-protocol, subname 21.7 Statement 21.8 PreparedStatement or CallableStatement 21.9 CallableStatement 21.10 ResultSet 752 Programming in JAVA2 Exercise-22 22.1 22.2 22.3 22.4 22.5 22.6 22.7 22.8 22.9 22.10 22.11 22.12 22.13 22.14 22.15 Server life cycle GET, POST doPost() doGet() WAR HTML Web Server Web Server GET POST HTTPServlet HTTP Cookie Session Cookie, Session tracking and URL rewriting 22.16 Cookie 22.17 Session tracking Exercise-23 23.1 23.2 23.3 23.4 23.5 23.6 23.7 interface Remote interface UnicastRemoteObject Registered bind(), Naming lookup() Exercise-24 24.1 24.2 24.3 24.4 24.5 24.6 24.7 24.8 24.9 24.10 Julian, Gregorian 0 to 11 Jan, 1970 white space tokens false argument index t, T hexadecimal, OX same * * * * * * Index 753 INDEX Symbols 12-hour clock 734 A abs() 180 absolute() 634 abstract class 129 Abstract Classes 3, 128 abstract method 129 Abstract Window Toolkit 369 AbstractButton 450 accept() 539, 587, 589 Access Modifier 140 acos() 180 ActionEvent 450, 452, 459, 542 ActionEvent Class 404 ActionEvent class methods 405 ActionPerformed() 445 actionPerformed() 504, 527, 530, 543, 552 Adapter class 421, 422 Adapter Classes 421 add() 432, 441, 512, 513, 556 addActionListener() 415, 438, 485, 504, 511, 512, 539 addAdjustmentListener() 415, 475 addCaretListener() 500 addChangeListener() 549 addComponentListener() 414 addCookie() 689, 690 addElement() 468 addItem() 504 addItemListener() 415, 504 addKeyListener() 414 addLayoutComponent() 556, 568 addListSelectionListener() 464, 474 addMenuDragMouseListener() 511 addMouseListener() 414 addMouseMotionListener() 414 addSeparator() 512 addWindowListener() 414 AdjustmentEvent Class 405 afterLast() 634 ALIGN 355 ALT 354 AM_PM 722, 723 anonymous inner class 436 API 6 append() 289, 496 Applet Basics 343 Colors 356 HTML Pages 363 Images 361 Information 352 Interfaces 358 Methods 347, 351 Multimedia 358 Applet class 347 Applet Tag 353 applets 6, 343 appletviewer 345, 346 application programs 6 Architecture Neutral 5 ARCHIVE 354 Arcs 376 ArithmeticException 205, 214 Array Initialization 73 Multi-dimensional 74 One-Dimensional 71 two-dimensional 75 ArrayIndexOutOfBoundsException 202, 205, 214 asin() 179 atan() 180 audio clip 359 automatic promotion 22 available() 224, 246 AWT 344, 369, 429 AWTEvent class 402 B BASIC 1 block statement 24 blocked state 313 Boolean Class 172 boolean literals 13 boolean type 16 booleanValue() 172 BorderLayout 555 constructors 556 methods 556 bound() 718 break Statement 59 break statement 49 brighter() 384 browser 351 BufferedInputStream 232 BufferedOutputStream 234 BufferedReader 264 BufferedWriter 265 ButtonGroup 459, 460, 565 byte 14 Byte Class 156 Byte Stream 223 754 Programming in JAVA2 ByteArrayInputStream 228 ByteArrayOutputStream 230 byteValue() 156 C C 1, 89 Call Level Interface 609 CallableStatement 616 methods 631 CallableStatement Interface 630 canExecute() 221 canRead() 220 canWrite() 220 capacity() 289 CardLayout 567, 568 constructors 568 methods 568 Using 569 CaretListener 500 caretUpdate() 500 catch block 201, 203 cbrt() 181 ceil() 180 CGI 655 ChangeEvent 450, 452, 459 char 15 Character Class 170 character literals 12 character stream 253, 255 characters 15 CharArrayReader 255, 256 CharArrayWriter 257 charAt() 282, 289 CharToByte Converter 261 charValue() 170 child thread 314 Circles 375 Class 2, 89 ClassCastException 214 Classes 87 ClassNotFoundException 213 CLASSPATH 661 clear() 468 clearRect() 372 clickCount() 411 Client Socket 587 client/server 711 CloneNotSupportedException 213 close() 224, 225, 241, 246, 254, 259, 261, 587, 588, 597, 616, 617, 634, 727, 736 CODE 354 CODEBASE 354 Color Methods 384 Color Class 382 Color class 356 color disc 396 comma Statement 64 Comments 21 commit() 616, 625 compareTo method 285 compareTo() 157, 159, 161, 163, 166, 168, 171, 283 Component 356 component events 407 ComponentEvent Class 407 compound interest 108 concat() 284 connect() 597, 603 Connection Interface Creating Statements 615 Connection interface methods 616 connection–oriented 586 connectionless 595 Console 722, 738, 742 methods 741 Console Class 741, 742 constructor 93 constructors 433, 726 Container methods 556 ContentPane 432 continue Statement 62 Control Panel 617 control statements 43 conversion 733 Conversion Characters % 734 0 733 A 734 a 735 a or A 734 B 734 b 733, 734 c 733, 735 D 735 d 733, 735 e 735 e or E 734 F 735 f 734 g or G 734 H 734 I 734 j 735 K 734 l 734 M 734 m 735 n 734 p 734 R 735 r 735 S 734 Index 755 s 733 T 735 t or T 734 Time 734 x or X 733 Y 735 y 735 z 734 Cookie 659, 688, 689 Cookie() 688 Cookies 688 copy() 496 copySign() 181 cos() 179 Cos(x) 65, 106 cosh() 181 Cosh(x) 150 create() 381 createDialog() 524, 527, 539 createStatement() 616, 622 cube root 181 currentThread() 308, 316 cut() 497 DNS 585 do..while Statement 54 doGet() 658, 670, 672, 673, 674 Domain Name System 585 doPost() 658, 672, 673, 674 DOS 266 DOS command 716 double 12, 13, 15 Double Class 168 double-precision 12 doubleValue() 156 drain() 241 draw3DRect() 372 drawArc() 376 drawImage() 361 drawLine() 370 drawOval() 375 drawPolygon() 378, 380 drawPolyline() 379, 380 drawRect() 371 drawRoundRect() 371 DriverManager 614, 617 methods 614 D E darker() 384 database 607 Datagram 595 DatagramPacket 595 constructors 595 methods 595 DatagramSocket 595 constructors 596 methods 596 DataInputStream 234, 236, 683 DataOutputStream 237, 683 date of birth 745 DB Protocol 610 DBMS 607 decimal integer 11 DefaultComboBoxModel 503 DefaultListModel 468 methods 468 delete() 220, 289 deleteCharAt() 290 deleteOnExit() 220 deleteRow() 634 delimiter() 727 Deployment Tool 665, 666, 668 Deployment tool 663 destroy() 347, 657, 658 differential equation 193 digital clock 366 disconnect() 597 Disk File Handling 225 dispose() 519 E 179 Echo-Server 591 echoCharIsSet() 494 Encapsulation 1, 2 endsWith() 283 ensureCapacity() 289 Enumeration 693 Equality operator 279 equals method 279, 280 equals() 157, 161, 163, 166, 168, 172, 282, 288, 584 equalsIgnoreCase() 282 Error 200, 210 escape sequence 12 event 402 event handling 401 Event Listeners 413 Event Model 401 EventObject 402 Exceptions 199, 200, 205 Broadcasting 210 Checked 213 Rethrowing 207 Unchecked 213 subclass 205 execute() 617, 622, 627 executeQuery() 617, 622, 627, 629 executeUpdate() 617, 622, 627 exists() 220 exp() 180 extends 113 756 Programming in JAVA2 F Factorial 314 factorial 106, 123 Fibonacci numbers 340 File Class 219 methods 219 FileInputStream 225 FileNotFoundException 225 FileOutputStream 225, 227 FileReader 264 FileWriter 262, 263 fill3DRect() 372 fillArc() 376 fillOval() 375 fillPolygon() 378 fillRect() 372 fillRoundRect() 372 FilterInputStream 231, 232, 234 FilterOutputStream 231, 234 final class 119 final method 120 final variable 122 finalize() 123 finally 201 finally Block 212 finally block 201 findLine() 727 first() 569, 634 firstElement() 468 Flags ' 735 # 735 ( 735 + 735 - 735 0 735 blank 735 flags 733 float 12, 13, 15 Float Class 165 floating point literals 12 floating point numbers 15 floatValue() 156 floor() 180 FlowLayout 558, 559 constructors 559 methods 559 FlowLayout manager 445 flush() 225, 238, 254, 261, 736, 741 flushBuffer() 659 Font Methods 391 Font class 389 Fonts 389 for .. Statement 55, 56 for loop 58 FORM 684 format specifiers 733 character 732 date 733 general 732 numeric types 732 time 733 format() 736, 738, 741, 742 Formatter 722 constructors 736 methods 736 Formatter Class 732 Formatting Date 739 Formatting numbers 737 forName() 622 FORTRAN 1, 89 Frame class 369, 373, 419 FTP 586 G Garbage Collection 122, 123 GenericServlet 658 GET 669, 670, 674, 680 get() 722, 724 getAbsolutePath() 219 getActionCommand() 405, 438, 445, 504, 511, 530 getAddress() 584, 595 getAdjustable() 406 getAdjustableType() 406 getAlignment() 559 getAllByName() 584 getAlpha() 384 getAppletInfo() 351, 352 getApproveButtonText() 540 getAttribute() 693 getAttributeNames() 693 getAudioClip() 358, 360 getAvailableFontFamilyNames() 389 getBackground() 357 getBigDecimal() 631, 634 getBlockDecrement() 475 getBlockIncrement() 475 getBlue() 384 getBoolean() 635 getBufferSize() 659 getByName() 584 getByte() 631, 635 getBytes() 282 getCaretPosition() 497 getChars() 282, 289 getCodeBase() 351, 357 getColumns() 485, 497, 563 getComment() 689 getComponent() 407 getConnection() 614, 622 getContent() 602, 604 getContentLength() 604 getContentPane() 432, 438, 444, 519 Index getContentType() 604, 659 getCookies() 659, 690 getCorner() 479 getCreationTime() 693, 694 getCurrentDirectory() 540 getData() 596 getDate() 604, 631, 635 getDocumentBase() 351, 357 getDouble() 631, 635 getDriver() 614 getEchoChar() 494 getElementAt() 468 getEncoding() 259, 261 getFamily() 391 getFile() 601 getFileFilter() 540 getFilePointer() 251, 252 getFirstVisibleIndex() 465 getFloat() 631, 635 getFontName() 391 getForeground() 357 getFreeSpace() 221 getGreen() 384 getHeight() 434 getHelpMenu() 513 getHgap() 556, 559, 563 getHorizontalAlignment() 448 getHorizontalScrollBar() 480 getHorizontalScrollBarPolicy() 480 getHost() 601 getHostAddress() 584 getHostName() 584 getHSBColor() 385 getIcon() 438, 448, 453, 511, 524 getID() 402 getId() 693, 694 getImage() 358, 361 getInetAddress() 587, 588, 597 getInputStream() 588, 604 getInt() 632, 635 getItem() 408 getItemAt() 504 getItemCount() 504, 512 getItemSelectable() 408 getKeyChar() 410 getKeyCode() 409 getKeyModifierText() 410 getKeyText() 410 getLastAccessedTime() 694 getLastModified() 604 getLastVisibleIndex() 465 getLength() 596 getLineCount() 497 getLineWrap() 497 getLocalAddress() 588, 597 getLocalGraphicsEnvironment() 389 getLocalHost() 584 getLocalPort() 587, 588, 597 757 getLong() 632, 635 getMaxAge() 689 getMaximum() 475, 549 getMaxInactiveInterval() 694 getMaxRows() 617 getMenu() 513 getMenuCount() 513 getMessage() 524 getMetaData() 627, 635 getMinimum() 476, 549 getModifier() 405 getName() 219, 301, 391, 540, 689, 690 getOrientation() 476, 549 getOutputStream() 588, 604, 660 getParameter() 351, 355, 659, 670, 675, 677, 683 getParameterInfo() 351 getParameterNames() 659, 677, 678, 680 getParameterValues() 659, 677, 678, 680 getParent() 219 getPath() 219, 689 getPercentComplete() 549 getPort() 595, 597, 601 getPriority() 309 getProtocol() 601 getRed() 384 getResultSet() 617, 622 getRGB() 384 getRow() 635 getRows() 497, 563 getSelectedFile() 543 getSelectedFiles() 540 getSelectedIndex() 465, 504 getSelectedItem() 504 getSelectedText() 485, 497 getSelectedValue() 465 getSelectedValues() 465 getSelectionEnd() 497 getSelectionStart() 497 getServerName() 659 getServletConfig() 657 getServletInfo() 658 getSession() 659, 693, 694 getSize() 391, 468, 474 getSoTimeout() 587 getSource() 474, 530 getStateChange() 408 getStatement() 636 getString() 549, 632, 636 getStyle() 391 getText() 438, 448, 453, 485, 497, 511 getTime() 694 getTimeZone() 724 getTitle() 433, 519 getTotalSpace() 221 getUnitIncrement() 476 getURL() 603 getUsableSpace() 221 getValue() 407, 476, 524, 549, 689, 690 758 Programming in JAVA2 getVerticalAlignment() 448 getVerticalScrollBar() 480 getVerticalScrollBarPolicy() 480 getVgap() 556, 559, 563 getVisibleRowCount() 465 getWidth() 434 getWindow() 413 getWriter() 660, 670, 690 getX() 411, 434 getXXX() 630 getY() 411, 434 GIF 361 GIF image 362 GlassPane 432 Graphics 369 Colors 382 Graphics class 361, 369, 391 Graphics Clip 381 GraphicsEnvironment 389 GraphicsEnvironment class 389 GregorianCalendar 721, 722, 724, 739 methods 724 GregorianCalendar Class 722 GridLayout 562 constructors 562 methods 563 GUI 401 H hashCode() 156 hasNext() 727 hasNextBoolean() 727 heavy-weight process 299 HEIGHT 354 hexadecimal integer 11 hide() 519 HOUR 722 HSB color 382 HSBtoRGB() 385 HSPACE 355 HTML 343 Form 669, 671 HTML page 353 HTTP 586, 656 protocol 656 request 656 HTTP request 711 HttpRequest 656 HttpServlet 658 HttpServletRequest 658, 670, 675, 690 HttpServletResponse 658, 670, 689, 690 HttpSession 659, 693, 694 Hyperbolic 150 hypot() 181 I I/O Streams 217 I/O classes 218 I/O File 680 identifier 16 if..else ladder 47, 48 nested 45, 46 if..else Statement 43 IllegalAccessException 213 IllegalArgumentException 214, 230 import Statement 138 IN parameters 615, 626, 628 indexOf() 283, 284 InetAddress 584 methods 584 Inheritance 1, 3, 113 init() 347, 350, 657 input/output 217 InputStream 217, 218, 223, 224 methods 224 InputStreamReader 259, 262 insert() 289, 497, 512 insertElementAt() 468 Instance Variable Hiding 94 int 14 Integer Class 160 Methods 161 integer literals 11 Interface HTTPSession 693 Implementing 145 interface 147, 657 AppletContext 358, 363 AudioClip 358 Runnable 301 Servlet 657, 658 WindowListener 419 windowListener 421, 422 interface declaration 145 Interfaces Defining 145 interfaces 137 AppletStub 358 Internet Explorer 365, 656 Internet Protocol 584 InterruptedException 213 intValue() 156 IOException 200, 211, 224, 234, 237, 263 IP address 584 isActionKey() 410 isActive() 351 isAlive() 301, 303 isBold() 391 Index isClosed() 616 isDefined() 170 isDigit() 170 isDirectory() 220 isEditable() 497, 504 isFile() 220 isFirst() 636 isHidden() 220 isInfinite() 166, 168 isItalic() 391 isLast() 636 isLeapYear() 724 isLetter() 170 isLowerCase() 170 isModal() 519 isMulticastAddress() 584 isNaN() 166, 168 isPlain() 391 isPopupTrigger() 411 isSelected() 453 isUpperCase() 170 isWhiteSpace() 171 ItemEvent 450, 452, 459 ItemListener 507 itemStateChanged() 507 J J2EE 655 J2SE 721 J2SE6 722, 741 JApplet 344, 432, 451, 487 Java Database Connectivity 607 Java expression 21 Java Foundation Classes 429 Java program 19 Java Virtual Machine 6 java.io 741 java.io package 218 java.lang 139 java.util 721, 732 javac 20 JAVAEE5 655 JavaEE5 667 JButton 437, 530 Constructors 437 Icons 442 JFrame 438 methods 438 on JApplet 444 Using 445 JCheckBox 450, 452 constructors 452 methods 453 on JFrame 453 on JPanel 455 Using 456 JComboBox 503 constructors 503 methods 504 on JPanel 505 Using 507 JComponent 430 JComponent class 430 JDBC 607, 684 Using 611 JDBC API 608 JDBC URLs 614 JDBC-ODBC bridge 608 JDBC-ODBC driver 607, 608 JDialog 432, 518 constructors 518 methods 519 Using 519 JDK 6 JFC 429 JFileChooser 538, 542 constructors 539 Creating 540 methods 539 Using 542 JFrame 430, 432, 433, 512, 552 method 433 JFrame Windows 433 JLabel 447, 480 constants 447 constructors 448 methods 448 on JFrame 449 JLayeredPane 432 JList 464 constructors 464 DefaultListModel 468 methods 464 Using 471 Using DefaultListModel 469 with an Array 465 JMenu 510 constructors 512 methods 512 on JFrame 513 on JApplet 516 JMenuBar 432, 510, 513 constructors 513 JMenubar methods 513 JMenuItem 510 constructors 511 methods 511 join method 311 join() 301 JOptionPane 522 constants 522 759 760 Programming in JAVA2 constructors 523 methods 524 Using 525 JPanel 445, 461 JPasswordField 494 constructors 494 JFrame 494 methods 494 JPEG 361 JPG format 361 JProgressBar 548, 552 constants 548 constructors 548 JFrame 549 methods 549 on JFrame 549 Using 551 JRadioButton 450, 459 constructors 459 on JFrame 460 Using 461 JRadioButtons 565 JRootPane 432 JScrollBar 474, 478 constructors 474, 475 methods 475 on JPanel 476 JScrollPane 465, 478, 484 constructors 479 methods 479 on JPanel 480 JScrollPane() 464 JSeparator 512 JTextArea 484, 496 constructors 496 methods 496 on JPanel 498 Using 500 JTextComponent 496 JTextField 484 constants 484 constructors 485 methods 485 on JApplet 487 on JFrame 488 on JPanel 486 Using 490 JToggleButton 450 constructors 450 on JApplet 451 JVM 6 JWindow 432 K Key Event Handling 417 KeyEvent Class 408 KeyEventListener 417 L labeled break 60 labeled continue 63 last() 569, 636 lastIndexOf() 283, 284 lastModified() 220 Layout Managers 555 length() 220, 251, 284, 289 light-weight process 300 list() 220 ListCellRenderer 464 listener 402 Listener Interfaces 413 ListModel 464 ListSelectionModel 464 Literals 12 Boolean 13 Character 12 Floating Point 12 String 13 literals 11 Integer 11 locale() 736 log() 180 log10() 181 logical operators 37 long 14 Long Class 163 longValue() 156 LONGVARCHAR 632 lookup() 714, 715 loop() 360 M Mac OS 429 Macintosh 7 Macintosh machines 429 main method 20 mark() 224, 254 markSupported() 224, 254 Math class 179 mathematical methods 179 max() 180 Memory Handling 228 Method Declaration 92 method overloading 101 method overriding 115 millisecond 723 MIME 660 min() 180 MINUTE 723 model-view 500, 503 monitor 321 MONTH 722 Mouse Event Handling 415 MouseEvent 415 Index MouseEvent Class 410 MouseEventListener 415 MouseMotionEvent 415 MouseMotionListener 415 Mozilla Firefox 656 MS-Access 617, 624, 628 multi-level inheritance 119 multilevel inheritance 146 Multimedia 365 Multiple Catch Blocks 205 multiple inheritance 147 Multitasking 299 multithreaded program 307 multithreaded programming 299 Multithreading 300 multithreading 5 N NAME 354 Naming class 714, 718 NegativeArraySizeException 214 nested try block 204 Netscape Navigator 656 networking 583 new operator 90 newLine() 265 Newton-Raphson method 195 next() 569, 636, 727, 729 nextBoolean() 727 nextByte() 727 nextDouble() 728 nextFloat() 728 nextInt() 728 nextLine() 728 nextLong() 728 nextShort() 728 no-argument constructor 247 NoSuchMethodException 213 notify 327 notify() 324 notifyAll() 324 NullPointerException 214 Number 623 Number Class 155 number game 333 NumberFormatException 214 O objects 2, 90 object file 241 object reference variable 90 object reference variables 279 object-oriented programming 1 ObjectInput 245 ObjectInputStream 245, 247 ObjectOutputStream 240 octal integer 11 ODBC 607 ODBC API 608 OOP 1 openConnection() 601 openStream() 602 Operators 29 dot 91 modulus 30 new 90 Arithmetic 29 Bitwise 32 Boolean 37 Decrement 31 Increment 31 Relational 36 operator precedence 40 Oracle database 633 OUT parameter 616, 630 registering 631 out() 736 OutputStream 218, 223, 224, 230, 234 OutputStreamWriter 262, 263 Overloading 101 overloading methods 4 Overriding 115 overriding methods 4, 117 P package statement 137 packages 137 Paint Modes 387 paint() 347, 369, 373 paintComponent() 445, 507 palindromes 83 PARAMNAME 355 paramString() 405, 407, 408, 410, 411 parseByte() 157 parseDouble() 168 ParseException 211 parseFloat() 166 parseInt() 161 parseLong() 163 parseShort() 159 Pascal 1, 89 passing by reference 103 passing by value 103 paste() 497 payroll 637 percentComplete() 550 Perl 655 PHI 179 play() 358, 359, 360 Polygons 378 Polyline 379 Polymorphism 1, 4, 101, 119 761 762 Programming in JAVA2 Port numbers 586 POST 671, 672, 674, 680 pow() 180 prepareCall() 616 PreparedStatement 615, 628 PreparedStatement Interface 626 methods 627 prepareStatement() 616, 626, 629 previous() 569, 636 prime number 712 printf() 741, 742 println 737 println method 286 println() 670 PrintWriter 660 private 2, 141 processActionEvent() 438 protected 141 public 2, 141 Q quadratic equation 197 R radix() 728 random() 180 RandomAccessFile 250, 251 RDBMS 607 read() 224, 235, 246, 254, 259 readBoolean() 235, 246 readByte() 235, 246 readChar() 246 readDouble() 236, 246 Reader 218, 253, 255 Reader class 259 reader() 741, 743 readFloat() 236, 246 readFully() 235, 246 readInt() 235, 246 readLine() 265, 742 readLong() 235 readObject() 246 readPassword() 742 readShort() 235, 246 readUnsignedByte() 235, 246 readUnsignedShort() 235, 246 readUTF() 246 ready() 254, 259 receive() 597 Rectangles 371 recursion 123 regionMatches() 283 Registering Listeners 414 registerOutParameter() 630 Remote class 713, 718 Remote Method Invocation(RMI) 711 remote object 712, 713 remote server 712 RemoteException 713 removeActionListener() 415, 438, 485 removeAllItems() 504 removeAttribute() 694 removeElement() 469 removeElementAt() 469 removeItem() 504 removeItemAt() 504 removeKeyListener() 414 removeMouseListener() 414 removeMouseMotionListener() 414 removeWindowListener() 414 renameTo() 220 repaint() 507 replace() 284, 290 replaceRange() 497 replaceSelection() 497 request GET 658 POST 658 reset() 224, 254, 257 resize() 351 Restart 349 ResultSet 622 ResultSet interface methods 634 reverse() 289 RGB color 382 RGBtoHSB() 385 rint() 180 RMI 711, 713 application 716 compiler 715 linking 713 registry 716 RMI application 713 RMI Registry 712, 714, 716 RMI server 714 Robust 5 rollback() 616, 625 round() 180 run() 301, 302, 305, 319 Runge-Kutta method 193, 198 Runnable 303 Runnable interface 301, 305 RuntimeException 200, 206, 207, 210 S Safe 5 Scanner 721, 722 constructors 726 methods 727 Index Scanner Class 721, 726, 731 Scanning a Console 730 Scanning a File 731 Scope of Variables 17 scroll bar 478 ScrollPaneConstants 478 SECOND 723 SecurityException 227 seek() 251, 252 send() 597 SequenceInputStream 239 Serializable 240, 245 serialization 240 Server program 712 ServerSocket 586 methods 587 service() 657, 658 Servlet 680 compiling 661 Deploying 662 executing 662 JDBC 684 servlet 655, 657, 660 ServletOutputStream 660 session 688 Session Handling 688 Session Tracking 688, 693 set() 722, 724 setActionCommand() 504, 511 setAddress() 596 setAlignment() 559 setAttribute() 694 setBackground() 357 setBigDecimal() 627 setBlob() 627 setBoolean() 627 setByte() 627 setCharAt() 289 setClob() 628 setColumnHeaderView() 480, 482, 483 setColumns() 485, 563 setComment() 689 setContentType() 660, 670 setCorner() 480, 483 setCurrentDirectory() 540 setData() 596 setDate() 628 setDouble() 628 setEchoChar() 494 setEditable() 485, 504, 505 setEditor() 505 setExecutable() 221 setFileFilter() 540 setFloat() 628 setFont() 391, 448 setForeground() 357 setHelpMenu() 513 setHgap() 556, 559, 563 setHorizontalAlignment() 449 setHorizontalScrollBarPolicy() 480 setIcon() 438, 449, 453, 511 setInt() 628 setJMenuBar() 519 setKeyChar() 409, 428 setKeyCode() 409 setLayout() 434, 555 setLength() 251, 289, 596 setLineWrap() 497, 498 setLocation() 434, 436 setLong() 628 setMaxAge() 689 setMaximum() 476, 549 setMaxInactiveInterval() 694 setMenuBar() 513 setMessage() 524 setMinimum() 476, 549 setModel() 505 setObject() 628 setOptionType() 524 setOrientation() 476 setPaintMode() 387 setPath() 689 setPort() 596 setPriority() 309 setReadable() 221 setReadOnly() 220 setRolloverIcon() 438, 511 setRowHeaderView() 480, 483 setRows( 563 setSelected() 453 setShort() 628 setSize() 434 setSoTimeout() 587 setString() 549, 628 setStringPainted() 549 setText() 438, 449, 453, 485 setTitle() 433, 436, 519 setUnitIncrement() 476 setValue() 549, 550, 689 setVerticalAlignment() 449 setVerticalScrollBarPolicy() 480 setVgap() 556, 559, 563 setVisible() 433, 436 setVisibleRowCount() 464 setWrapStyleWord() 498 setWritable() 220 setXORMode() 387 setXXX() 626 short 14 Short Class 158 Methods 159 shortValue() 156 763 764 Programming in JAVA2 show() 519, 527 showConfirmDialog() 524, 527, 533, 543 showDialog() 540 showDocument() 363 showMessageDialog() 525, 527 showOpenDialog() 540, 543 showSaveDialog() 540 showStatus() 351 signum() 181 simple interest 108 Simpson’s 1/3 rule 187, 188 Simpson’s rule 198 sin() 179 Sin(x) 65, 106 single-precision 12 sinh() 181 Sinh(x) 150 size() 257 skip() 224, 254, 728 skipBytes() 235, 246 sleep() 301, 314, 550 Socket 586 methods 588 Socket Programming 586 SQL Package 611 SQL program 633 SQL statements 615, 617, 623, 624 sqrt() 180 standard deviation 131 start() 301, 302, 347 startsWith() 283 stateless protocol 688 Statement 615 Statement Interface Executing Statements 616 Statement interface 617 methods 617 statement object 629 static 124 Static Block 127 Static method 124 Static Variables 125 status bar 351 stop() 347, 360 stored procedures 630 String 277 Concatenation 281 String class 277, 278 string literal 13 String literals 279 String objects 279 String() 277 StringBuffer 277, 288 StringBuffer Class 288 StringBuffer class 277, 290 StringOutOfBoundsException 214 subclass 113 substring() 284, 290 SUNDAY 722 super.paintComponent() 445 superclass 205 Swing 344 Creating Windows 432 Origin 429 Swing classes 429 switch Statement 49 synchronized 321 synchronized method 321, 322, 324 Synchronizing Methods 318 System.exit(0) 419 System.out 738 T tan() 179 tanh() 181 TCP/IP 583 Telnet 586 Ternary Operator 40 TextEvent Class 412 The ItemEvent Class 408 this 301 this in a class 94 this in a Constructor 96 Thread Communication 323 Controlling 313 creating 301 Method 314 Methods 301, 314 new 306 Priorities 309 thread blocked 306 child 308 dead 307 new 306 runnable 306 running 306 Waiting 311 Thread class 301 throw statement 207 Throwable 209 throws 211 time zone 734 toBinaryString() 161, 164 toCharArray() 257 toDegrees() 180 toHexString() 161, 164 toLowerCase() 171, 284 Tomcat 4.1 661 toOctalString() 161, 164 Index toRadians() 180 toString() 156, 159, 161, 163, 166, 168, 257, 286, 287, 290, 384, 584, 736 toUpperCase() 171, 284 translate() 381 translatePoint() 411 Trapezoidal rule 185 trim() 284 try block 201, 203 try...catch 201, 202 Types 13 Character 15 Boolean 13 char 13 Floating Point 15 Integer 14 byte 13 int 13 long 13 short 13 type casting 22, 24 Type Conversion 22 type signature 101 Types of Drivers Type I 608 Type II 608 Type III 608 Type IV 608 Types of Exceptions 200 U UDP 583 UDP Client 599 UDP packet 599 UDP Server 597 unary operators 31 UnicastRemoteObject 713 Unicode 15 Unicode characters 15, 217 Uniform Resource Locator 600 Unix 7 update() 369 URL 357, 600, 714, 715 URL Class constructors 601 methods 601 URL Connection 603 URL Rewriting 688 useDelimiter() 728 useRadix() 728 utility classes 721 VARCHAR 632 variables 16 scope 25 view 478 view port 478 VSPACE 355 W wait 327 wait() 324 WAR file 660, 663 WAR Naming 663 Web Components 663, 667 web server 656, 660, 666, 667 while Statement 52 WIDTH 354 Window Event Handling 419 WindowEvent Class 412, 419 Windows 7 World Wide Web 600 wrapper classes 155 write() 225, 237, 241, 254, 261 writeBoolean() 238, 241 writeByte() 238, 241 writeBytes() 238, 241 writeChar() 238, 241 writeChars() 238, 241 writeDouble() 238, 241 writeFloat() 238, 241 writeInt() 238, 241 writeLong() 238, 241 writeObject() 241 Writer 218, 253, 261 Writer class 254 writer() 742, 743 writeShort() 238, 241 writeTo() 257 writeUTF( 241 writeUTF() 241 X XOR mode 387 Y YEAR 723 yield method 316 yield() 314 ****** V VALUE 355 valueChanged() 474 valueOf() 157, 159, 161, 163, 166, 168 View publication stats ****** 765