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:
[email protected]. ****** (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. //
[email protected] 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 ( 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 (>) 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 > 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 == != > >= < 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) & (xb) | (x 100) = false ^ false = false (c1 != c2) ^ (b > 100) = true ^ false = true ! (a>b) = ! false = true (a>b) == (xb) != (xb) ? (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>> < >= == != & ^ | && || ?: = 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 //
[email protected] 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. //
[email protected] 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 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 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 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 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
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
******
765