Docstoc

Java Programming

Document Sample
Java Programming Powered By Docstoc
					                                    Java Quick Reference

Console Input                                 GUI Input Dialog

Scanner input = new Scanner(System.in);       String string = JOptionPane.showInputDialog(
int intValue = input.nextInt();                 "Enter input");
long longValue = input.nextLong();            int intValue = Integer.parseInt(string);
double doubleValue = input.nextDouble();      double doubleValue =
float floatValue = input.nextFloat();           Double.parseDouble(string);
String string = input.next();
                                              Message Dialog
Console Output
                                              JOptionPane.showMessageDialog(null,
System.out.println(anyValue);                   "Enter input");



Primitive Data Types       Arithmetic Operators            Assignment Operators

byte      8 bits           +       addition                =     assignment
short     16 bits          -       subtraction             +=    addition assignment
int       32 bits          *       multiplication          -=    subtraction assignment
long      64 bits          /       division                *=    multiplication assignment
float     32 bits          %       remainder               /=    division assignment
double    64 bits          ++var   preincrement            %=    remainder assignment
char      16 bits          --var   predecrement
boolean   true/false       var++   postincrement
                           var--   postdecrement


Relational Operators               Logical Operators                  if Statements

<     less than                    &&      short circuit AND          if (condition) {
<=    less than or equal to        ||      short circuit OR             statements;
>     greater than                 !       NOT                        }
>=    greater than or equal to     ^       exclusive OR
==    equal to                                                        if (condition) {
!=    not equal                                                         statements;
                                                                      }
                                                                      else {
switch Statements                  loop Statements                      statements;
                                                                      }
switch (intExpression) {           while (condition) {
  case value1:                       statements;                      if (condition1) {
    statements;                    }                                    statements;
    break;                                                            }
  ...                              do {                               else if (condition2) {
  case valuen:                       statements;                        statements;
    statements;                    } while (condition);               }
    break;                                                            else {
  default:                         for (init; condition;                statements;
    statements;                      adjustment) {                    }
}                                    statements;
                                   }


                    Companion Web site: www.pearsonhighered.com/liang
                                   Java Quick Reference

Frequently Used Static Constants/Methods        Array/Length/Initializer

Math.PI                                          int[] list = new int[10];
Math.random()                                    list.length;
Math.pow(a, b)                                   int[] list = {1, 2, 3, 4};
System.currentTimeMillis()
System.out.println(anyValue)                    Multidimensional Array/Length/Initializer
JOptionPane.showMessageDialog(null,
  message)                                       int[][] list = new int[10][10];
JOptionPane.showInputDialog(                     list.length;
  prompt-message)                                list[0].length;
Integer.parseInt(string)                         int[][] list = {{1, 2}, {3, 4}};
Double.parseDouble(string)
Arrays.sort(type[] list)                        Ragged Array
Arrays.binarySearch(type[] list, type key)
                                                 int[][] m = {{1, 2, 3, 4},
                                                              {1, 2, 3},
                                                              {1, 2},
                                                              {1}};



Text File Output                        File Class               Object Class

 PrintWriter output =                   File file =              Object o = new Object();
   new PrintWriter(filename);             new File(filename);    o.toString();
 output.print(...);                     file.exists()            o.equals(o1);
 output.println(...);                   file.renameTo(File)
 output.printf(...);                    file.delete()
                                                                 Comparable Interface
Text File Input
                                                                 c.compareTo(Comparable)
  Scanner input = new Scanner(                                   c is a Comparable object
   new File(filename));


String Class                                   ArrayList Class

String s = "Welcome";                          ArrayList<E> list = new ArrayList<E>();
String s = new String(char[]);                 list.add(object);
int length = s.length();                       list.add(index, object);
char ch = s.charAt(index);                     list.clear();
int d = s.compareTo(s1);                       Object o = list.get(index);
boolean b = s.equals(s1);                      boolean b = list.isEmpty();
boolean b = s.startsWith(s1);                  boolean b = list.contains(object);
boolean b = s.endsWith(s1);                    int i = list.size();
String s1 = s.trim();                          list.remove(index);
String s1 = s.toUpperCase();                   list.set(index, object);
String s1 = s.toLowerCase();                   int i = list.indexOf(object);
int index = s.indexOf(ch);                     int i = list.lastIndexOf(object);
int index = s.lastIndexOf(ch);
String s1 = s.substring(ch);
String s1 = s.substring(i,j);
char[] chs = s.toCharArray();                  printf Method
String s1 = s.replaceAll(regex,repl);
String[] tokens = s.split(regex);              System.out.printf("%b %c %d %f %e %s",
                                                 true, 'A', 45, 45.5, 45.5, "Welcome");
                                               System.out.printf("%-5d %10.2f %10.2e %8s",
                                                 45, 45.5, 45.5, "Welcome");


                   Companion Web site: www.pearsonhighered.com/liang
           INTRODUCTION TO



  JAVA
                                                                 TM




       PROGRAMMING
          COMPREHENSIVE VERSION

                         Eighth Edition




                  Y. Daniel Liang
                 Armstrong Atlantic State University




                              Prentice Hall
      Boston Columbus Indianapolis New York San Francisco Upper Saddle River
Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto
  Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Vice President and Editorial Director, ECS: Marcia J. Horton
Editor in Chief, Computer Science: Michael Hirsch
Executive Editor: Tracy Dunkelberger
Assistant Editor: Melinda Haggerty
Editorial Assistant: Allison Michael
Vice President, Production: Vince O’Brien
Senior Managing Editor: Scott Disanno
Production Editor: Irwin Zucker
Senior Operations Specialist: Alan Fischer
Marketing Manager: Erin Davis
Marketing Assistant: Mack Patterson
Art Director: Kenny Beck
Cover Image: Male Ruby-throated Hummingbird / Steve Byland / Shutterstock;
  Hummingbird, Nazca Lines / Gary Yim / Shutterstock
Art Editor: Greg Dulles
Media Editor: Daniel Sandin


Copyright © 2011, 2009, 2007, 2004 by Pearson Higher Education. Upper Saddle River, New Jersey, 07458.
All right reserved. Manufactured in the United States of America. This publication is protected by Copyright and
permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval sys-
tem, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To
obtain permission(s) to use materials from this work, please submit a written request to Pearson Higher Education,
Permissions Department, 1 Lake Street, Upper Saddle River, NJ 07458.

The author and publisher of this book have used their best efforts in preparing this book. These efforts include the
development, research, and testing of the theories and programs to determine their effectiveness. The author and
publisher make no warranty of any kind, expressed or implied, with regard to these programs or the documentation
contained in this book. The author and publisher shall not be liable in any event for incidental or consequential
damages in connection with, or arising out of, the furnishing, performance, or use of these programs.




Library of Congress Cataloging-in-Publication Data on file.




                                                                           10 9 8 7 6 5 4 3 2 1

                                                                           ISBN-13: 978-0-13-213080-6
                                                                           ISBN-10: 0-13-213080-7
        This book is dedicated to Dr. S. K. Dhall and
   Dr. S. Lakshmivarahan of the University of Oklahoma,
who inspired me in teaching and research. Thank you for being
                  my mentors and advisors.




            To Samantha, Michael, and Michelle
PREFACE
                            This book uses the fundamentals-first approach and teaches programming concepts and tech-
                            niques in a problem-driven way.
fundamentals-first              The fundamentals-first approach introduces basic programming concepts and techniques
                            before objects and classes. My own experience, confirmed by the experiences of many col-
                            leagues, demonstrates that new programmers in order to succeed must learn basic logic and
                            fundamental programming techniques such as loops and stepwise refinement. The fundamen-
                            tal concepts and techniques of loops, methods, and arrays are the foundation for program-
                            ming. Building the foundation prepares students to learn object-oriented programming, GUI,
                            database, and Web programming.
problem-driven                  Problem-driven means focused on problem solving rather than syntax. We make introducto-
                            ry programming interesting by using interesting problems. The central thread of early chapters
                            is on problem solving. Appropriate syntax and library are introduced to support the writing of
                            a program for solving the problems. To support the teaching of programming in a problem-
                            driven way, the book provides a wide variety of problems at various levels of difficulty to mo-
                            tivate students. In order to appeal to students in all majors, the problems cover many
                            application areas in math, science, business, financials, gaming, animation, and multimedia.

                            Two Versions
comprehensive version       This comprehensive version covers fundamentals of programming, object-oriented program-
                            ming, GUI programming, algorithms and data structures, concurrency, networking, internation-
                            alization, advanced GUI, database, and Web programming. It is designed to prepare students to
brief version               become proficient Java programmers. A brief version (Introduction to Java Programming, Brief
                            Version, Eighth Edition) is available for a first course on programming, commonly known as
                            CS1. The brief version contains the first 20 chapters of the comprehensive version.


                            What’s New in This Edition?
                            This edition substantially improves Introduction to Java Programming, Seventh Edition. The
                            major improvements are as follows:
complete revision           ■   This edition is completely revised in every detail to enhance clarity, presentation, content,
                                examples, and exercises.
                            ■   In the examples and exercises, which are provided to motivate and stimulate student inter-
new problems                     est in programming, one-fifth of the problems are new.
early console input         ■   In the previous edition, console input was covered at the end of Chapter 2. The new edition in-
                                 troduces console input early in Chapter 2 so that students can write interactive programs early.
hand trace box              ■   The hand trace box is added for many programs to help novice students to read and trace
                                programs.
multidimensional arrays     ■   Single-dimensional arrays and multidimensional arrays are covered in two chapters to give
                                instructors the flexibility to cover multidimensional arrays later.
Sudoku problem simplified   ■   The case study for the Sudoku problem has been moved to the Companion Website. A
                                more pedagogically effective simple version of the Sudoku problem is presented instead.
                            ■   The design of the API for Java GUI programming is an excellent example of how the
                                object-oriented principle is applied. Students learn better with concrete and visual examples.

iv
                                                                                                                       Preface v
    So, basic GUI now precedes the introduction of abstract classes and interfaces. The instruc-        basic GUI earlier
    tor, however, can still choose to cover abstract classes and interfaces before GUI.
■   Exception handling is covered before abstract classes and interfaces so that students can           exception handling earlier
    build robust programs early. The instructor can still choose to cover exception handling later.
■   Chapter 12, “Object-Oriented Design and Patterns,” in the previous edition has been
    replaced by spreading the design guidelines and patterns into several chapters so that these        design guidelines
    topics can be covered in appropriate context.
■   The chapter on sorting now follows right after the chapter on algorithm efficiency, so that         sorting
    students can immediately apply algorithm efficiency to sorting algorithms.
■   A brand-new bonus Chapter 44 covers Java 2D.                                                        Java 2D

■   The coverage on data structures is expanded with new bonus chapters on AVL trees, splay
    trees, 2-4 trees, B-trees, and red-black trees, and hashing. So the book can be used for a
    full data structures course.                                                                        new data structures chapters


Learning Strategies
A programming course is quite different from other courses. In a programming course, you
learn from examples, from practice, and from mistakes. You need to devote a lot of time to              learn from mistakes
writing programs, testing them, and fixing errors.
    For first-time programmers, learning Java is like learning any high-level programming lan-
guage. The fundamental point is to develop the critical skills of formulating programmatic              programmatic solution
solutions for real problems and translating them into programs using selection statements,
loops, methods, and arrays.
    Once you acquire the basic skills of writing programs using loops, methods, and arrays,
you can begin to learn how to develop large programs and GUI programs using the object-                 object-oriented programming
oriented approach.
    When you know how to program and you understand the concept of object-oriented pro-
gramming, learning Java becomes a matter of learning the Java API. The Java API establishes             Java API
a framework for programmers to develop applications using Java. You have to use the classes
and interfaces in the API and follow their conventions and rules to create applications. The
best way to learn the Java API is to imitate examples and do exercises.

Pedagogical Features
The book uses the following elements to get the most from the material:
■   Objectives list what students should have learned from the chapter. This will help them
    determine whether they have met the objectives after completing the chapter.
■   Introduction opens the discussion with representative problems to give the reader an
    overview of what to expect from the chapter.
■   Problems carefully chosen and presented in an easy-to-follow style, teach problem solving
    and programming concepts. The book uses many small, simple, and stimulating examples
    to demonstrate important ideas.
■   Chapter Summary reviews the important subjects that students should understand and
    remember. It helps them reinforce the key concepts they have learned in the chapter.
■   Review Questions are grouped by sections to help students track their progress and eval-
    uate their learning.
■   Programming Exercises are grouped by sections to provide students with opportunities to
    apply on their own the new skills they have learned. The level of difficulty is rated as easy (no
vi Preface
                 asterisk), moderate (*), hard (**), or challenging (***). The trick of learning programming is
                 practice, practice, and practice. To that end, the book provides a great many exercises.
             ■   LiveLab is a course assessment and management system. Students can submit programs
                 online. The system automatically grades the programs/multiple-choice quizzes and gives
                 students instant feedback. Instructors can create custom programming exercises and
                 quizzes as well as use the system prebuilt exercises and quizzes.
             ■   Notes, Tips, and Cautions are inserted throughout the text to offer valuable advice and in-
                 sight on important aspects of program development.


                   Note
                   Provides additional information on the subject and reinforces important concepts.

                   Tip
                   Teaches good programming style and practice.

                   Caution
                   Helps students steer away from the pitfalls of programming errors.

                   Design Guide
                   Provides the guidelines for designing programs.


             Flexible Chapter Orderings
             The book is designed to provide flexible chapter orderings to enable GUI, exception handling,
             recursion, generics, and the Java Collections Framework to be covered earlier or later. The
             diagram on the next page shows the chapter dependencies.

             Organization of the Book
             The chapters can be grouped into five parts that, taken together, form a comprehensive intro-
             duction to Java programming, data structures and algorithms, and database and Web pro-
             gramming. Because knowledge is cumulative, the early chapters provide the conceptual basis
             for understanding programming and guide students through simple examples and exercises;
             subsequent chapters progressively present Java programming in detail, culminating with the
             development of comprehensive Java applications.

             Part I: Fundamentals of Programming (Chapters 1–7)
             The first part of the book is a stepping stone, preparing you to embark on the journey of learning
             Java. You will begin to know Java (Chapter 1) and will learn fundamental programming tech-
             niques with primitive data types, variables, constants, assignments, expressions, and operators
             (Chapter 2), control statements (Chapters 3–4), methods (Chapter 5), and arrays (Chapters 6–7).
             After Chapter 6, you may jump to Chapter 20 to learn how to write recursive methods for solv-
             ing inherently recursive problems.

             Part II: Object-Oriented Programming (Chapters 8–11, 13–14, 19)
             This part introduces object-oriented programming. Java is an object-oriented programming
             language that uses abstraction, encapsulation, inheritance, and polymorphism to provide great
             flexibility, modularity, and reusability in developing software. You will learn programming
             with objects and classes (Chapters 8–10), class inheritance (Chapter 11), polymorphism
             (Chapter 11), exception handling (Chapter 13), abstract classes (Chapter 14), and interfaces
             (Chapter 14). Processing strings will be introduced in Chapter 9 along with text I/O. Binary
             I/O is introduced in Chapter 19.
Part I: Fundamentals of         Part II: Object-Oriented           Part III: GUI Programming                Part IV: Data Structures and              Part V: Advanced Java
  Programming                     Programming                                                                 Algorithms                      Ch 18     Programming
 Chapter 1 Introduction to       Chapter 8 Objects and Classes      Chapter 12 GUI Basics           Ch 6    Chapter 20 Recursion                      Chapter 29 Multithreading
   Computers, Programs, and
   Java
                                 Chapter 9 Strings and Text I/O     Chapter 15 Graphics             Ch 14   Chapter 21 Generics                       Chapter 30 Networking

 Chapter 2 Elementary
                                 Chapter 10 Thinking in Objects     Chapter 16 Event-Driven                 Chapter 22 Java Collections               Chapter 31 Internationalization
   Programming
                                                                      Programming                             Framework
                                 Chapter 11 Inheritance and                                                                                           Chapter 37 Java Database
 Chapter 3 Selections                                               Chapter 17 Creating Graphical           Chapter 23 Algorithm Efficiency
                                   Polymorphism                                                                                                         Programming
                                                                      User Interfaces
 Chapter 4 Loops                 Chapter 13 Exception                                                       Chapter 24 Sorting                        Chapter 38 Advanced Java
                                   Handling                         Chapter 18 Applets and                                                              Database Programming
                                                                      Multimedia
 Chapter 5 Methods                                                                                          Chapter 25 Lists, Stacks, and
                                 Chapter 14 Abstract Classes                                                  Queues, and Priority Queues             Chapter 39 Servlets
                                   and Interfaces                   Chapter 32 JavaBeans and Bean
 Chapter 6 Single-Dimensional                                         Events
   Arrays                                                                                                   Chapter 26 Binary Search Trees            Chapter 40 JavaServer Pages
                                 Chapter 19 Binary I/O
                                                                    Chapter 33 Containers, Layout
 Chapter 7 Multidimensional                                           Managers, and Borders                 Chapter 27 Graphs and                     Chapter 41 JSF and Visual
   Arrays                                                                                                     Applications                              Web Development
                                                                    Chapter 34 Menus, Toolbars,
                                                                      and Dialogs                           Chapter 28 Weighted Graphs                Chapter 42 Web Services
                                                                                                              and Applications

                                                                    Chapter 35 MVC and Swing                                                          Chapter 43 Remote Method
                                                                      Models                                Chapter 45 AVL and Splay
                                                                                                                                                        Invocation
                                                                                                              Trees

                                                                    Chapter 36 JTable and JTree
                                  Note: Chapters 1–20 are in the                                            Chapter 46 2-4 Trees and
                                  brief version of this book                                                  B-Trees
                                                                    Chapter 44 Java 2D
                                  Note: Chapters 38–48 are bonus                                            Chapter 47 Red-Black Trees
                                  chapters available from the
                                  Companion Website
                                                                                                            Chapter 48 Hashing




                                                                                                                                                                                        Preface vii
viii Preface
                Part III: GUI Programming (Chapters 12, 15–18, 32–36, and 44)
                This part introduces elementary Java GUI programming in Chapters 12 and 15–18 and advanced
                Java GUI programming in Chapters 32–36 and 44. Major topics include GUI basics (Chapter 12),
                drawing shapes (Chapter 15), event-driven programming (Chapter 16), creating graphical user
                interfaces (Chapter 17), and writing applets (Chapter 18). You will learn the architecture of Java
                GUI programming and use the GUI components to develop applications and applets from these
                elementary GUI chapters. The advanced GUI chapters introduce Java GUI programming in more
                depth and breadth. You will delve into JavaBeans and learn how to develop custom events and
                source components in Chapter 32, review and explore new containers, layout managers, and bor-
                ders in Chapter 33, learn how to create GUI with menus, popup menus, toolbars, dialogs, and
                internal frames in Chapter 34, develop components using the MVC approach and explore the
                advanced Swing components JSpinner, JList, JComboBox, JSpinner, and JTable, and
                JTree in Chapters 35 and 36. Bonus Chapter 44 introduces Java 2D.

                Part IV: Algorithms and Data Structures (Chapters 20–28, 45–48)
                This part introduces the main subjects in a typical data structures course. Chapter 20 intro-
                duces recursion to write methods for solving inherently recursive problems. Chapter 21 intro-
                duces generics to improve software reliability. Chapter 22 introduces the Java Collection
                Framework, which defines a set of useful API for data structures. Chapter 23 introduces mea-
                surement of algorithm efficiency in order to choose an appropriate algorithm for applications.
                Chapter 24 introduces classic sorting algorithms. You will learn how to implement several
                classic data structures lists, queues, priority queues, binary search trees, AVL trees, splay
                trees, 2-4 trees, B-trees, and red-black trees in Chapters 25–26 and 45–47. Chapters 27 and 28
                introduce graph applications. Chapter 48 introduces hashing.

                Part V: Advanced Java Programming (Chapters 29–31, 37–43)
                This part of the book is devoted to advanced Java programming. Chapter 29 treats the use of
                multithreading to make programs more responsive and interactive. Chapter 30 introduces how
                to write programs that talk with each other from different hosts over the Internet. Chapter 31
                covers the use of internationalization support to develop projects for international audiences.
                Chapter 37 introduces the use of Java to develop database projects, Chapter 38 introduces
                advanced Java database programming, and Chapters 39 and 40 introduce how to use Java
                servlets and JSP to generate dynamic contents from Web servers. Chapter 41 introduces rapid
                Web application development using JavaServer Faces. Chapter 42 introduces Web services.
                Chapter 43 introduces remote method invocation.


                Java Development Tools
                You can use a text editor, such as the Windows Notepad or WordPad, to create Java programs
                and to compile and run the programs from the command window. You can also use a Java
IDE tutorials   development tool, such as TextPad, NetBeans, or Eclipse. These tools support an integrated
                development environment (IDE) for rapidly developing Java programs. Editing, compiling,
                building, executing, and debugging programs are integrated in one graphical user interface.
                Using these tools effectively can greatly increase your programming productivity. TextPad is
                a primitive IDE tool. NetBeans and Eclipse are more sophisticated, but they are easy to use if
                you follow the tutorials. Tutorials on TextPad, NetBeans and Eclipse can be found in the sup-
                plements on the Companion Website.


                LiveLab
                This book is accompanied by an improved faster Web-based course assessment and manage-
                ment system. The system has three main components:
                                                                                                    Preface ix
■   Automatic Grading System: It can automatically grade programs from the text or creat-
    ed by instructors.
■   Quiz Creation/Submission/Grading System: It enables instructors to create/modify
    quizzes that students can take and be graded upon automatically.
■   Tracking grades, attendance, etc: The system enables the students to track grades and
    instructors, to view the grades of all students, and to track attendance.
The main features of the Automatic Grading System are as follows:

■   Allows students to compile, run and submit exercises. (The system checks whether their
    program runs correctly—students can continue to run and resubmit the program before the
    due date.)
■   Allows instructors to review submissions; run programs with instructor test cases; correct
    them; and provide feedback to students.
■   Allows instructors to create/modify custom exercises, create public and secret test cases,
    assign exercises, and set due dates for the whole class or for individuals.
■   All the exercises in the text can be assigned to students. Additionally, LiveLab provides
    extra exercises that are not printed in the text.
■   Allows instructors to sort and filter all exercises and check grades (by time frame, student,
    and/or exercise).
■   Allows instructors to delete students from the system.
■   Allows students and instructors to track grades on exercises.

The main features of the Quiz System are as follows:

■   Allows instructors to create/modify quizzes from test bank or a text file or to create com-
    plete new tests online.
■   Allows instructors to assign the quizzes to students and set a due date and test time limit
    for the whole class or for individuals.
■   Allows students and instructors to review submitted quizzes.

■   Allows students and instructors to track grades on quizzes.

Video Notes are Pearson’s new visual tool designed for teaching students key programming con-
cepts and techniques. These short step-by-step videos demonstrate how to solve problems from
design through coding. Video Notes allows for self-paced instruction with easy navigation includ-
ing the ability to select, play, rewind, fast-forward, and stop within each Video Note exercise.
   Video Note margin icons in your textbook let you know what a Video Notes video is avail-
able for a particular concept or homework problem.
   Video Notes are free with the purchase of a new textbook. To purchase access to Video
Notes, please go to www.pearsonhighered.com/liang.

Student Resource Materials
The student resources can be accessed through the Publisher’s Web site
(www.pearsonhighered.com/liang) and the Companion Web site (www.cs.armstrong.edu/liang/intro8e).
The resources include:
■   Answers to review questions
■   Solutions to even-numbered programming exercises
x Preface
                  ■   Source code for book examples
                  ■   Interactive self-test (organized by chapter sections)
                  ■   LiveLab
                  ■   Resource links
                  ■   Errata
                  ■   Video Notes
                  ■   Web Chapters
                  To access the Video Notes and Web Chapters, students must log onto www.pearsonhighered.com/liang
                  and use the access card located in the front of the book to register and access the material. If there is
                  no access card in the front of this textbook, students can purchase access by visiting
                  www.pearsonhighered.com/liang and selecting purchase access to premium content.


                  Additional Supplements
                  The text covers the essential subjects. The supplements extend the text to introduce additional
                  topics that might be of interest to readers. The supplements listed in this table are available
                  from the Companion Web site.


                                        Supplements on the Companion Web site
            Part I General Supplements                                F Enumerated Types
             A Glossary                                               G Packages
             B Installing and Configuring JDK                         H Regular Expressions
             C Compiling and Running Java from the                    I Formatted Strings
                Command Window                                        J The Methods in the Object Class
             D Java Coding Style Guidelines                           K Hiding Data Fields and Static
             E Creating Desktop Shortcuts for Java                      Methods
                Applications on Windows                               L Initialization Blocks
             F Using Packages to Organize the Classes                 M Extended Discussions on Overriding
                in the Text                                             Methods
                                                                      N Design Patterns
            Part II IDE Supplements
                                                                      O Text I/O Prior to JDK 1.5 (Reader and
             A TextPad Tutorial
                                                                        Writer Classes)
             B NetBeans Tutorial | One Page Startup
                                                                      P Assertions
                Instruction
                                                                      Q Packaging and Deploying Java Projects
             C Learning Java Effectively with
                                                                      R Java Web Start
                NetBeans
                                                                      S GridBagLayout | OverlayLayout |
             D Eclipse Tutorial | One Page Startup
                                                                        SpringLayout
                Instruction
                                                                      T Networking Using Datagram Protocol
             E Learning Java Effectively with Eclipse
                                                                      U Creating Internal Frames
            Part III Java Supplements                                 V Pluggable Look and Feel
             A Java Characteristics                                   W UML Graphical Notations
             B Discussion on Operator and Operand                     X Testing Classes Using JUnit
                Evaluations                                           Y JNI
             C The & and | Operators                                  Z The StringTokenizer Class
             D Bitwise Operations
                                                                    Part IV Database Supplements
             E Statement Labels with break
                                                                     A SQL Statements for Creating and
                and continue
                                                                        Initializing Tables Used in the Book
                                                                                                      Preface xi

    B   MySQL Tutorial                                   Part V Web Programming Supplements
    C   Oracle Tutorial                                   A HTML and XHTML Tutorial
    D   Microsoft Access Tutorial                         B CSS Tutorial
    E   Introduction to Database Systems                  C XML
    F   Relational Database Concept                       D Java and XML
    G   Database Design                                   E Tomcat Tutorial
    H   SQL Basics                                        F More Examples on JSF and Visual Web
    I   Advanced SQL                                         Development



Instructor Resource Materials
The instructor resources can be accessed through the Publisher’s Web site
(www.pearsonhighered.com/liang) and the Companion Web site (www.cs.armstrong.edu/liang/intro8e).
For username and password information to the Liang 8e site, please contact your Pearson Repre-
sentative.
   The resources include:
■   PowerPoint lecture slides with source code and run program capacity
■   Instructor solutions manual
■   Computerized test generator
■   Sample exams using multiple choice and short answer questions, write and trace pro-
    grams, and correcting programming errors.
■   LiveLab
■   Errata
■   Video Notes
■   Web Chapters

To access the Video Notes and Web Chapters, instructors must log onto www.pearsonhighered.com/liang
and register.


Acknowledgments
I would like to thank Armstrong Atlantic State University for enabling me to teach what I
write and for supporting me in writing what I teach. Teaching is the source of inspiration for
continuing to improve the book. I am grateful to the instructors and students who have offered
comments, suggestions, bug reports, and praise.
   This book has been greatly enhanced thanks to outstanding reviews for this and previous
editions. The reviewers are: Elizabeth Adams (James Madison University), Syed Ahmed
(North Georgia College and State University), Omar Aldawud (Illinois Institute of Technol-
ogy), Yang Ang (University of Wollongong, Australia), Kevin Bierre (Rochester Institute of
Technology), David Champion (DeVry Institute), James Chegwidden (Tarrant County Col-
lege), Anup Dargar (University of North Dakota), Charles Dierbach (Towson University),
Frank Ducrest (University of Louisiana at Lafayette), Erica Eddy (University of Wisconsin at
Parkside), Deena Engel (New York University), Henry A Etlinger (Rochester Institute of Tech-
nology), James Ten Eyck (Marist College), Olac Fuentes (University of Texas at El Paso),
Harold Grossman (Clemson University), Barbara Guillot (Louisiana State University), Ron
Hofman (Red River College, Canada), Stephen Hughes (Roanoke College), Vladan Jovanovic
(Georgia Southern University), Edwin Kay (Lehigh University), Larry King (University of
Texas at Dallas), Nana Kofi (Langara College, Canada), George Koutsogiannakis (Illinois
xii Preface
              Institute of Technology), Roger Kraft (Purdue University at Calumet), Hong Lin (DeVry Insti-
              tute), Dan Lipsa (Armstrong Atlantic State University), James Madison (Rensselaer Polytech-
              nic Institute), Frank Malinowski (Darton College), Tim Margush (University of Akron),
              Debbie Masada (Sun Microsystems), Blayne Mayfield (Oklahoma State University), John
              McGrath (J.P. McGrath Consulting), Shyamal Mitra (University of Texas at Austin), Michel
              Mitri (James Madison University), Kenrick Mock (University of Alaska Anchorage), Jun Ni
              (University of Iowa), Benjamin Nystuen (University of Colorado at Colorado Springs), Mau-
              reen Opkins (CA State University, Long Beach), Gavin Osborne (University of Saskatchewan),
              Kevin Parker (Idaho State University), Dale Parson (Kutztown University), Mark Pendergast
              (Florida Gulf Coast University), Richard Povinelli (Marquette University), Roger Priebe (Uni-
              versity of Texas at Austin), Mary Ann Pumphrey (De Anza Junior College), Pat Roth (South-
              ern Polytechnic State University), Ronald F. Taylor (Wright State University), Carolyn
              Schauble (Colorado State University), David Scuse (University of Manitoba), Ashraf Shirani
              (San Jose State University), Daniel Spiegel (Kutztown University), Amr Sabry (Indiana Uni-
              versity), Lixin Tao (Pace University), Russ Tront (Simon Fraser University), Deborah Trytten
              (University of Oklahoma), Kent Vidrine (George Washington University), and Bahram
              Zartoshty (California State University at Northridge).
                 It is a great pleasure, honor, and privilege to work with Pearson. I would like to thank
              Tracy Dunkelberger and her colleagues Marcia Horton, Margaret Waples, Erin Davis,
              Michael Hirsh, Matt Goldstein, Jake Warde, Melinda Haggerty, Allison Michael, Scott Dis-
              anno, Irwin Zucker, and their colleagues for organizing, producing, and promoting this pro-
              ject, and Robert Lentz for copy editing.
                 As always, I am indebted to my wife, Samantha, for her love, support, and encouragement.
                                              Y. Daniel Liang
                                              y.daniel.liang@gmail.com
                                              www.cs.armstrong.edu/liang
                                              www.pearsonhighered.com/liang
BRIEF CONTENTS
1 Introduction to Computers, Programs,           32 JavaBeans and Bean Events              1091
     and Java                                1   33 Containers, Layout Managers,
 2   Elementary Programming                 23        and Borders                           1111
 3   Selections                             71   34   Menus, Toolbars, and Dialogs         1149
 4   Loops                                 115   35   MVC and Swing Models                 1187
 5   Methods                              155    36   JTable and JTree                     1225
 6   Single-Dimensional Arrays            197    37   Java Database Programming            1273
 7   Multidimensional Arrays              235
 8   Objects and Classes                  263
                                                 Chapters are available from the companion
 9   Strings and Text I/O                 301    Web site at www.pearsonhighered.com/liang:
10   Thinking in Objects                  343
11   Inheritance and Polymorphism         373    38   Advanced Java Database Programming   38–1
12   GUI Basics                           405    39   Servlets                             39–1
13   Exception Handling                   431    40   JavaServer Pages                     40–1
14   Abstract Classes and Interfaces      457    41   JSF and Visual Web Development       41–1
15   Graphics                             497    42   Web Services                         42–1
16   Event-Driven Programming             533    43   Remote Method Invocation             43–1
17   Creating Graphical User Interfaces   571    44   Java 2D                              44–1
18   Applets and Multimedia               613    45   AVL Trees and Splay Trees            45–1
19   Binary I/O                           649    46   2-4 Trees and B-Trees                46–1
20   Recursion                            677    47   Red-Black Trees                      47–1
21   Generics                             707    48   Hashing                              48–1
22   Java Collections Framework           727
23   Algorithm Efficiency                 765    APPENDIXES
24   Sorting                              791
                                                 A    Java Keywords                        1309
25   Lists, Stacks, Queues, and
     Priority Queues                       821   B    The ASCII Character Set               1312
26   Binary Search Trees                   857   C    Operator Precedence Chart            1314
27   Graphs and Applications               891   D    Java Modifiers                       1316
28   Weighted Graphs and Applications      939   E    Special Floating-Point Values        1318
29   Multithreading                        971   F    Number Systems                        1319
30   Networking                           1017
31   Internationalization                 1057   INDEX                                     1323




                                                                                            xiii
CONTENTS
      Chapter 1 Introduction to Computers, Programs,
                and Java                                                 1
             1.1   Introduction                                           2
             1.2   What Is a Computer?                                    2
             1.3   Programs                                               5
             1.4   Operating Systems                                      7
             1.5   Java, World Wide Web, and Beyond                      8
             1.6   The Java Language Specification, API, JDK, and IDE   10
             1.7   A Simple Java Program                                 11
             1.8   Creating, Compiling, and Executing a Java Program    13
             1.9   (GUI) Displaying Text in a Message Dialog Box        16

      Chapter 2 Elementary Programming                                  23
             2.1   Introduction                                         24
             2.2   Writing Simple Programs                              24
             2.3   Reading Input from the Console                       26
             2.4   Identifiers                                          29
             2.5   Variables                                            29
             2.6   Assignment Statements and Assignment Expressions     30
             2.7   Named Constants                                      31
             2.8   Numeric Data Types and Operations                    32
             2.9   Problem: Displaying the Current Time                 37
            2.10   Shorthand Operators                                  39
            2.11   Numeric Type Conversions                             41
            2.12   Problem: Computing Loan Payments                     43
            2.13   Character Data Type and Operations                   44
            2.14   Problem: Counting Monetary Units                     47
            2.15   The String Type                                      50
            2.16   Programming Style and Documentation                  51
            2.17   Programming Errors                                   53
            2.18   (GUI) Getting Input from Input Dialogs               55

      Chapter 3 Selections                                              71
             3.1   Introduction                                         72
             3.2   boolean Data Type                                    72
             3.3   Problem: A Simple Math Learning Tool                 73
             3.4   if Statements                                        74
             3.5   Problem: Guessing Birthdays                          75
             3.6   Two-Way if Statements                                79
             3.7   Nested if Statements                                 80
xiv
                                                                          Contents xv
       3.8   Common Errors in Selection Statements                 81
       3.9   Problem: An Improved Math Learning Tool               82
      3.10   Problem: Computing Body Mass Index                    84
      3.11   Problem: Computing Taxes                              85
      3.12   Logical Operators                                     88
      3.13   Problem: Determining Leap Year                        90
      3.14   Problem: Lottery                                      91
      3.15   switch Statements                                     93
      3.16   Conditional Expressions                               95
      3.17   Formatting Console Output                             95
      3.18   Operator Precedence and Associativity                 97
      3.19   (GUI) Confirmation Dialogs                            98

Chapter 4 Loops                                                    115
       4.1   Introduction                                           116
       4.2   The while Loop                                         116
       4.3   The do-while Loop                                     124
       4.4   The for Loop                                          126
       4.5   Which Loop to Use?                                    128
       4.6   Nested Loops                                          129
       4.7   Minimizing Numeric Errors                             130
       4.8   Case Studies                                           131
       4.9   Keywords break and continue                           135
      4.10   (GUI) Controlling a Loop with a Confirmation Dialog   139

Chapter 5 Methods                                                  155
       5.1   Introduction                                          156
       5.2   Defining a Method                                     156
       5.3   Calling a Method                                      158
       5.4   void Method Example                                   160
       5.5   Passing Parameters by Values                          162
       5.6   Modularizing Code                                     165
       5.7   Problem: Converting Decimals to Hexadecimals          167
       5.8   Overloading Methods                                   168
       5.9   The Scope of Variables                                 171
      5.10   The Math Class                                        172
      5.11   Case Study: Generating Random Characters              175
      5.12   Method Abstraction and Stepwise Refinement            176

Chapter 6 Single-Dimensional Arrays                                197
       6.1   Introduction                                          198
       6.2   Array Basics                                          198
       6.3   Problem: Lotto Numbers                                204
       6.4   Problem: Deck of Cards                                206
       6.5   Copying Arrays                                        208
xvi Contents
                       6.6   Passing Arrays to Methods                        209
                       6.7   Returning an Array from a Method                 212
                       6.8   Variable-Length Argument Lists                   215
                       6.9   Searching Arrays                                 216
                      6.10   Sorting Arrays                                   219
                      6.11   The Arrays Class                                 223

               Chapter 7 Multidimensional Arrays                              235
                       7.1   Introduction                                     236
                       7.2   Two-Dimensional Array Basics                     236
                       7.3   Processing Two-Dimensional Arrays                238
                       7.4   Passing Two-Dimensional Arrays to Methods        240
                       7.5   Problem: Grading a Multiple-Choice Test          241
                       7.6   Problem: Finding a Closest Pair                  242
                       7.7   Problem: Sudoku                                  244
                       7.8   Multidimensional Arrays                          248

               Chapter 8 Objects and Classes                                  263
                       8.1   Introduction                                     264
                       8.2   Defining Classes for Objects                     264
                       8.3   Example: Defining Classes and Creating Objects   266
                       8.4   Constructing Objects Using Constructors          270
                       8.5   Accessing Objects via Reference Variables        270
                       8.6   Using Classes from the Java Library              274
                       8.7   Static Variables, Constants, and Methods         278
                       8.8   Visibility Modifiers                             282
                       8.9   Data Field Encapsulation                         283
                      8.10   Passing Objects to Methods                       286
                      8.11   Array of Objects                                 287

               Chapter 9 Strings and Text I/O                                 301
                       9.1   Introduction                                     302
                       9.2   The String Class                                 302
                       9.3   The Character Class                              313
                       9.4   The StringBuilder/StringBuffer Class             315
                       9.5   Command-Line Arguments                           320
                       9.6   The File Class                                   322
                       9.7   File Input and Output                            325
                       9.8   (GUI) File Dialogs                               329

               Chapter 10 Thinking in Objects                                 343
                      10.1   Introduction                                     344
                      10.2   Immutable Objects and Classes                    344
                      10.3   The Scope of Variables                           345
                      10.4   The this Reference                               346
                      10.5   Class Abstraction and Encapsulation              347
                                                                   Contents xvii
       10.6   Object-Oriented Thinking                      351
       10.7   Object Composition                            353
       10.8   Designing the Course Class                    355
       10.9   Designing a Class for Stacks                  357
      10.10   Designing the GuessDate Class                 359
      10.11   Class Design Guidelines                       362

Chapter 11 Inheritance and Polymorphism                     373
       11.1   Introduction                                  374
       11.2   Superclasses and Subclasses                   374
       11.3   Using the super Keyword                       380
       11.4   Overriding Methods                            382
       11.5   Overriding vs. Overloading                    383
       11.6   The Object Class and Its toString() Method    384
       11.7   Polymorphism                                  384
       11.8   Dynamic Binding                               385
       11.9   Casting Objects and the instanceof Operator   387
      11.10   The Object’s equals() Method                  389
      11.11   The ArrayList Class                           390
      11.12   A Custom Stack Class                          393
      11.13   The protected Data and Methods                394
      11.14   Preventing Extending and Overriding           396

Chapter 12 GUI Basics                                       405
       12.1   Introduction                                  406
       12.2   Swing vs. AWT                                 406
       12.3   The Java GUI API                              406
       12.4   Frames                                        408
       12.5   Layout Managers                                411
       12.6   Using Panels as Subcontainers                 417
       12.7   The Color Class                               419
       12.8   The Font Class                                419
       12.9   Common Features of Swing GUI Components       420
      12.10   Image Icons                                   422

Chapter 13 Exception Handling                               431
       13.1   Introduction                                  432
       13.2   Exception-Handling Overview                   432
       13.3   Exception-Handling Advantages                 434
       13.4   Exception Types                               437
       13.5   More on Exception Handling                    439
       13.6   The finally Clause                            445
       13.7   When to Use Exceptions                        447
       13.8   Rethrowing Exceptions                         447
       13.9   Chained Exceptions                            447
      13.10   Creating Custom Exception Classes             448
xviii Contents

                 Chapter 14 Abstract Classes and Interfaces                       457
                        14.1   Introduction                                       458
                        14.2   Abstract Classes                                   458
                        14.3   Example: Calendar and GregorianCalendar            462
                        14.4   Interfaces                                         465
                        14.5   Example: The Comparable Interface                  467
                        14.6   Example: The ActionListener Interface              469
                        14.7   Example: The Cloneable Interface                   471
                        14.8   Interfaces vs. Abstract Classes                    473
                        14.9   Processing Primitive Data Type Values as Objects   476
                       14.10   Sorting an Array of Objects                        479
                       14.11   Automatic Conversion between Primitive Types and
                               Wrapper Class Types                                481
                       14.12   The BigInteger and BigDecimal Classes              481
                       14.13   Case Study: The Rational Class                     482

                 Chapter 15 Graphics                                              497
                        15.1   Introduction                                       498
                        15.2   Graphical Coordinate Systems                       498
                        15.3   The Graphics Class                                 499
                        15.4   Drawing Strings, Lines, Rectangles, and Ovals      501
                        15.5   Case Study: The FigurePanel Class                  502
                        15.6   Drawing Arcs                                       506
                        15.7   Drawing Polygons and Polylines                     507
                        15.8   Centering a String Using the FontMetrics Class     510
                        15.9   Case Study: The MessagePanel Class                 512
                       15.10   Case Study: The StillClock Class                   516
                       15.11   Displaying Images                                  520
                       15.12   Case Study: The ImageViewer Class                  522

                 Chapter 16 Event-Driven Programming                              533
                        16.1   Introduction                                       534
                        16.2   Event and Event Source                             534
                        16.3   Listeners, Registrations, and Handling Events      535
                        16.4   Inner Classes                                      541
                        16.5   Anonymous Class Listeners                          542
                        16.6   Alternative Ways of Defining Listener Classes      544
                        16.7   Problem: Loan Calculator                           547
                        16.8   Window Events                                      549
                        16.9   Listener Interface Adapters                         551
                       16.10   Mouse Events                                       552
                       16.11   Key Events                                         555
                       16.12   Animation Using the Timer Class                    557

                 Chapter 17 Creating Graphical User Interfaces                    571
                        17.1   Introduction                                       572
                        17.2   Buttons                                            572
                        17.3   Check Boxes                                        578
                                                              Contents xix
       17.4   Radio Buttons                             581
       17.5   Labels                                    583
       17.6   Text Fields                               584
       17.7   Text Areas                                586
       17.8   Combo Boxes                               590
       17.9   Lists                                     593
      17.10   Scroll Bars                               596
      17.11   Sliders                                   599
      17.12   Creating Multiple Windows                 602

Chapter 18 Applets and Multimedia                       613
       18.1   Introduction                              614
       18.2   Developing Applets                        614
       18.3   The HTML File and the <applet> Tag        615
       18.4   Applet Security Restrictions              618
       18.5   Enabling Applets to Run as Applications   618
       18.6   Applet Life-Cycle Methods                 620
       18.7   Passing Strings to Applets                620
       18.8   Case Study: Bouncing Ball                 624
       18.9   Case Study: TicTacToe                     628
      18.10   Locating Resources Using the URL Class    632
      18.11   Playing Audio in Any Java Program         633
      18.12   Case Study: Multimedia Animations         634


Chapter 19 Binary I/O                                   649
       19.1   Introduction                              650
       19.2   How is I/O Handled in Java?               650
       19.3   Text I/O vs. Binary I/O                   650
       19.4   Binary I/O Classes                        652
       19.5   Problem: Copying Files                    660
       19.6   Object I/O                                662
       19.7   Random-Access Files                       666

Chapter 20 Recursion                                    677
       20.1   Introduction                              678
       20.2   Problem: Computing Factorials             678
       20.3   Problem: Computing Fibonacci Numbers      681
       20.4   Problem Solving Using Recursion           683
       20.5   Recursive Helper Methods                  684
       20.6   Problem: Finding the Directory Size       687
       20.7   Problem: Towers of Hanoi                  688
       20.8   Problem: Fractals                         692
       20.9   Problem: Eight Queens                     695
      20.10   Recursion vs. Iteration                   697
      20.11   Tail Recursion                            697
xx Contents

              Chapter 21 Generics                                                        707
                      21.1   Introduction                                                708
                      21.2   Motivations and Benefits                                    708
                      21.3   Defining Generic Classes and Interfaces                     710
                      21.4   Generic Methods                                             712
                      21.5   Raw Type and Backward Compatibility                         713
                      21.6   Wildcard Generic Types                                      714
                      21.7   Erasure and Restrictions on Generics                        716
                      21.8   Case Study: Generic Matrix Class                            719

              Chapter 22 Java Collections Framework                                      727
                      22.1   Introduction                                                728
                      22.2   Collections                                                 728
                      22.3   The Collection Interface and the AbstractCollection Class   729
                      22.4   Sets                                                        730
                      22.5   The Comparator Interface                                    737
                      22.6   Lists                                                       738
                      22.7   Static Methods for Lists and Collections                    742
                      22.8   Performance of Sets and Lists                               745
                      22.9   The Vector and Stack Classes                                746
                     22.10   Queues and Priority Queues                                  748
                     22.11   Maps                                                        751
                     22.12   Singleton and Unmodifiable Collections and Maps             756

              Chapter 23 Algorithm Efficiency                                            765
                     23.1    Introduction                                                766
                     23.2    Big O Notation                                              766
                     23.3    Examples: Determining Big O                                 767
                     23.4    Analyzing Algorithm Time Complexity                         769
                     23.5    Case Studies: Finding Fibonacci Numbers                     771
                     23.6    Case Studies: Finding Greatest Common Divisors              774
                     23.7    Case Studies: Finding Prime Numbers                         778
                     23.8    Case Studies: Closest Pair of Points                        783
                     23.9    Preview of Other Algorithms                                 785

              Chapter 24 Sorting                                                         791
                     24.1    Introduction                                                792
                     24.2    Bubble Sort                                                 792
                     24.3    Merge Sort                                                  794
                     24.4    Quick Sort                                                  797
                     24.5    Heap Sort                                                   801
                     24.6    Bucket Sort and Radix Sort                                  807
                     24.7    External Sort                                               809

              Chapter 25 Lists, Stacks, Queues, and Priority Queues                      821
                     25.1    Introduction                                                822
                     25.2    Common Features for Lists                                   822
                                                                  Contents xxi
       25.3   Array Lists                                  825
       25.4   Linked Lists                                 830
       25.5   Variations of Linked Lists                   842
       25.6   Stacks and Queues                            843
       25.7   Priority Queues                              846
       25.8   Case Study: Evaluating Expressions           847


Chapter 26 Binary Search Trees                             857
       26.1   Introduction                                 858
       26.2   Binary Search Trees                          858
       26.3   Deleting Elements in a BST                   870
       26.4   Tree Visualization                           876
       26.5   Iterators                                    879
       26.6   Case Study: Data Compression                 881


Chapter 27 Graphs and Applications                         891
       27.1   Introduction                                 892
       27.2   Basic Graph Terminologies                    893
       27.3   Representing Graphs                          894
       27.4   Modeling Graphs                              898
       27.5   Graph Visualization                          909
       27.6   Graph Traversals                              911
       27.7   Depth-First Search (DFS)                     912
       27.8   Breadth-First Search (BFS)                   916
       27.9   Case Study: The Nine Tail Problem            919
      27.10   Case Study: The Knight’s Tour Problem        923


Chapter 28 Weighted Graphs and Applications                939
       28.1   Introduction                                 940
       28.2   Representing Weighted Graphs                 940
       28.3   The WeightedGraph Class                      942
       28.4   Minimum Spanning Trees                       949
       28.5   Finding Shortest Paths                       955
       28.6   Case Study: The Weighted Nine Tail Problem   962


Chapter 29 Multithreading                                  971
       29.1   Introduction                                 972
       29.2   Thread Concepts                              972
       29.3   Creating Tasks and Threads                   972
       29.4   The Thread Class                             975
       29.5   Example: Flashing Text                       978
       29.6   GUI Event Dispatch Thread                    979
       29.7   Case Study: Clock with Audio                 980
       29.8   Thread Pools                                 983
xxii Contents
                        29.9   Thread Synchronization                        985
                       29.10   Synchronization Using Locks                   989
                       29.11   Cooperation among Threads                     991
                       29.12   Case Study: Producer/Consumer                 995
                       29.13   Blocking Queues                               998
                       29.14   Semaphores                                  1000
                       29.15   Avoiding Deadlocks                           1001
                       29.16   Thread States                               1002
                       29.17   Synchronized Collections                    1002
                       29.18   SwingWorker                                 1004
                       29.19   Displaying Progress Using JProgressBar      1007

                Chapter 30 Networking                                      1017
                       30.1    Introduction                                1018
                       30.2    Client/Server Computing                     1018
                       30.3    The InetAddress Class                       1025
                       30.4    Serving Multiple Clients                    1026
                       30.5    Applet Clients                              1029
                       30.6    Sending and Receiving Objects                1031
                       30.7    Retrieving Files from Web Servers           1036
                       30.8    JEditorPane                                 1039
                       30.9    Case Studies: Distributed TicTacToe Games   1041

                Chapter 31 Internationalization                            1057
                        31.1   Introduction                                1058
                        31.2   The Locale Class                            1058
                        31.3   Displaying Date and Time                    1060
                        31.4   Formatting Numbers                           1071
                        31.5   Resource Bundles                            1077
                        31.6   Character Encoding                          1084

                Chapter 32 JavaBeans and Bean Events                       1091
                       32.1    Introduction                                1092
                       32.2    JavaBeans                                   1092
                       32.3    Bean Properties                             1093
                       32.4    Java Event Model Review                     1094
                       32.5    Creating Custom Source Components           1097
                       32.6    Creating Custom Event Sets                   1101

                Chapter 33 Containers, Layout Managers, and Borders         1111
                       33.1    Introduction                                1112
                       33.2    Swing Container Structures                  1112
                       33.3    Layout Managers                             1114
                       33.4    Creating Custom Layout Managers             1123
                                                                              Contents xxiii
       33.5   JScrollPane                                             1128
       33.6   JTabbedPane                                             1132
       33.7   JSplitPane                                              1133
       33.8   Swing Borders                                           1136

Chapter 34 Menus, Toolbars, and Dialogs                               1149
       34.1   Introduction                                            1150
       34.2   Menus                                                   1150
       34.3   Popup Menus                                             1156
       34.4   JToolBar                                                1158
       34.5   Processing Actions Using the Action Interface           1160
       34.6   JOptionPane Dialogs                                     1164
       34.7   Creating Custom Dialogs                                  1171
       34.8   JColorChooser                                           1174
       34.9   JFileChooser                                            1176

Chapter 35 MVC and Swing Models                                       1187
       35.1   Introduction                                            1188
       35.2   MVC                                                     1188
       35.3   MVC Variations                                          1194
       35.4   Swing Model-View-Controller Architecture                 1195
       35.5   JSpinner                                                1196
       35.6   Spinner Models and Editors                              1198
       35.7   JList and its Models                                    1205
       35.8   List Models                                             1209
       35.9   List Cell Renderer                                       1212
      35.10   JComboBox and its Models                                1216


Chapter 36 JTable and JTree                                           1225
       36.1   Introduction                                            1226
       36.2   JTable                                                  1226
       36.3   Table Models and Table Column Models                     1231
       36.4   Auto Sort and Filtering                                 1235
       36.5   Case Study: Modifying Rows and Columns                  1237
       36.6   Table Renderers and Editors                             1242
       36.7   Custom Table Renderers and Editors                      1245
       36.8   Table Model Events                                      1247
       36.9   JTree                                                   1250
      36.10   TreeModel and DefaultTreeModel                          1254
      36.11   TreeNode, MutableTreeNode, and DefaultMutableTreeNode   1256
      36.12   TreePath and TreeSelectionModel                         1259
      36.13   Case Study: Modifying Trees                             1262
      36.14   Tree Node Rendering and Editing                         1265
      36.15   Tree Events                                             1267
xxiv Contents

                Chapter 37 Java Database Programming                                    1273
                          37.1   Introduction                                           1274
                          37.2   Relational Database Systems                            1274
                          37.3   SQL                                                    1278
                          37.4   JDBC                                                   1286
                          37.5   PreparedStatement                                      1295
                          37.6   CallableStatement                                      1297
                          37.7   Retrieving Metadata                                    1300

                A detailed table of contents for the Web chapters is available on the
                companion Web site:
                Chapter 38 Advanced Java Database Programming                           38–1

                Chapter 39 Servlets                                                     39–1

                Chapter 40 JavaServer Pages                                             40–1

                Chapter 41 JSF and Visual Web Development                               41–1

                Chapter 42 Web Services                                                 42–1

                Chapter 43 Remote Method Invocation                                     43–1

                Chapter 44 Java 2D                                                      44-1

                Chapter 45 AVL Trees and Splay Trees                                    45-1

                Chapter 46 2-4 Trees and B-Trees                                        46-1

                Chapter 47 Red-Black Trees                                              47-1

                Chapter 48 Hashing                                                      48-1


                APPENDIXES
                 Appendix A      Java Keywords                                          1309
                 Appendix B      The ASCII Character Set                                1312
                 Appendix C      Operator Precedence Chart                              1314
                 Appendix D      Java Modifiers                                         1316
                 Appendix E      Special Floating-Point Values                          1318
                 Appendix F      Number Systems                                         1319

                INDEX                                                                   1323
                                                            CHAPTER 1
INTRODUCTION TO COMPUTERS,
PROGRAMS, AND JAVA
Objectives
■   To review computer basics, programs, and operating systems (§§1.2–1.4).
■   To explore the relationship between Java and the World Wide Web (§1.5).
■   To distinguish the terms API, IDE, and JDK (§1.6).
■   To write a simple Java program (§1.7).
■   To display output on the console (§1.7).
■   To explain the basic syntax of a Java program (§1.7).
■   To create, compile, and run Java programs (§1.8).
■   (GUI) To display output using the JOptionPane
    output dialog boxes (§1.9).
2 Chapter 1 Introduction to Computers, Programs, and Java

                     1.1 Introduction
                     You use word processors to write documents, Web browsers to explore the Internet, and email
                     programs to send email. These are all examples of software that runs on computers. Software
                     is developed using programming languages. There are many programming languages—so
why Java?            why Java? The answer is that Java enables users to develop and deploy applications on the
                     Internet for servers, desktop computers, and small hand-held devices. The future of comput-
                     ing is being profoundly influenced by the Internet, and Java promises to remain a big part of
                     that future. Java is the Internet programming language.
                        You are about to begin an exciting journey, learning a powerful programming language. At
                     the outset, it is helpful to review computer basics, programs, and operating systems and to
                     become familiar with number systems. If you are already familiar with such terms as CPU,
                     memory, disks, operating systems, and programming languages, you may skip the review in
                     §§1.2–1.4.


                     1.2 What Is a Computer?
hardware             A computer is an electronic device that stores and processes data. It includes both hardware
software             and software. In general, hardware comprises the visible, physical elements of the computer,
                     and software provides the invisible instructions that control the hardware and make it perform
                     specific tasks. Writing instructions for computers to perform is called computer program-
                     ming. Knowing computer hardware isn’t essential to your learning a programming language,
                     but it does help you understand better the effect of the program instructions. This section
                     introduces computer hardware components and their functions.
                        A computer consists of the following major hardware components (Figure 1.1):
                           ■    Central processing unit (CPU)
                           ■    Memory (main memory)
                           ■    Storage devices (e.g., disks, CDs, tapes)
                           ■    Input and output devices (e.g., monitors, keyboards, mice, printers)
                           ■    Communication devices (e.g., modems and network interface cards (NICs))


                                                                   Bus



                               Storage                            Communication         Input           Output
                                            Memory      CPU
                               Devices                               Devices           Devices          Devices
                          e.g., Disk, CD,                           e.g., Modem     e.g., Keyboard,   e.g., Monitor,
                             and Tape                                 and NIC            Mouse            Printer

                     FIGURE 1.1 A computer consists of CPU, memory, storage devices, input devices, output
                     devices, and communication devices.


bus                    The components are connected through a subsystem called a bus that transfers data or
                     power between them.

                     1.2.1 Central Processing Unit
CPU                  The central processing unit (CPU) is the computer’s brain. It retrieves instructions from
                     memory and executes them. The CPU usually has two components: a control unit and an
                     arithmetic/logic unit. The control unit controls and coordinates the actions of the other
                                                                                         1.2 What Is a Computer? 3
components. The arithmetic/logic unit performs numeric operations (addition, subtraction,
multiplication, division) and logical operations (comparisons).
   Today’s CPU is built on a small silicon semiconductor chip having millions of transistors.
Every computer has an internal clock, which emits electronic pulses at a constant rate. These
pulses are used to control and synchronize the pace of operations. The higher the clock speed,
the more instructions are executed in a given period of time. The unit of measurement of clock
speed is the hertz (Hz), with 1 hertz equaling 1 pulse per second. The clock speed of a com-        speed
puter is usually stated in megahertz (MHz) (1 MHz is 1 million Hz). CPU speed has been              hertz
improved continuously. Intel’s Pentium 3 Processor runs at about 500 megahertz and Pentium          megahertz
4 Processor at about 3 gigahertz (GHz) (1 GHz is 1000 MHz).                                         gigahertz


1.2.2 Memory
To store and process information, computers use off and on electrical states, referred to by
convention as 0 and 1. These 0s and 1s are interpreted as digits in the binary number system
and called bits (binary digits). Data of various kinds, such as numbers, characters, and strings,   bit
are encoded as series of bits. Data and program instructions for the CPU to execute are stored
as groups of bits, or bytes, each byte composed of eight bits, in a computer’s memory. A
memory unit is an ordered sequence of bytes, as shown in Figure 1.2.                                byte


                       Memory address    Memory content




                                 2000   01001010   Encoding for character ‘J’
                                 2001   01100001   Encoding for character ‘a’
                                 2002   01110110   Encoding for character ‘v’
                                 2003   01100001   Encoding for character ‘a’
                                 2004   00000011   Encoding for number 3




FIGURE 1.2   Memory stores data and program instructions.

   The programmer need not be concerned about the encoding and decoding of data, which
the system performs automatically, based on the encoding scheme. In the popular ASCII
encoding scheme, for example, character 'J' is represented by 01001010 in one byte.
   A byte is the minimum storage unit. A small number such as 3 can be stored in a single
byte. To store a number that cannot fit into a single byte, the computer uses several adjacent
bytes. No two data items can share or split the same byte.
   A memory byte is never empty, but its initial content may be meaningless to your program.
The current content of a memory byte is lost whenever new information is placed in it.
   A program and its data must be brought to memory before they can be executed.
   Every byte has a unique address. The address is used to locate the byte for storing and
retrieving data. Since bytes can be accessed in any order, the memory is also referred to as
random-access memory (RAM). Today’s personal computers usually have at least 1 gigabyte
of RAM. Computer storage size is measured in bytes, kilobytes (KB), megabytes (MB), giga-           RAM
bytes (GB), and terabytes (TB). A kilobyte is 210 = 1024, about 1000 bytes, a megabyte is           megabyte
220 = 1048576, about 1 million bytes, a gigabyte is about 1 billion bytes, and a terabyte is
about 1000 gigabytes. Like the CPU, memory is built on silicon semiconductor chips having
thousands of transistors embedded on their surface. Compared to CPU chips, memory chips
are less complicated, slower, and less expensive.
4 Chapter 1 Introduction to Computers, Programs, and Java

                     1.2.3      Storage Devices
                     Memory is volatile, because information is lost when the power is turned off. Programs and
                     data are permanently stored on storage devices and are moved, when the computer actually
                     uses them, to memory, which is much faster than storage devices.
                        There are four main types of storage devices:
                           ■   Disk drives
                           ■   CD drives (CD-R, CD-RW, and DVD)
                           ■   Tape drives
                           ■   USB flash drives
drive                Drives are devices for operating a medium, such as disks, CDs, and tapes.

                     Disks
hard disk            Each computer has at least one hard drive. Hard disks are for permanently storing data and
                     programs. The hard disks of the latest PCs store from 80 to 250 gigabytes. Often disk drives
                     are encased inside the computer. Removable hard disks are also available.

                     CDs and DVDs
CD-R                 CD stands for compact disk. There are two types of CD drives: CD-R and CD-RW. A CD-R is
                     for read-only permanent storage; the user cannot modify its contents once they are recorded.
CD-RW                A CD-RW can be used like a hard disk and can be both read and rewritten. A single CD can
                     hold up to 700 MB. Most software is distributed through CD-ROMs. Most new PCs are
                     equipped with a CD-RW drive that can work with both CD-R and CD-RW.
                        DVD stands for digital versatile disc or digital video disk. DVDs and CDs look alike, and
                     you can use either to store data. A DVD can hold more information than a CD. A standard
                     DVD’s storage capacity is 4.7 GB.

                     Tapes
                     Tapes are mainly used for backup of data and programs. Unlike disks and CDs, tapes store
                     information sequentially. The computer must retrieve information in the order it was stored.
                     Tapes are very slow. It would take one to two hours to back up a 1-gigabyte hard disk. The
                     new trend is to back up data using flash drives or external hard disks.

                     USB Flash Drives
                     USB flash drives are devices for storing and transporting data. A flash drive is small—about
                     the size of a pack of gum. It acts like a portable hard drive that can be plugged into your com-
                     puter’s USB port. USB flash drives are currently available with up to 32 GB storage capacity.

                     1.2.4      Input and Output Devices
                     Input and output devices let the user communicate with the computer. The common input
                     devices are keyboards and mice. The common output devices are monitors and printers.

                     The Keyboard
                     A computer keyboard resembles a typewriter keyboard with extra keys added for certain spe-
                     cial functions.
function key            Function keys are located at the top of the keyboard and are numbered with prefix F. Their
                     use depends on the software.
modifier key            A modifier key is a special key (e.g., Shift, Alt, Ctrl) that modifies the normal action of
                     another key when the two are pressed in combination.
                                                                                                          1.3 Programs 5
   The numeric keypad, located on the right-hand corner of the keyboard, is a separate set of      numeric keypad
keys for quick input of numbers.
   Arrow keys, located between the main keypad and the numeric keypad, are used to move
the cursor up, down, left, and right.
   The Insert, Delete, Page Up, and Page Down keys, located above the arrow keys, are used
in word processing for performing insert, delete, page up, and page down.
The Mouse
A mouse is a pointing device. It is used to move an electronic pointer called a cursor around
the screen or to click on an object on the screen to trigger it to respond.
The Monitor
The monitor displays information (text and graphics). The screen resolution and dot pitch
determine the quality of the display.
   The screen resolution specifies the number of pixels per square inch. Pixels (short for “pic-   screen resolution
ture elements”) are tiny dots that form an image on the screen. A common resolution for a 17-
inch screen, for example, is 1024 pixels wide and 768 pixels high. The resolution can be set
manually. The higher the resolution, the sharper and clearer the image is.
   The dot pitch is the amount of space between pixels in millimeters. The smaller the dot         dot pitch
pitch, the better the display.

1.2.5     Communication Devices
Computers can be networked through communication devices, such as the dialup modem
(modulator/demodulator), DSL, cable modem, network interface card, and wireless. A dialup          modem
modem uses a phone line and can transfer data at a speed up to 56,000 bps (bits per second).
A DSL (digital subscriber line) also uses a phone line and can transfer data twenty times          DSL
faster. A cable modem uses the TV cable line maintained by the cable company and is as fast
as a DSL. A network interface card (NIC) is a device that connects a computer to a local area      NIC
network (LAN). The LAN is commonly used in universities and business and government                LAN
organizations. A typical NIC called 10BaseT can transfer data at 10 mbps (million bits per         mbps
second). Wireless is becoming popular. Every laptop sold today is equipped with a wireless
adapter that enables the computer to connect with the Internet.


1.3 Programs
Computer programs, known as software, are instructions to the computer, telling it what to do.     software
Computers do not understand human languages, so you need to use computer languages in
computer programs. Programming is the creation of a program that is executable by a com-           programming
puter and performs the required tasks.
   A computer’s native language, which differs among different types of computers, is its
machine language—a set of built-in primitive instructions. These instructions are in the form      machine language
of binary code, so in telling the machine what to do, you have to enter binary code. Program-
ming in machine language is a tedious process. Moreover, the programs are highly difficult to
read and modify. For example, to add two numbers, you might have to write an instruction in
binary like this:
   1101101010011010

   Assembly language is a low-level programming language in which a mnemonic is used to            assembly language
represent each of the machine-language instructions. For example, to add two numbers, you
might write an instruction in assembly code like this:
   ADDF3 R1, R2, R3
6 Chapter 1 Introduction to Computers, Programs, and Java
                         Assembly languages were developed to make programming easy. However, since the com-
assembler             puter cannot understand assembly language, a program called an assembler is used to convert
                      assembly-language programs into machine code, as shown in Figure 1.3.


                               Assembly Source File                                   Machine-Code File

                                      ..                                                    ..
                               ADDF3 R1, R2, R3                   Assembler          1101101010011010
                                      ..                                                    ..


                      FIGURE 1.3   Assembler translates assembly-language instructions to machine code.


                         Assembly programs are written in terms of machine instructions with easy-to-remember
                      mnemonic names. Since assembly language is machine dependent, an assembly program can
                      be executed only on a particular kind of machine. The high-level languages were developed in
                      order to transcend platform specificity and make programming easier.
high-level language      The high-level languages are English-like and easy to learn and program. Here, for exam-
                      ple, is a high-level language statement that computes the area of a circle with radius 5:

                        area = 5 * 5 * 3.1415;

                        Among the more than one hundred high-level languages, the following are well known:
                           ■   COBOL (COmmon Business Oriented Language)
                           ■   FORTRAN (FORmula TRANslation)
                           ■   BASIC (Beginner’s All-purpose Symbolic Instruction Code)
                           ■   Pascal (named for Blaise Pascal)
                           ■   Ada (named for Ada Lovelace)
                           ■   C (developed by the designer of B)
                           ■   Visual Basic (Basic-like visual language developed by Microsoft)
                           ■   Delphi (Pascal-like visual language developed by Borland)
                           ■   C++ (an object-oriented language, based on C)
                           ■   C# (a Java-like language developed by Microsoft)
                           ■   Java

                      Each of these languages was designed for a specific purpose. COBOL was designed for busi-
                      ness applications and is used primarily for business data processing. FORTRAN was
                      designed for mathematical computations and is used mainly for numeric computations.
                      BASIC was designed to be learned and used easily. Ada was developed for the Department
                      of Defense and is used mainly in defense projects. C combines the power of an assembly lan-
                      guage with the ease of use and portability of a high-level language. Visual Basic and Delphi
                      are used in developing graphical user interfaces and in rapid application development. C++
                      is popular for system software projects such as writing compilers and operating systems. The
                      Microsoft Windows operating system was coded using C++. C# (pronounced C sharp) is a
                      new language developed by Microsoft for developing applications based on the Microsoft
                      .NET platform. Java, developed by Sun Microsystems, is widely used for developing plat-
                      form-independent Internet applications.
                                                                                          1.4 Operating Systems 7
   A program written in a high-level language is called a source program or source code.        source program
Since a computer cannot understand a source program, a program called a compiler is used to     compiler
translate it into a machine-language program. The machine-language program is then linked
with other supporting library code to form an executable file, which can be run on the
machine, as shown in Figure 1.4. On Windows, executable files have extension .exe.



      Source File       Compiler       Machine-language       Linker        Executable
                                             File                              File


                                         Library Code


FIGURE 1.4 A source program is compiled into a machine-language file, which is then
linked with the system library to form an executable file.


1.4 Operating Systems
The operating system (OS) is the most important program that runs on a computer, which          OS
manages and controls a computer’s activities. The popular operating systems are Microsoft
Windows, Mac OS, and Linux. Application programs, such as a Web browser or a word
processor, cannot run without an operating system. The interrelationship of hardware, operat-
ing system, application software, and the user is shown in Figure 1.5.


                                          User



                                   Application Programs



                                     Operating System



                                        Hardware


FIGURE 1.5   The operating system is the software that controls and manages the system.


   The major tasks of an operating system are:
      ■   Controlling and monitoring system activities
      ■   Allocating and assigning system resources
      ■   Scheduling operations

1.4.1 Controlling and Monitoring System Activities
Operating systems perform basic tasks, such as recognizing input from the keyboard, sending
output to the monitor, keeping track of files and directories on the disk, and controlling
peripheral devices, such as disk drives and printers. They also make sure that different pro-
grams and users running at the same time do not interfere with each other, and they are
responsible for security, ensuring that unauthorized users do not access the system.
8 Chapter 1 Introduction to Computers, Programs, and Java

                     1.4.2     Allocating and Assigning System Resources
                     The operating system is responsible for determining what computer resources a program
                     needs (e.g., CPU, memory, disks, input and output devices) and for allocating and assigning
                     them to run the program.

                     1.4.3     Scheduling Operations
                     The OS is responsible for scheduling programs to make efficient use of system resources. Many
                     of today’s operating systems support such techniques as multiprogramming, multithreading, or
                     multiprocessing to increase system performance.
multiprogramming        Multiprogramming allows multiple programs to run simultaneously by sharing the CPU.
                     The CPU is much faster than the computer’s other components. As a result, it is idle most of
                     the time—for example, while waiting for data to be transferred from the disk or from other
                     sources. A multiprogramming OS takes advantage of this situation by allowing multiple pro-
                     grams to use the CPU when it would otherwise be idle. For example, you may use a word
                     processor to edit a file at the same time as the Web browser is downloading a file.
multithreading          Multithreading allows concurrency within a program, so that its subtasks can run at the
                     same time. For example, a word-processing program allows users to simultaneously edit text
                     and save it to a file. In this example, editing and saving are two tasks within the same applica-
                     tion. These two tasks may run on separate threads concurrently.
multiprocessing         Multiprocessing, or parallel processing, uses two or more processors together to perform a
                     task. It is like a surgical operation where several doctors work together on one patient.


                     1.5 Java, World Wide Web, and Beyond
                     This book     introduces Java programming. Java was developed by a team led by James
                     Gosling at    Sun Microsystems. Originally called Oak, it was designed in 1991 for use in
                     embedded      chips in consumer electronic appliances. In 1995, renamed Java, it was
                     redesigned      for developing Internet applications. For the history of Java, see
                     java.sun.com/features/1998/05/birthday.html.
                         Java has become enormously popular. Its rapid rise and wide acceptance can be traced to
                     its design characteristics, particularly its promise that you can write a program once and run it
                     anywhere. As stated by Sun, Java is simple, object oriented, distributed, interpreted, robust,
                     secure, architecture neutral, portable, high performance, multithreaded, and dynamic. For the
                     anatomy of Java characteristics, see www.cs.armstrong.edu/liang/JavaCharacteristics.pdf.
                         Java is a full-featured, general-purpose programming language that can be used to develop
                     robust mission-critical applications. Today, it is employed not only for Web programming, but
                     also for developing standalone applications across platforms on servers, desktops, and mobile
                     devices. It was used to develop the code to communicate with and control the robotic rover on
                     Mars. Many companies that once considered Java to be more hype than substance are now
                     using it to create distributed applications accessed by customers and partners across the Inter-
                     net. For every new project being developed today, companies are asking how they can use
                     Java to make their work easier.
                         The World Wide Web is an electronic information repository that can be accessed on the
                     Internet from anywhere in the world. The Internet, the Web’s infrastructure, has been around
                     for more than thirty years. The colorful World Wide Web and sophisticated Web browsers are
                     the major reason for the Internet’s popularity.
                         The primary authoring language for the Web is the Hypertext Markup Language (HTML).
                     HTML is a simple language for laying out documents, linking documents on the Internet, and
                     bringing images, sound, and video alive on the Web. However, it cannot interact with the user
                     except through simple forms. Web pages in HTML are essentially static and flat.
                         Java initially became attractive because Java programs can be run from a Web browser.
applet               Such programs are called applets. Applets employ a modern graphical interface with buttons,
                                                                                  1.5 Java, World Wide Web, and Beyond 9
text fields, text areas, radio buttons, and so on, to interact with users on the Web and process
their requests. Applets make the Web responsive, interactive, and fun to use. Figure 1.6 shows
an applet running from a Web browser for playing a Tic Tac Toe game.

                          Enter this URL from a Web browser




FIGURE 1.6    A Java applet for playing TicTacToe is embedded in an HTML page.


     Tip
      For a demonstration of Java applets, visit java.sun.com/applets. This site provides a rich Java
      resource as well as links to other cool applet demo sites. java.sun.com is the official Sun Java Web-
      site.

   Java can also be used to develop applications on the server side. These applications can be
run from a Web server to generate dynamic Web pages. The automatic grading system for this
book, as shown in Figure 1.7, was developed using Java.

                                Enter this URL from a Web browser




FIGURE 1.7    Java was used to develop an automatic grading system to accompany this book.
10 Chapter 1 Introduction to Computers, Programs, and Java
                                 Java is a versatile programming language. You can use it to develop applications on
                              your desktop and on the server. You can also use it to develop applications for small hand-
                              held devices. Figure 1.8 shows a Java-programmed calendar displayed on a BlackBerry©
                              and on a cell phone.




                              FIGURE 1.8 Java can be used to develop applications for hand-held and wireless devices,
                              such as a BlackBerry© (left) and a cell phone (right).


                              1.6 The Java Language Specification, API, JDK, and IDE
                              Computer languages have strict rules of usage. If you do not follow the rules when writing a
                              program, the computer will be unable to understand it. The Java language specification and
                              Java API define the Java standard.
Java language specification      The Java language specification is a technical definition of the language that includes the
                              syntax and semantics of the Java programming language. The complete Java language speci-
                              fication can be found at java.sun.com/docs/books/jls.
API                              The application program interface (API) contains predefined classes and interfaces for
                              developing Java programs. The Java language specification is stable, but the API is still
                              expanding. At the Sun Java Website (java.sun.com), you can view and download the latest ver-
                              sion of the Java API.
                                 Java is a full-fledged and powerful language that can be used in many ways. It comes in
Java SE, EE, and ME           three editions: Java Standard Edition (Java SE), Java Enterprise Edition (Java EE), and Java
                              Micro Edition (Java ME). Java SE can be used to develop client-side standalone applications
                              or applets. Java EE can be used to develop server-side applications, such as Java servlets and
                              JavaServer Pages. Java ME can be used to develop applications for mobile devices, such as
                              cell phones. This book uses Java SE to introduce Java programming.
                                 There are many versions of Java SE. The latest, Java SE 6, will be used in this book. Sun
                              releases each version with a Java Development Toolkit (JDK). For Java SE 6, the Java Devel-
JDK 1.6 = JDK 6               opment Toolkit is called JDK 1.6 (also known as Java 6 or JDK 6).
                                 JDK consists of a set of separate programs, each invoked from a command line, for devel-
                              oping and testing Java programs. Besides JDK, you can use a Java development tool (e.g., Net-
Java IDE                      Beans, Eclipse, and TextPad)—software that provides an integrated development environment
                              (IDE) for rapidly developing Java programs. Editing, compiling, building, debugging, and
                                                                                     1.7 A Simple Java Program 11
online help are integrated in one graphical user interface. Just enter source code in one window
or open an existing file in a window, then click a button, menu item, or function key to compile
and run the program.


1.7 A Simple Java Program
Let us begin with a simple Java program that displays the message “Welcome to Java!” on the
console. Console refers to text entry and display device of a computer. The program is shown       console
in Listing 1.1.


LISTING 1.1 Welcome.java                                                                           Video Note
                                                                                                   First Java program
1 public class Welcome {                                                                           class
2   public static void main(String[] args) {                                                       main method
3     // Display message Welcome to Java! to the console
4     System.out.println("Welcome to Java!");                                                      display message
5   }
6 }


 Welcome to Java!


   The line numbers are displayed for reference purposes but are not part of the program. So,      line numbers
don’t type line numbers in your program.
   Line 1 defines a class. Every Java program must have at least one class. Each class has a
name. By convention, class names start with an uppercase letter. In this example, the class        class name
name is Welcome.
   Line 2 defines the main method. In order to run a class, the class must contain a method        main method
named main. The program is executed from the main method.
   A method is a construct that contains statements. The main method in this program con-
tains the System.out.println statement. This statement prints a message "Welcome to
Java!" to the console (line 4). Every statement in Java ends with a semicolon (;), known as
the statement terminator.                                                                          statement terminator
   Reserved words, or keywords, have a specific meaning to the compiler and cannot be used         reserved word
for other purposes in the program. For example, when the compiler sees the word class, it
understands that the word after class is the name for the class. Other reserved words in this
program are public, static, and void.
   Line 3 is a comment that documents what the program is and how it is constructed. Com-          comment
ments help programmers to communicate and understand the program. They are not pro-
gramming statements and thus are ignored by the compiler. In Java, comments are preceded
by two slashes (//) on a line, called a line comment, or enclosed between /* and */ on one or
several lines, called a block comment. When the compiler sees //, it ignores all text after //
on the same line. When it sees /*, it scans for the next */ and ignores any text between /*
and */. Here are examples of comments:

   // This application program prints Welcome to Java!
   /* This application program prints Welcome to Java! */
   /* This application program
      prints Welcome to Java! */

   A pair of braces in a program forms a block that groups the program’s components. In Java,      block
each block begins with an opening brace ({) and ends with a closing brace (}). Every class
has a class block that groups the data and methods of the class. Every method has a method
12 Chapter 1 Introduction to Computers, Programs, and Java
                     block that groups the statements in the method. Blocks can be nested, meaning that one block
                     can be placed within another, as shown in the following code.

                             public class Welcome {
                               public static void main(String[] args) {               Class block
                                 System.out.println("Welcome to Java!"); Method block
                               }
                             }



                          Tip
matching braces           An opening brace must be matched by a closing brace. Whenever you type an opening brace,
                          immediately type a closing brace to prevent the missing-brace error. Most Java IDEs automatically
                          insert the closing brace for each opening brace.


                          Note
                          You are probably wondering why the main method is declared this way and why
                          System.out.println(...) is used to display a message to the console. For the time being,
                          simply accept that this is how things are done. Your questions will be fully answered in subse-
                          quent chapters.


                          Caution
case sensitive            Java source programs are case sensitive. It would be wrong, for example, to replace main in the
                          program with Main.


                          Note
                          Like any programming language, Java has its own syntax, and you need to write code that obeys
syntax rules              the syntax rules. If your program violates the rules—for example if the semicolon is missing, a
                          brace is missing, a quotation mark is missing, or String is misspelled—the Java compiler will
                          report syntax errors. Try to compile the program with these errors and see what the compiler
                          reports.

                     The program in Listing 1.1 displays one message. Once you understand the program, it is
                     easy to extend it to display more messages. For example, you can rewrite the program to dis-
                     play three messages, as shown in Listing 1.2.

                     LISTING 1.2 Welcome1.java
class                1 public class Welcome1 {
main method          2   public static void main(String[] args) {
display message      3     System.out.println("Programming is fun!");
                     4     System.out.println("Fundamentals First");
                     5     System.out.println("Problem Driven");
                     6   }
                     7 }


                      Programming is fun!
                      Fundamentals First
                      Problem Driven


                        Further, you can perform mathematical computations and display the result to the console.
                                                                10.5 + 2 * 3
                     Listing 1.3 gives an example of evaluating              .
                                                                  45 - 3.5
                                                      1.8 Creating, Compiling, and Executing a Java Program 13

LISTING 1.3 ComputeExpression.java
1 public class ComputeExpression {                                                                      class
2   public static void main(String[] args) {                                                            main method
3     System.out.println((10.5 + 2 * 3) / (45 – 3.5));                                                  compute expression
4   }
5 }



 0.39759036144578314



   The multiplication operator in Java is *. As you see, it is a straightforward process to trans-
late an arithmetic expression to a Java expression. We will discuss Java expressions further in
Chapter 2.


1.8 Creating, Compiling, and Executing a Java Program
You have to create your program and compile it before it can be executed. This process is
repetitive, as shown in Figure 1.9. If your program has compilation errors, you have to mod-
ify the program to fix them, then recompile it. If your program has runtime errors or does not
produce the correct result, you have to modify the program, recompile it, and execute it
again.


                                                                       Create/Modify Source Code

                Source code (developed by the programmer)
         public class Welcome {                      Saved on the disk
           public static void main(String[] args) {
             System.out.println("Welcome to Java!");              Source Code
           }
         }


              Bytecode (generated by the compiler for JVM                   Compile Source Code
              to read and interpret, not for you to understand)        e.g., javac Welcome.java
         …
         Method Welcome()                                                              If compilation errors
           0 aload_0                                              Stored on the disk
           …

         Method void main(java.lang.String[])                                   Bytecode
           0 getstatic #2 …
           3 ldc #3 <String "Welcome to Java!">
           5 invokevirtual #4 …
           8 return
                                                                               Run Bytecode
                                                                           e.g., java Welcome


                “Welcome to Java” is printed on the console
         Welcome to Java!                                                         Result


                                                                                       If runtime errors or incorrect result

FIGURE 1.9 The Java program-development process consists of repeatedly creating/modifying source code, compiling,
and executing programs.
14 Chapter 1 Introduction to Computers, Programs, and Java
editor                                  You can use any text editor or IDE to create and edit a Java source-code file. This section
                                    demonstrates how to create, compile, and run Java programs from a command window. If you
                                    wish to use an IDE such as Eclipse, NetBeans, or TextPad, please refer to Supplement II for
                                    tutorials. From the command window, you can use the NotePad to create the Java source code
                                    file, as shown in Figure 1.10.

Video Note
Brief Eclipse Tutorial




                                    FIGURE 1.10     You can create the Java source file using Windows NotePad.

                                          Note
file name                                 The source file must end with the extension .java and must have exactly the same name as the
                                          public class name. For example, the file for the source code in Listing 1.1 should be named
                                          Welcome.java, since the public class name is Welcome.

                                    A Java compiler translates a Java source file into a Java bytecode file. The following com-
                                    mand compiles Welcome.java:
compile                                javac Welcome.java


                                          Note
Supplement I.B                            You must first install and configure JDK before compiling and running programs. See Supplement
                                          I.B, “Installing and Configuring JDK 6,” on how to install JDK and set up the environment to
                                          compile and run Java programs. If you have trouble compiling and running programs, please see
Supplement I.C                            Supplement I.C, “Compiling and Running Java from the Command Window.” This supplement
                                          also explains how to use basic DOS commands and how to use Windows NotePad and WordPad
                                          to create and edit files. All the supplements are accessible from the Companion Website.

                                        If there are no syntax errors, the compiler generates a bytecode file with a .class extension. So
.class bytecode file                the preceding command generates a file named Welcome. class, as shown in Figure 1.11(a). The
                                    Java language is a high-level language while Java bytecode is a low-level language. The bytecode
                                    is similar to machine instructions but is architecture neutral and can run on any platform that has
                                    a Java Virtual Machine (JVM), as shown in Figure 1.11(b). Rather than a physical machine, the
                                    virtual machine is a program that interprets Java bytecode. This is one of Java’s primary advan-
                                    tages: Java bytecode can run on a variety of hardware platforms and operating systems.


                                                                                                                      Bytecode
                                                                                                                 Java

                                                                                                                      irtual Mach
                                                                                                                    aV
                                                                                                              Jav




                                                                                                                                in




    Welcome.java                                              Welcome.class
                                                                                                                                  e




    (Java source                      Java                    (Java bytecode                                           Any
                                                                                            JVM
      code file)                    Compiler                  executable file)                                       Computer
                         compiled                 generates                      executed
                            by                                                      by




                                           (a)                                                                           (b)

FIGURE 1.11 (a) Java source code is translated into bytecode. (b) Java bytecode can be executed on any computer with a
Java Virtual Machine.
                                                            1.8 Creating, Compiling, and Executing a Java Program 15
    To execute a Java program is to run the program’s bytecode. You can execute the bytecode
on any platform with a JVM. Java bytecode is interpreted. Interpreting translates the individ-                  interpreting bytecode
ual steps in the bytecode into the target machine-language code one at a time rather than trans-
lating the whole program as a single unit. Each step is executed immediately after it is
translated.
    The following command runs the bytecode:

   java Welcome                                                                                                 run

   Figure 1.12 shows the javac command for compiling Welcome.java. The compiler gener-
ated the Welcome.class file. This file is executed using the java command.


                                                                                                                Video Note
                                                                                                                Compile and run a Java program
          Compile

          Show files




          Run




FIGURE 1.12     The output of Listing 1.1 displays the message “Welcome to Java!”



     Note
      For simplicity and consistency, all source code and class files are placed under c:\book unless           c:\book
      specified otherwise.


     Caution
      Do not use the extension .class in the command line when executing the program. Use java                  java ClassName
      ClassName to run the program. If you use java ClassName.class in the command line, the
      system will attempt to fetch ClassName.class.class.


     Tip
      If you execute a class file that does not exist, a NoClassDefFoundError will occur. If you exe-           NoClassDefFoundError
      cute a class file that does not have a main method or you mistype the main method (e.g., by
      typing Main instead of main), a NoSuchMethodError will occur.                                             NoSuchMethodError



     Note
      When executing a Java program, the JVM first loads the bytecode of the class to memory using a
      program called the class loader. If your program uses other classes, the class loader dynamically         class loader
      loads them just before they are needed. After a class is loaded, the JVM uses a program called
      bytecode verifier to check the validity of the bytecode and ensure that the bytecode does not vio-        bytecode verifier
      late Java’s security restrictions. Java enforces strict security to make sure that Java programs arriv-
      ing from the network do not harm your computer.
16 Chapter 1 Introduction to Computers, Programs, and Java

                           Pedagogical Note
                           Instructors may require students to use packages for organizing programs. For example, you may
                           place all programs in this chapter in a package named chapter1. For instructions on how to use
using package              packages, please see Supplement I.F, “Using Packages to Organize the Classes in the Text.”


                     1.9 (GUI) Displaying Text in a Message Dialog Box
                     The program in Listing 1.1 displays the text on the console, as shown in Figure 1.12. You can
                     rewrite the program to display the text in a message dialog box. To do so, you need to use the
JOptionPane          showMessageDialog method in the JOptionPane class. JOptionPane is one of the many
                     predefined classes in the Java system that you can reuse rather than “reinventing the wheel.”
showMessageDialog    You can use the showMessageDialog method to display any text in a message dialog box,
                     as shown in Figure 1.13. The new program is given in Listing 1.4.

                                                           Title


                                    Title bar

                                                                                        Message

                                                                                        Click the OK button to
                                                                                        dismiss the dialog box

                     FIGURE 1.13    “Welcome to Java!” is displayed in a message box.

                     LISTING 1.4 WelcomeInMessageDialogBox.java
block comment         1   /* This application program displays Welcome to Java!
                      2    * in a message dialog box.
                      3    */
import                4   import javax.swing.JOptionPane;
                      5
                      6   public class WelcomeInMessageDialogBox {
main method           7     public static void main(String[] args) {
                      8       // Display Welcome to Java! in a message dialog box
display message       9       JOptionPane.showMessageDialog(null, "Welcome to Java!");
                     10     }
                     11   }

                     This program uses a Java class JOptionPane (line 9). Java’s predefined classes are grouped
package              into packages. JOptionPane is in the javax.swing package. JOptionPane is imported to
                     the program using the import statement in line 4 so that the compiler can locate the class
                     without the full name javax.swing.JOptionPane.

                           Note
                           If you replace JOptionPane on line 9 with javax.swing.JOptionPane, you don’t need to
                           import it in line 4. javax.swing.JOptionPane is the full name for the JOptionPane class.

                        The showMessageDialog method is a static method. Such a method should be invoked
                     by using the class name followed by a dot operator (.) and the method name with arguments.
                     Methods will be introduced in Chapter 5, “Methods.” The showMessageDialog method can
                     be invoked with two arguments, as shown below.


                                                                       JOptionPane.showMessageDialog(null,
                                                                         "Welcome to Java!");
                                                                                                                 Key Terms 17
   The first argument can always be null. null is a Java keyword that will be fully intro-
duced in Chapter 8, “Objects and Classes.” The second argument is a string for text to be
displayed.
   There are several ways to use the showMessageDialog method. For the time being, you                   two versions of
need to know only two ways. One is to use a statement, as shown in the example:                            showMessageDialog

   JOptionPane.showMessageDialog(null, x);

where x is a string for the text to be displayed.
  The other is to use a statement like this one:
   JOptionPane.showMessageDialog(null, x,
     y, JOptionPane.INFORMATION_MESSAGE);

where x is a string for the text to be displayed, and y is a string for the title of the message
box. The fourth argument can be JOptionPane.INFORMATION_MESSAGE, which causes the
icon (    ) to be displayed in the message box, as shown in the following example.


                                              JOptionPane.showMessageDialog(null,
                                                "Welcome to Java!",
                                                "Display Message",
                                                JOptionPane.INFORMATION_MESSAGE);



      Note
      There are two types of import statements: specific import and wildcard import. The specific        specific import
      import specifies a single class in the import statement. For example, the following statement
      imports JOptionPane from package javax.swing.

         import javax.swing.JOptionPane;

      The wildcard import imports all the classes in a package. For example, the following statement     wildcard import
      imports all classes from package javax.swing.

         import javax.swing.*;

      The information for the classes in an imported package is not read in at compile time or runtime
      unless the class is used in the program. The import statement simply tells the compiler where to
      locate the classes. There is no performance difference between a specific import and a wildcard    no performance difference
      import declaration.


      Note
      Recall that you have used the System class in the statement System.out.println(”Welcome
      to Java”); in Listing 1.1. The System class is not imported because it is in the java.lang         java.lang
      package. All the classes in the java.lang package are implicitly imported in every Java program.   implicitly imported


   KEY TERMS
   .class file 14                                          byte 3
   .java file 14                                           bytecode 14
   assembly language 5                                     bytecode verifier 15
   bit 3                                                   cable modem 5
   block 12                                                central processing unit (CPU)         2
   block comment 11                                        class loader 15
   bus 2                                                   comment 11
18 Chapter 1 Introduction to Computers, Programs, and Java
                       compiler 7                                             memory 3
                       console 11                                             modem 5
                       dot pitch 5                                            network interface card (NIC)         5
                       DSL (digital subscriber line) 5                        operating system (OS) 7
                       hardware 2                                             pixel 5
                       high-level language 6                                  program 5
                       Integrated Development Environment                     programming 5
                          (IDE) 10                                            resolution 5
                       java command 15                                        software 5
                       javac command 15                                       source code 7
                       Java Development Toolkit (JDK) 10                      source file 14
                       Java Virtual Machine (JVM) 14                          specific import 17
                       keyword (or reserved word) 11                          storage devices 4
                       line comment 11                                        statement 11
                       machine language 5                                     wildcard import 17
                       main method 11


                            Note
Supplement I.A              The above terms are defined in the present chapter. Supplement I.A, “Glossary,” lists all the
                            key terms and descriptions in the book, organized by chapters.


                       CHAPTER SUMMARY
                        1. A computer is an electronic device that stores and processes data.
                        2. A computer includes both hardware and software.
                        3. Hardware is the physical aspect of the computer that can be seen.
                        4. Computer programs, known as software, are the invisible instructions that control the
                            hardware and make it perform tasks.

                        5. Computer programming is the writing of instructions (i.e., code) for computers to
                            perform.

                        6. The central processing unit (CPU) is a computer’s brain. It retrieves instructions from
                            memory and executes them.

                        7. Computers use zeros and ones because digital devices have two stable states, referred
                            to by convention as zero and one.

                        8. A bit is a binary digit 0 or 1.
                        9. A byte is a sequence of 8 bits.
                       10. A kilobyte is about 1000 bytes, a megabyte about 1 million bytes, a gigabyte about 1
                            billion bytes, and a terabyte about 1000 gigabytes.

                       11. Memory stores data and program instructions for the CPU to execute.
                       12. A memory unit is an ordered sequence of bytes.
                       13. Memory is volatile, because information is lost when the power is turned off.
                                                                                             Chapter Summary 19

14. Programs and data are permanently stored on storage devices and are moved to mem-
     ory when the computer actually uses them.

15. The machine language is a set of primitive instructions built into every computer.
16. Assembly language is a low-level programming language in which a mnemonic is
     used to represent each machine-language instruction.

17. High-level languages are English-like and easy to learn and program.
18. A program written in a high-level language is called a source program.
19. A compiler is a software program that translates the source program into a machine-
     language program.

20. The operating system (OS) is a program that manages and controls a computer’s
     activities.

21. Java is platform independent, meaning that you can write a program once and run it
     anywhere.

22. Java programs can be embedded in HTML pages and downloaded by Web browsers
     to bring live animation and interaction to Web clients.

23. Java source files end with the .java extension.
24. Every class is compiled into a separate bytecode file that has the same name as the
     class and ends with the .class extension.

25. To compile a Java source-code file from the command line, use the javac command.
26. To run a Java class from the command line, use the java command.
27. Every Java program is a set of class definitions. The keyword class introduces a
     class definition. The contents of the class are included in a block.

28. A block begins with an opening brace ({) and ends with a closing brace (}). Methods
     are contained in a class.

29. A Java program must have a main method. The main method is the entry point where
     the program starts when it is executed.

30. Every statement in Java ends with a semicolon (;), known as the statement terminator.
31. Reserved words, or keywords, have a specific meaning to the compiler and cannot be
     used for other purposes in the program.

32. In Java, comments are preceded by two slashes (//) on a line, called a line comment,
     or enclosed between /* and */ on one or several lines, called a block comment.

33. Java source programs are case sensitive.
34. There are two types of import statements: specific import and wildcard import. The
     specific import specifies a single class in the import statement. The wildcard import
     imports all the classes in a package.
20 Chapter 1 Introduction to Computers, Programs, and Java

                       REVIEW QUESTIONS
                              Note
                              Answers to review questions are on the Companion Website.

                       Sections 1.2–1.4
                       1.1      Define hardware and software.
                       1.2      List the main components of the computer.
                       1.3      Define machine language, assembly language, and high-level programming
                                language.
                       1.4      What is a source program? What is a compiler?
                       1.5      What is the JVM?
                       1.6      What is an operating system?

                       Sections 1.5–1.6
                       1.7      Describe the history of Java. Can Java run on any machine? What is needed to run
                                Java on a computer?
                       1.8      What are the input and output of a Java compiler?
                       1.9      List some Java development tools. Are tools like NetBeans and Eclipse different
                                languages from Java, or are they dialects or extensions of Java?
                       1.10     What is the relationship between Java and HTML?

                       Sections 1.7–1.9
                       1.11     Explain the Java keywords. List some Java keywords you learned in this chapter.
                       1.12     Is Java case sensitive? What is the case for Java keywords?
                       1.13     What is the Java source filename extension, and what is the Java bytecode file-
                                name extension?
                       1.14     What is a comment? Is the comment ignored by the compiler? How do you denote
                                a comment line and a comment paragraph?
                       1.15     What is the statement to display a string on the console? What is the statement to
                                display the message “Hello world” in a message dialog box?
                       1.16     The following program is wrong. Reorder the lines so that the program displays
                                morning followed by afternoon.
                                   public static void main(String[] args) {
                                   }

                                public class Welcome {
                                    System.out.println("afternoon");
                                    System.out.println("morning");
                                }

                       1.17     Identify and fix the errors in the following code:
                                1 public class Welcome {
                                2   public void Main(String[] args) {
                                3     System.out.println('Welcome to Java!);
                                4   }
                                5 )
                                                                                                        Programming Exercises 21

1.18     What is the command to compile a Java program? What is the command to run a
         Java program?
1.19     If a NoClassDefFoundError occurs when you run a program, what is the cause
         of the error?
1.20 If a NoSuchMethodError occurs when you run a program, what is the cause of
         the error?
1.21 Why does the System class not need to be imported?
1.22 Are there any performance differences between the following two                              import
         statements?
         import javax.swing.JOptionPane;

         import javax.swing.*;

1.23 Show the output of the following code:
         public class Test {
           public static void main(String[] args) {
             System.out.println("3.5 * 4 / 2 – 2.5 is ");
             System.out.println(3.5 * 4 / 2 – 2.5);
           }
         }



PROGRAMMING EXERCISES
       Note
       Solutions to even-numbered exercises are on the Companion Website. Solutions to all exer-
       cises are on the Instructor Resource Website. The level of difficulty is rated easy (no star),        level of difficulty
       moderate (*), hard (**), or challenging (***).

1.1      (Displaying three messages) Write a program that displays Welcome to Java,
         Welcome to Computer Science, and Programming is fun.
1.2      (Displaying five messages) Write a program that displays Welcome to Java five
         times.
1.3*     (Displaying a pattern) Write a program that displays the following pattern:
             J         A          V     V    A
             J        A A          V   V    A A
         J   J       AAAAA          V V    AAAAA
          J J       A     A          V    A     A
1.4      (Printing a table) Write a program that displays the following table:
         a          a^2        a^3
         1          1          1
         2          4          8
         3          9          27
         4          16         64
1.5      (Computing expressions) Write a program that displays the result of
         9.5 * 4.5 - 2.5 * 3
                             .
              45.5 - 3.5
22 Chapter 1 Introduction to Computers, Programs, and Java

                       1.6   (Summation of a series) Write a program that displays the result of
                             1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9.
                       1.7   (Approximating p) p can be computed using the following formula:

                                                        1  1 1 1   1    1
                                         p = 4 * a1 -     + - + -    +    + Áb
                                                        3  5 7 9  11   13

                                                                                   1 1 1
                             Write a program that displays the result of 4 * a1 - + - +
                                                                                   3 5 7
                             1     1    1
                               -     +    b. Use 1.0 instead of 1 in your program.
                             9    11   13
                                                             CHAPTER 2
ELEMENTARY PROGRAMMING
Objectives
■   To write Java programs to perform simple calculations (§2.2).
■   To obtain input from the console using the Scanner
    class (§2.3).
■   To use identifiers to name variables, constants, methods,
    and classes (§2.4).
■   To use variables to store data (§§2.5–2.6).
■   To program with assignment statements and assignment
    expressions (§2.6).
■   To use constants to store permanent data (§2.7).
■   To declare Java primitive data types: byte, short,
    int, long, float, double, and char (§2.8.1).

■   To use Java operators to write numeric
    expressions (§§2.8.2–2.8.3).
■   To display the current time (§2.9).
■   To use shorthand operators (§2.10).
■   To cast the value of one type to another type (§2.11).
■   To compute loan payments (§2.12).
■   To represent characters using the char type (§2.13).
■   To compute monetary changes (§2.14).
■   To represent a string using the String type (§2.15).
■   To become familiar with Java documentation,
    programming style, and naming conventions (§2.16).
■   To distinguish syntax errors, runtime errors, and logic
    errors and debug errors (§2.17).
■   (GUI) To obtain input using the JOptionPane input
    dialog boxes (§2.18).
24 Chapter 2 Elementary Programming

                   2.1 Introduction
                   In Chapter 1 you learned how to create, compile, and run a Java program. Now you will learn
                   how to solve practical problems programmatically. Through these problems, you will learn ele-
                   mentary programming using primitive data types, variables, constants, operators, expressions,
                   and input and output.


                   2.2 Writing Simple Programs
problem            To begin, let’s look at a simple problem for computing the area of a circle. How do we write a
                   program for solving this problem?
                       Writing a program involves designing algorithms and translating algorithms into code. An
algorithm          algorithm describes how a problem is solved in terms of the actions to be executed and the
                   order of their execution. Algorithms can help the programmer plan a program before writing
                   it in a programming language. Algorithms can be described in natural languages or in
pseudocode         pseudocode (i.e., natural language mixed with programming code). The algorithm for this
                   program can be described as follows:
                      1. Read in the radius.
                      2. Compute the area using the following formula:
                                                        area = radius * radius * p
                      3. Display the area.
                   Many of the problems you will encounter when taking an introductory course in program-
                   ming can be described with simple, straightforward algorithms.
                      When you code, you translate an algorithm into a program. You already know that every
                   Java program begins with a class declaration in which the keyword class is followed by the
                   class name. Assume that you have chosen ComputeArea as the class name. The outline of the
                   program would look like this:
                      public class ComputeArea {
                        // Details to be given later
                      }

                   As you know, every Java program must have a main method where program execution
                   begins. So the program is expanded as follows:
                      public class ComputeArea {
                        public static void main(String[] args) {
                          // Step 1: Read in radius

                              // Step 2: Compute area

                              // Step 3: Display the area
                          }
                      }

                   The program needs to read the radius entered by the user from the keyboard. This raises two
                   important issues:
                          ■   Reading the radius.
                          ■   Storing the radius in the program.
                   Let’s address the second issue first. In order to store the radius, the program needs to declare a sym-
variable           bol called a variable. A variable designates a location in memory for storing data and computa-
                   tional results in the program. A variable has a name that can be used to access the memory location.
                                                                                2.2 Writing Simple Programs 25
  Rather than using x and y as variable names, choose descriptive names: in this case,           descriptive names
radius for radius, and area for area. To let the compiler know what radius and area are,
specify their data types. Java provides simple data types for representing integers, floating-   floating-point number
point numbers (i.e., numbers with a decimal point), characters, and Boolean types. These
types are known as primitive data types or fundamental types.                                    primitive data types
   Declare radius and area as double-precision floating-point numbers. The program can
be expanded as follows:
   public class ComputeArea {
     public static void main(String[] args) {
       double radius;
       double area;

           // Step 1: Read in radius

           // Step 2: Compute area

           // Step 3: Display the area
       }
   }

The program declares radius and area as variables. The reserved word double indicates
that radius and area are double-precision floating-point values stored in the computer.
   The first step is to read in radius. Reading a number from the keyboard is not a simple
matter. For the time being, let us assign a fixed value to radius in the program.
   The second step is to compute area by assigning the result of the expression radius *
radius * 3.14159 to area.
   In the final step, display area on the console by using the System.out.println
method.
   The complete program is shown in Listing 2.1. A sample run of the program is shown in
Figure 2.1.




            Compile
            Run




FIGURE 2.1 The program displays the area of a circle.


LISTING 2.1 ComputeArea.java
 1 public class ComputeArea {
 2   public static void main(String[] args) {
 3     double radius; // Declare radius
 4     double area; // Declare area
 5
 6     // Assign a radius
 7     radius = 20; // New value is radius
 8
 9     // Compute area
10     area = radius * radius * 3.14159;
11
12     // Display results
26 Chapter 2 Elementary Programming
                              13     System.out.println("The area for the circle of radius " +
                              14       radius + " is " + area);
                              15   }
                              16 }

declaring variable            Variables such as radius and area correspond to memory locations. Every variable has a
                              name, a type, a size, and a value. Line 3 declares that radius can store a double value. The
assign value                  value is not defined until you assign a value. Line 7 assigns 20 into radius. Similarly, line 4
                              declares variable area, and line 10 assigns a value into area. The following table shows the
                              value in the memory for area and radius as the program is executed. Each row in the table
                              shows the values of variables after the statement in the corresponding line in the program is
                              executed. Hand trace is helpful to understand how a program works, and it is also a useful tool
                              for finding errors in the program.


                               line#                 radius                               area
                                3                    no value
                                4                                                         no value
                                7                    20
                               10                                                         1256.636

concatenating strings             The plus sign (+) has two meanings: one for addition and the other for concatenating
                              strings. The plus sign (+) in lines 13–14 is called a string concatenation operator. It combines
                              two strings if two operands are strings. If one of the operands is a nonstring (e.g., a number),
concatenating strings with    the nonstring value is converted into a string and concatenated with the other string. So the
  numbers                     plus signs (+) in lines 13–14 concatenate strings into a longer string, which is then displayed
                              in the output. Strings and string concatenation will be discussed further in §2.15, “The
                              String Type.”


                                    Caution
breaking a long string              A string constant cannot cross lines in the source code. Thus the following statement would
                                    result in a compile error:

                                    System.out.println("Introduction to Java Programming,
                                      by Y. Daniel Liang");

                                    To fix the error, break the string into separate substrings, and use the concatenation operator (+)
                                    to combine them:

                                    System.out.println("Introduction to Java Programming, " +
                                      "by Y. Daniel Liang");


                                    Tip
incremental development and         This example consists of three steps. It is a good approach to develop and test these steps
   testing                          incrementally by adding them one at a time.



                              2.3 Reading Input from the Console
                              In Listing 2.1, the radius is fixed in the source code. To use a different radius, you have to
                              modify the source code and recompile it. Obviously, this is not convenient. You can use the
Video Note
                              Scanner class for console input.
Obtain input
                                 Java uses System.out to refer to the standard output device and System.in to the stan-
                              dard input device. By default the output device is the display monitor, and the input device is
                                                                              2.3 Reading Input from the Console 27
the keyboard. To perform console output, you simply use the println method to display a
primitive value or a string to the console. Console input is not directly supported in Java, but
you can use the Scanner class to create an object to read input from System.in, as follows:
   Scanner input = new Scanner(System.in);

The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax
Scanner input declares that input is a variable whose type is Scanner. The whole line
Scanner input = new Scanner(System.in) creates a Scanner object and assigns its ref-
erence to the variable input. An object may invoke its methods. To invoke a method on an
object is to ask the object to perform a task. You can invoke the methods in Table 2.1 to read
various types of input.

TABLE 2.1 Methods for Scanner Objects
Method                          Description

nextByte()                      reads an integer of the byte type.
nextShort()                     reads an integer of the short type.
nextInt()                       reads an integer of the int type.
nextLong()                      reads an integer of the long type.
nextFloat()                     reads a number of the float type.
nextDouble()                    reads a number of the double type.
next()                          reads a string that ends before a whitespace character.
nextLine()                      reads a line of text (i.e., a string ending with the Enter key pressed).

   For now, we will see how to read a number that includes a decimal point by invoking the
nextDouble() method. Other methods will be covered when they are used. Listing 2.2
rewrites Listing 2.1 to prompt the user to enter a radius.

LISTING 2.2 ComputeAreaWithConsoleInput.java
 1 import java.util.Scanner; // Scanner is in the java.util package                                        import class
 2
 3 public class ComputeAreaWithConsoleInput {
 4   public static void main(String[] args) {
 5     // Create a Scanner object
 6     Scanner input = new Scanner(System.in);                                                             create a Scanner
 7
 8     // Prompt the user to enter a radius
 9     System.out.print("Enter a number for radius: ");
10     double radius = input.nextDouble() ;                                                                read a double
11
12     // Compute area
13     double area = radius * radius * 3.14159;
14
15     // Display result
16     System.out.println("The area for the circle of radius " +
17       radius + " is " + area);
18   }
19 }


 Enter a number for radius: 2.5
 The area for the circle of radius 2.5 is 19.6349375
28 Chapter 2 Elementary Programming

                     Enter a number for radius: 23
                     The area for the circle of radius 23.0 is 1661.90111


                    The Scanner class is in the java.util package. It is imported in line 1. Line 6 creates a
                    Scanner object.
                      The statement in line 9 displays a message to prompt the user for input.
                       System.out.print ("Enter a number for radius: ");

print vs. println   The print method is identical to the println method except that println moves the cur-
                    sor to the next line after displaying the string, but print does not advance the cursor to the
                    next line when completed.
                       The statement in line 10 reads an input from the keyboard.
                       double radius = input.nextDouble();

                    After the user enters a number and presses the Enter key, the number is read and assigned to
                    radius.
                       More details on objects will be introduced in Chapter 8, “Objects and Classes.” For the
                    time being, simply accept that this is how to obtain input from the console.
                       Listing 2.3 gives another example of reading input from the keyboard. The example reads
                    three numbers and displays their average.

                    LISTING 2.3 ComputeAverage.java
import class         1 import java.util.Scanner; // Scanner is in the java.util package
                     2
                     3 public class ComputeAverage {
                     4   public static void main(String[] args) {
                     5     // Create a Scanner object
create a Scanner     6     Scanner input = new Scanner(System.in);
                     7
                     8     // Prompt the user to enter three numbers
                     9     System.out.print("Enter three numbers: ");
read a double       10     double number1 = input.nextDouble() ;
                    11     double number2 = input.nextDouble() ;
                    12     double number3 = input.nextDouble() ;
                    13
                    14     // Compute average
                    15     double average = (number1 + number2 + number3) / 3;
                    16
                    17     // Display result
                    18     System.out.println("The average of " + number1 + " " + number2
                    19       + " " + number3 + " is " + average);
                    20   }
                    21 }


enter input in       Enter three numbers: 1 2 3
  one line           The average of 1.0 2.0 3.0 is 2.0



enter input in       Enter three numbers: 10.5
  multiple lines     11
                     11.5
                     The average of 10.5 11.0 11.5 is 11.0
                                                                                                             2.5 Variables          29
The code for importing the Scanner class (line 1) and creating a Scanner object (line 6) are
the same as in the preceding example as well as in all new programs you will write.
   Line 9 prompts the user to enter three numbers. The numbers are read in lines 10–12. You
may enter three numbers separated by spaces, then press the Enter key, or enter each number
followed by a press of the Enter key, as shown in the sample runs of this program.


2.4 Identifiers
As you see in Listing 2.3, ComputeAverage, main, input, number1, number2, number3,
and so on are the names of things that appear in the program. Such names are called
identifiers. All identifiers must obey the following rules:
     ■   An identifier is a sequence of characters that consists of letters, digits, underscores          identifier naming rules
         (_), and dollar signs ($).
     ■   An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot
         start with a digit.
     ■   An identifier cannot be a reserved word. (See Appendix A, “Java Keywords,” for a
         list of reserved words.)
     ■   An identifier cannot be true, false, or null.
     ■   An identifier can be of any length.
For example, $2, ComputeArea, area, radius, and showMessageDialog are legal identi-
fiers, whereas 2A and d+4 are not because they do not follow the rules. The Java compiler
detects illegal identifiers and reports syntax errors.

     Note
     Since Java is case sensitive, area, Area, and AREA are all different identifiers.                    case sensitive


     Tip
     Identifiers are for naming variables, constants, methods, classes, and packages. Descriptive iden-   descriptive names
     tifiers make programs easy to read.


     Tip
     Do not name identifiers with the $ character. By convention, the $ character should be used only     the $ character
     in mechanically generated source code.


2.5 Variables
As you see from the programs in the preceding sections, variables are used to store values to             why called variables?
be used later in a program. They are called variables because their values can be changed. In
the program in Listing 2.2, radius and area are variables of double-precision, floating-
point type. You can assign any numerical value to radius and area, and the values of
radius and area can be reassigned. For example, you can write the code shown below to
compute the area for different radii:
  // Compute the first area
  radius = 1.0;
  area = radius * radius * 3.14159;
  System.out.println("The area is " + area + " for radius " + radius);
   // Compute the second area
   radius = 2.0;
   area = radius * radius * 3.14159;
   System.out.println("The area is " + area + " for radius " + radius);
30 Chapter 2 Elementary Programming
                         Variables are for representing data of a certain type. To use a variable, you declare it by telling
                         the compiler its name as well as what type of data it can store. The variable declaration tells
                         the compiler to allocate appropriate memory space for the variable based on its data type. The
                         syntax for declaring a variable is
                            datatype variableName;

declaring variables         Here are some examples of variable declarations:
                            int count;           // Declare count to be an integer variable;
                            double radius;       // Declare radius to be a double variable;
                            double interestRate; // Declare interestRate to be a double variable;

                         The examples use the data types int, double, and char. Later you will be introduced to
                         additional data types, such as byte, short, long, float, char, and boolean.
                            If variables are of the same type, they can be declared together, as follows:
                            datatype variable1, variable2, ..., variablen;

                         The variables are separated by commas. For example,
                            int i, j, k; // Declare i, j, and k as int variables


                               Note
naming variables               By convention, variable names are in lowercase. If a name consists of several words, concatenate
                               all of them and capitalize the first letter of each word except the first. Examples of variables are
                               radius and interestRate.

initializing variables   Variables often have initial values. You can declare a variable and initialize it in one step.
                         Consider, for instance, the following code:
                            int count = 1;

                         This is equivalent to the next two statements:
                            int count;
                            x = 1;

                         You can also use a shorthand form to declare and initialize variables of the same type together.
                         For example,
                            int i = 1, j = 2;


                               Tip
                               A variable must be declared before it can be assigned a value. A variable declared in a method
                               must be assigned a value before it can be used.
                               Whenever possible, declare a variable and assign its initial value in one step. This will make the
                               program easy to read and avoid programming errors.


                         2.6 Assignment Statements and Assignment
                             Expressions
assignment statement     After a variable is declared, you can assign a value to it by using an assignment statement. In
assignment operator      Java, the equal sign (=) is used as the assignment operator. The syntax for assignment state-
                         ments is as follows:

                            variable = expression;
                                                                                                          2.7 Named Constants 31
   An expression represents a computation involving values, variables, and operators that,                     expression
taking them together, evaluates to a value. For example, consider the following code:

   int x = 1;                // Assign 1 to variable x
   double radius = 1.0;      // Assign 1.0 to variable radius
   x = 5 * (3 / 2) + 3 * 2; // Assign the value of the expression to x
   x = y + 1;                // Assign the addition of y and 1 to x
   area = radius * radius * 3.14159; // Compute area

A variable can also be used in an expression. For example,

   x = x + 1;

In this assignment statement, the result of x + 1 is assigned to x. If x is 1 before the state-
ment is executed, then it becomes 2 after the statement is executed.
   To assign a value to a variable, the variable name must be on the left of the assignment
operator. Thus, 1 = x would be wrong.

     Note
      In mathematics, x = 2 * x + 1 denotes an equation. However, in Java, x = 2 * x + 1 is
      an assignment statement that evaluates the expression 2 * x + 1 and assigns the result to x.

In Java, an assignment statement is essentially an expression that evaluates to the value to be
assigned to the variable on the left-hand side of the assignment operator. For this reason, an
assignment statement is also known as an assignment expression. For example, the following                     assignment expression
statement is correct:
   System.out.println(x = 1);

which is equivalent to
   x = 1;
   System.out.println(x);

The following statement is also correct:
   i = j = k = 1;

which is equivalent to

   k = 1;
   j = k;
   i = j;


     Note
      In an assignment statement, the data type of the variable on the left must be compatible with the
      data type of the value on the right. For example, int x = 1.0 would be illegal, because the
      data type of x is int. You cannot assign a double value (1.0) to an int variable without using
      type casting. Type casting is introduced in §2.11 “Numeric Type Conversions.”


2.7 Named Constants
The value of a variable may change during the execution of a program, but a named constant
or simply constant represents permanent data that never changes. In our ComputeArea pro-                       constant
gram, p is a constant. If you use it frequently, you don’t want to keep typing 3.14159;
instead, you can declare a constant for p. Here is the syntax for declaring a constant:
   final datatype CONSTANTNAME = VALUE;
32 Chapter 2 Elementary Programming
                           A constant must be declared and initialized in the same statement. The word final is a
                        Java keyword for declaring a constant. For example, you can declare p as a constant and
                        rewrite Listing 2.1 as follows:

                           // ComputeArea.java: Compute the area of a circle
                           public class ComputeArea {
                             public static void main(String[] args) {
                               final double PI = 3.14159; // Declare a constant
                                   // Assign a radius
                                   double radius = 20;
                                   // Compute area
                                   double area = radius * radius * PI ;
                                   // Display results
                                   System.out.println("The area for the circle of radius " +
                                     radius + " is " + area);
                               }
                           }


                               Caution
naming constants                By convention, constants are named in uppercase: PI, not pi or Pi.


                               Note
benefits of constants           There are three benefits of using constants: (1) you don’t have to repeatedly type the same value;
                                (2) if you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you need to
                                change it only in a single location in the source code; (3) a descriptive name for a constant makes
                                the program easy to read.


                        2.8 Numeric Data Types and Operations
                        Every data type has a range of values. The compiler allocates memory space for each variable
                        or constant according to its data type. Java provides eight primitive data types for numeric val-
                        ues, characters, and Boolean values. This section introduces numeric data types.
                           Table 2.2 lists the six numeric data types, their ranges, and their storage sizes.


                        TABLE 2.2       Numeric Data Types
                        Name                                           Range                                        Storage Size

                        byte             -27 1-1282 to 27 – 1 (127)                                                 8-bit signed

                        short            -215 1-327682 to 215 – 1 (32767)                                           16-bit signed

                        int              -231 1-21474836482 to 231 – 1 (2147483647)                                 32-bit signed

                        long             -263 to 263 – 1                                                            64-bit signed

                                        (i.e., -9223372036854775808
                                        to 9223372036854775807)
                        float           Negative range: -3.4028235E + 38 to -1.4E – 45                              32-bit IEEE 754
                                        Positive range: 1.4E–45 to 3.4028235E + 38

                        double          Negative range: -1.7976931348623157E + 308 to -4.9E–324                     64-bit IEEE 754
                                        Positive range: 4.9E - 324 to 1.7976931348623157E + 308
                                                                                  2.8 Numeric Data Types and Operations                   33

     Note
      IEEE 754 is a standard approved by the Institute of Electrical and Electronics Engineers for represent-
      ing floating-point numbers on computers. The standard has been widely adopted. Java has adopted
      the 32-bit IEEE 754 for the float type and the 64-bit IEEE 754 for the double type. The IEEE
      754 standard also defines special values as given in Appendix E, “Special Floating-Point Values.”

Java uses four types for integers: byte, short, int, and long. Choose the type that is most                     integer types
appropriate for your variable. For example, if you know an integer stored in a variable is
within a range of byte, declare the variable as a byte. For simplicity and consistency, we will
use int for integers most of the time in this book.
   Java uses two types for floating-point numbers: float and double. The double type is                         floating point
twice as big as float. So, the double is known as double precision, float as single precision.
Normally you should use the double type, because it is more accurate than the float type.

     Caution
      When a variable is assigned a value that is too large (in size) to be stored, it causes overflow. For     what is overflow?
      example, executing the following statement causes overflow, because the largest value that can
      be stored in a variable of the int type is 2147483647. 2147483648 is too large.

      int value = 2147483647 + 1; // value will actually be -2147483648

      Likewise, executing the following statement causes overflow, because the smallest value that can
      be stored in a variable of the int type is -2147483648. -2147483649 is too large in size to
      be stored in an int variable.

      int value = -2147483648 - 1; // value will actually be 2147483647

      Java does not report warnings or errors on overflow. So be careful when working with numbers
      close to the maximum or minimum range of a given type.
      When a floating-point number is too small (i.e., too close to zero) to be stored, it causes
      underflow. Java approximates it to zero. So normally you should not be concerned with underflow.          what is underflow?


2.8.1 Numeric Operators
The operators for numeric data types include the standard arithmetic operators: addition (+),                   operators +, -, *, /, %
subtraction (–), multiplication (*), division (/), and remainder (%), as shown in Table 2.3.
   When both operands of a division are integers, the result of the division is an integer. The                 integer division
fractional part is truncated. For example, 5 / 2 yields 2, not 2.5, and –5 / 2 yields -2, not
–2.5. To perform regular mathematical division, one of the operands must be a floating-point
number. For example, 5.0 / 2 yields 2.5.
   The % operator yields the remainder after division. The left-hand operand is the dividend
and the right-hand operand the divisor. Therefore, 7 % 3 yields 1, 12 % 4 yields 0, 26 % 8
yields 2, and 20 % 13 yields 7.


                            TABLE 2.3        Numeric Operators
                            Name Meaning                     Example        Result

                            +         Addition               34 + 1         35
                            -         Subtraction            34.0 – 0.1     33.9
                            *         Multiplication         300 * 30       9000
                            /         Division               1.0 / 2.0      0.5
                            %         Remainder              20 % 3         2
34 Chapter 2 Elementary Programming
                                 2            3              3                               1          Quotient

                            3   7        4 12          8 26              Divisor        13 20           Dividend
                                6            12              24                             13
                                1             0               2                              7          Remainder

                       The % operator is often used for positive integers but can be used also with negative integers
                   and floating-point values. The remainder is negative only if the dividend is negative. For example,
                   -7 % 3 yields -1, -12 % 4 yields 0, -26 % -8 yields -2, and 20 % -13 yields 7.
                       Remainder is very useful in programming. For example, an even number % 2 is always 0
                   and an odd number % 2 is always 1. So you can use this property to determine whether a num-
                   ber is even or odd. If today is Saturday, it will be Saturday again in 7 days. Suppose you and
                   your friends are going to meet in 10 days. What day is in 10 days? You can find that the day
                   is Tuesday using the following expression:
                                        Day 6 in a week is Saturday
                                                                        A week has 7 days

                                             (6 + 10) % 7 is 2
                                                                      Day 2 in a week is Tuesday
                                                                      Note: Day 0 in a week is Sunday
                                             After 10 days

                      Listing 2.4 gives a program that obtains minutes and remaining seconds from an amount of
                   time in seconds. For example, 500 seconds contains 8 minutes and 20 seconds.

                   LISTING 2.4 DisplayTime.java
import Scanner      1 import java.util.Scanner;
create a Scanner    2
                    3 public class DisplayTime {
                    4   public static void main(String[] args) {
                    5     Scanner input = new Scanner(System.in);
                    6     // Prompt the user for input
                    7     System.out.print("Enter an integer for seconds: ");
read an integer     8     int seconds = input.nextInt() ;
                    9
divide             10     int minutes = seconds / 60 ; // Find minutes in seconds
remainder          11     int remainingSeconds = seconds % 60 ; // Seconds remaining
                   12     System.out.println(seconds + " seconds is " + minutes +
                   13       " minutes and " + remainingSeconds + " seconds");
                   14   }
                   15 }


                    Enter an integer for seconds: 500
                    500 seconds is 8 minutes and 20 seconds


                    line#              seconds                    minutes             remainingSeconds
                       8               500
                      10                                          8
                      11                                                              20

                      The nextInt() method (line 8) reads an integer for seconds. Line 4 obtains the minutes
                   using seconds / 60. Line 5 (seconds % 60) obtains the remaining seconds after taking
                   away the minutes.
                                                                                2.8 Numeric Data Types and Operations 35
   The + and - operators can be both unary and binary. A unary operator has only one                          unary operator
operand; a binary operator has two. For example, the - operator in -5 is a unary operator                     binary operator
to negate number 5, whereas the - operator in 4 - 5 is a binary operator for subtracting 5
from 4.

      Note
      Calculations involving floating-point numbers are approximated because these numbers are not            floating-point approximation
      stored with complete accuracy. For example,
      System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);

      displays 0.5000000000000001, not 0.5, and
      System.out.println(1.0 - 0.9);

      displays 0.09999999999999998, not 0.1. Integers are stored precisely. Therefore, calcula-
      tions with integers yield a precise integer result.

2.8.2 Numeric Literals
A literal is a constant value that appears directly in a program. For example, 34 and 0.305                   literal
are literals in the following statements:
   int numberOfYears = 34;
   double weight = 0.305;

Integer Literals
An integer literal can be assigned to an integer variable as long as it can fit into the variable.
A compile error will occur if the literal is too large for the variable to hold. The statement
byte b = 128, for example, will cause a compile error, because 128 cannot be stored in a
variable of the byte type. (Note that the range for a byte value is from -128 to 127.)
    An integer literal is assumed to be of the int type, whose value is between
-231 1-21474836482 and 231 - 1 121474836472. To denote an integer literal of the long type,                   long literal
append the letter L or l to it (e.g., 2147483648L). L is preferred because l (lowercase L) can eas-
ily be confused with 1 (the digit one). To write integer 2147483648 in a Java program, you have
to write it as 2147483648L, because 2147483648 exceeds the range for the int value.

      Note
      By default, an integer literal is a decimal integer number. To denote an octal integer literal, use a   octal and hex literals
      leading 0 (zero), and to denote a hexadecimal integer literal, use a leading 0x or 0X (zero x). For
      example, the following code displays the decimal value 65535 for hexadecimal number FFFF.

      System.out.println(0xFFFF);

      Hexadecimal numbers, binary numbers, and octal numbers are introduced in Appendix F, “Num-
      ber Systems.”


Floating-Point Literals
Floating-point literals are written with a decimal point. By default, a floating-point literal is
treated as a double type value. For example, 5.0 is considered a double value, not a float
value. You can make a number a float by appending the letter f or F, and you can make a
number a double by appending the letter d or D. For example, you can use 100.2f or                            suffix d or D
100.2F for a float number, and 100.2d or 100.2D for a double number.                                          suffix f or F


      Note
      The double type values are more accurate than the float type values. For example,                       double vs. float
36 Chapter 2 Elementary Programming
                                   System.out.println("1.0 / 3.0 is " + 1.0 / 3.0);

                                   displays 1.0 / 3.0 is 0.3333333333333333.

                                   System.out.println("1.0F / 3.0F is " + 1.0F / 3.0F);

                                   displays 1.0F / 3.0F is 0.33333334.

                             Scientific Notation
                             Floating-point literals can also be specified in scientific notation; for example, 1.23456e+2,
                             the same as 1.23456e2, is equivalent to 1.23456 * 102 = 123.456, and 1.23456e-2 is
                             equivalent to 1.23456 * 10-2 = 0.0123456. E (or e) represents an exponent and can be in
                             either lowercase or uppercase.

                                  Note
why called floating-point?         The float and double types are used to represent numbers with a decimal point. Why are
                                   they called floating-point numbers? These numbers are stored in scientific notation. When a
                                   number such as 50.534 is converted into scientific notation, such as 5.0534e+1, its decimal
                                   point is moved (i.e., floated) to a new position.


                             2.8.3     Evaluating Java Expressions
                             Writing a numeric expression in Java involves a straightforward translation of an arithmetic
                             expression using Java operators. For example, the arithmetic expression

                                                 3 + 4x   101y - 521a + b + c2     4  9 + x
                                                        -                      + 9a +       b
                                                    5               x              x    y
                             can be translated into a Java expression as:

                                (3 + 4 * x) / 5 – 10 * (y - 5) * (a + b + c) / x +
                                9 * (4 / x + (9 + x) / y)

                             Though Java has its own way to evaluate an expression behind the scene, the result of a Java
                             expression and its corresponding arithmetic expression are the same. Therefore, you can
evaluating an expression     safely apply the arithmetic rule for evaluating a Java expression. Operators contained within
                             pairs of parentheses are evaluated first. Parentheses can be nested, in which case the expres-
                             sion in the inner parentheses is evaluated first. Multiplication, division, and remainder opera-
                             tors are applied next. If an expression contains several multiplication, division, and remainder
                             operators, they are applied from left to right. Addition and subtraction operators are applied
                             last. If an expression contains several addition and subtraction operators, they are applied
                             from left to right. Here is an example of how an expression is evaluated:

                                           3 + 4 * 4 + 5 * (4 + 3) - 1
                                                                                           (1) inside parentheses first
                                           3 + 4 * 4 + 5 * 7 – 1
                                                                                           (2) multiplication
                                           3 + 16 + 5 * 7 – 1
                                                                                           (3) multiplication
                                           3 + 16 + 35 – 1
                                                                                           (4) addition
                                           19 + 35 – 1
                                                                                           (5) addition
                                                  54 – 1
                                                                                           (6) subtraction
                                                  53
                                                                     2.9 Problem: Displaying the Current Time 37
   Listing 2.5 gives a program that converts a Fahrenheit degree to Celsius using the formula
celsius = A 9 B 1fahrenheit - 322.
            5



LISTING 2.5 FahrenheitToCelsius.java
 1 import java.util.Scanner;
 2
 3 public class FahrenheitToCelsius {
 4   public static void main(String[] args) {
 5     Scanner input = new Scanner(System.in);
 6
 7     System.out.print("Enter a degree in Fahrenheit: ");
 8     double fahrenheit = input.nextDouble();
 9
10     // Convert Fahrenheit to Celsius
11     double celsius = (5.0 / 9) * (fahrenheit - 32);                                                   divide
12     System.out.println("Fahrenheit " + fahrenheit + " is " +
13       celsius + " in Celsius");
14   }
15 }


 Enter a degree in Fahrenheit: 100
 Fahrenheit 100.0 is 37.77777777777778 in Celsius


 line#                            fahrenheit                       celsius
   8                             100
  11                                                               37.77777777777778



                                                                                           5
    Be careful when applying division. Division of two integers yields an integer in Java. 9 is trans-   integer vs. decimal division
lated to 5.0 / 9 instead of 5 / 9 in line 11, because 5 / 9 yields 0 in Java.


2.9 Problem: Displaying the Current Time
                                                                                                         Video Note
The problem is to develop a program that displays the current time in GMT (Greenwich Mean                Use operators / and %
Time) in the format hour:minute:second, such as 13:19:8.
    The currentTimeMillis method in the System class returns the current time in mil-                    currentTimeMillis
liseconds elapsed since the time 00:00:00 on January 1, 1970 GMT, as shown in Figure 2.2.
This time is known as the Unix epoch, because 1970 was the year when the Unix operating                  Unix epoch
system was formally introduced.


                                           Elapsed
                                            time
                                                                                             Time
                 Unix Epoch                                       Current Time
                  01-01-1970                                System.currentTimeMillis()
                00:00:00 GMT

FIGURE 2.2 The System.currentTimeMillis() returns the number of milliseconds
since the Unix epoch.

  You can use this method to obtain the current time, and then compute the current second,
minute, and hour as follows.
38 Chapter 2 Elementary Programming
                      1. Obtain the total milliseconds since midnight, Jan 1, 1970, in totalMilliseconds by
                         invoking System.currentTimeMillis() (e.g., 1203183086328 milliseconds).
                      2. Obtain the total seconds totalSeconds by dividing totalMilliseconds by 1000
                         (e.g., 1203183086328 milliseconds / 1000 = 1203183086 seconds).
                      3. Compute the current second from totalSeconds % 60 (e.g., 1203183086 seconds
                         % 60 = 26, which is the current second).
                      4. Obtain the total minutes totalMinutes by dividing totalSeconds by 60 (e.g.,
                         1203183086 seconds / 60 = 20053051 minutes).

                      5. Compute the current minute from totalMinutes % 60 (e.g., 20053051 minutes %
                         60 = 31, which is the current minute).

                      6. Obtain the total hours totalHours by dividing totalMinutes by 60 (e.g.,
                         20053051 minutes / 60 = 334217 hours).

                      7. Compute the current hour from totalHours % 24 (e.g., 334217 hours % 24 = 17,
                         which is the current hour).
                    Listing 2.6 gives the complete program.

                    LISTING 2.6 ShowCurrentTime.java
                     1 public class ShowCurrentTime {
                     2   public static void main(String[] args) {
                     3     // Obtain the total milliseconds since midnight, Jan 1, 1970
totalMilliseconds    4     long totalMilliseconds = System.currentTimeMillis();
                     5
                     6     // Obtain the total seconds since midnight, Jan 1, 1970
totalSeconds         7     long totalSeconds = totalMilliseconds / 1000;
                     8
                     9     // Compute the current second in the minute in the hour
currentSecond       10     long currentSecond = (int)(totalSeconds % 60);
                    11
                    12     // Obtain the total minutes
totalMinutes        13     long totalMinutes = totalSeconds / 60;
                    14
                    15     // Compute the current minute in the hour
currentMinute       16     long currentMinute = totalMinutes % 60;
                    17
                    18     // Obtain the total hours
totalHours          19     long totalHours = totalMinutes / 60;
                    20
                    21     // Compute the current hour
currentHour         22     long currentHour = totalHours % 24;
                    23
                    24     // Display results
                    25     System.out.println("Current time is " + currentHour + ":"
                    26       + currentMinute + ":" + currentSecond + " GMT");
                    27   }
                    28 }




                     Current time is 17:31:26 GMT
                                                                                      2.10 Shorthand Operators             39

                 line#      4                  7            10        13         16         19         22
 variables
 totalMilliseconds          1203183086328

 totalSeconds                                  1203183086

 currentSecond                                              26

 totalMinutes                                                         20053051

 currentMinute                                                                   31

 totalHours                                                                                 334217
 currentHour                                                                                           17




  When System.currentTimeMillis() (line 4) is invoked, it returns the difference,
measured in milliseconds, between the current GMT and midnight, January 1, 1970 GMT.
This method returns the milliseconds as a long value. So, all the variables are declared as the
long type in this program.


2.10 Shorthand Operators
Very often the current value of a variable is used, modified, and then reassigned back to the
same variable. For example, the following statement adds the current value of i with 8 and
assigns the result back to i:

   i = i + 8;

Java allows you to combine assignment and addition operators using a shorthand operator. For
example, the preceding statement can be written as:

   i += 8;

The += is called the addition assignment operator. Other shorthand operators are shown in         addition assignment operator
Table 2.4.



                TABLE 2.4       Shorthand Operators
                Operator    Name                        Example    Equivalent

                +=          Addition assignment         i += 8     i = i + 8

                -=          Subtraction assignment      i -= 8     i = i – 8

                *=          Multiplication assignment   i *= 8     i = i * 8

                /=          Division assignment         i /= 8     i = i / 8

                %=          Remainder assignment        i %= 8     i = i % 8
40 Chapter 2 Elementary Programming

                                     Caution
                                     There are no spaces in the shorthand operators. For example, + = should be +=.


                                     Note
                                     Like the assignment operator (=), the operators (+=, -=, *=, /=, %=) can be used to form an
                                     assignment statement as well as an expression. For example, in the following code, x += 2 is a
                                     statement in the first line and an expression in the second line.

                                     x += 2 ; // Statement
                                     System.out.println(x += 2 ); // Expression

                                  There are two more shorthand operators for incrementing and decrementing a variable by 1.
                               These are handy, because that’s often how much the value needs to be changed. The two opera-
                               tors are ++ and ––. For example, the following code increments i by 1 and decrements j by 1.
                                  int i = 3, j = 3;
                                  i++; // i becomes 4
                                  j——; // j becomes 2

                               The ++ and —— operators can be used in prefix or suffix mode, as shown in Table 2.5.

                               TABLE 2.5     Increment and Decrement Operators
                               Operator        Name                  Description                         Example (assume i = 1)

                               ++var           preincrement          Increment var by 1 and              int j = ++i; // j is 2,
                                                                     use the new var value                 // i is 2

                               var++           postincrement         Increment var by 1, but             int j = i++; // j is 1,
                                                                     use the original var value            // i is 2

                               --var           predecrement          Decrement var by 1 and              int j = --i; // j is 0,
                                                                     use the new var value                 // i is 0

                               var--           postdecrement         Decrement var by 1 and              int j = ++i; // j is 1,
                                                                     use the original var value            // i is 0


                                   If the operator is before (prefixed to) the variable, the variable is incremented or decremented
                               by 1, then the new value of the variable is returned. If the operator is after (suffixed to) the vari-
                               able, then the variable is incremented or decremented by 1, but the original old value of the vari-
                               able is returned. Therefore, the prefixes ++x and ——x are referred to, respectively, as the
preincrement, predecrement     preincrement operator and the predecrement operator; and the suffixes x++ and x—— are referred
postincrement, postdecrement   to, respectively, as the postincrement operator and the postdecrement operator. The prefix form
                               of ++ (or ——) and the suffix form of ++ (or ——) are the same if they are used in isolation, but they
                               cause different effects when used in an expression. The following code illustrates this:

                                            int i = 10;            Same effect as
                                            int newNum = 10 * i++;                            int newNum = 10 * i;
                                                                                              i = i + 1;


                                   In this case, i is incremented by 1, then the old value of i is returned and used in the mul-
                               tiplication. So newNum becomes 100. If i++ is replaced by ++i as follows,

                                            int i = 10;              Same effect as
                                            int newNum = 10 * (++i);                            i = i + 1;
                                                                                                int newNum = 10 * i;
                                                                                         2.11 Numeric Type Conversions                 41
i is incremented by 1, and the new value of i is returned and used in the multiplication. Thus
newNum becomes 110.
   Here is another example:
   double x = 1.0;
   double y = 5.0;
   double z = x–– + (++y);

After all three lines are executed, y becomes 6.0, z becomes 7.0, and x becomes 0.0.
   The increment operator ++ and the decrement operator —— can be applied to all integer and
floating-point types. These operators are often used in loop statements. A loop statement is a
construct that controls how many times an operation or a sequence of operations is performed
in succession. This construct, and the topic of loop statements, are introduced in Chapter 4,
“Loops.”

      Tip
      Using increment and decrement operators makes expressions short, but it also makes them com-
      plex and difficult to read. Avoid using these operators in expressions that modify multiple vari-
      ables or the same variable multiple times, such as this one: int k = ++i + i.



2.11 Numeric Type Conversions
Can you perform binary operations with two operands of different types? Yes. If an integer
and a floating-point number are involved in a binary operation, Java automatically converts
the integer to a floating-point value. So, 3 * 4.5 is same as 3.0 * 4.5.
   You can always assign a value to a numeric variable whose type supports a larger range of
values; thus, for instance, you can assign a long value to a float variable. You cannot, how-
ever, assign a value to a variable of a type with smaller range unless you use type casting.
Casting is an operation that converts a value of one data type into a value of another data type.
Casting a variable of a type with a small range to a variable of a type with a larger range is
known as widening a type. Casting a variable of a type with a large range to a variable of a              widening a type
type with a smaller range is known as narrowing a type. Widening a type can be performed                  narrowing a type
automatically without explicit casting. Narrowing a type must be performed explicitly.
   The syntax is the target type in parentheses, followed by the variable’s name or the value to          type casting
be cast. For example, the following statement

   System.out.println((int)1.7);

displays 1. When a double value is cast into an int value, the fractional part is truncated.
   The following statement

   System.out.println((double)1 / 2);

displays 0.5, because 1 is cast to 1.0 first, then 1.0 is divided by 2. However, the statement
   System.out.println(1 / 2);

displays 0, because 1 and 2 are both integers and the resulting value should also be an integer.


      Caution
      Casting is necessary if you are assigning a value to a variable of a smaller type range, such as    possible loss of precision
      assigning a double value to an int variable. A compile error will occur if casting is not used in
      situations of this kind. Be careful when using casting. Loss of information might lead to
      inaccurate results.
42 Chapter 2 Elementary Programming

                             Note
                             Casting does not change the variable being cast. For example, d is not changed after casting in
                             the following code:

                             double d = 4.5;
                             int i = (int)d;           // i becomes 4, but d is not changed, still 4.5

                             Note
                             To assign a variable of the int type to a variable of the short or byte type, explicit casting
                             must be used. For example, the following statements have a compile error:

                             int i = 1;
                             byte b = i; // Error because explicit casting is required

                             However, so long as the integer literal is within the permissible range of the target variable,
                             explicit casting is not needed to assign an integer literal to a variable of the short or byte type.
                             Please refer to §2.8.2, “Numeric Literals.”

                     Listing 2.7 gives a program that displays the sales tax with two digits after the decimal point.

                     LISTING 2.7 SalesTax.java
                      1 import java.util.Scanner;
                      2
                      3 public class SalesTax {
                      4   public static void main(String[] args) {
                      5     Scanner input = new Scanner(System.in);
                      6
                      7     System.out.print("Enter purchase amount: ");
                      8     double purchaseAmount = input.nextDouble();
                      9
casting              10     double tax = purchaseAmount * 0.06;
                     11     System.out.println("Sales tax is " + (int)(tax * 100) / 100.0) ;
                     12   }
                     13 }



                      Enter purchase amount: 197.55
                      Sales tax is 11.85




                      line#                   purchaseAmount                             tax                      output
                         8                    197.55
                        10                                                               11.853
                        11                                                                                        11.85



formatting numbers     Variable purchaseAmount is 197.55 (line 8). The sales tax is 6% of the purchase, so the
                     tax is evaluated as 11.853 (line 10). Note that

                        tax * 100 is 1185.3
                        (int)(tax * 100) is 1185
                        (int)(tax * 100) / 100.0 is 11.85

                     So, the statement in line 11 displays the tax 11.85 with two digits after the decimal point.
                                                                 2.12 Problem: Computing Loan Payments 43

2.12 Problem: Computing Loan Payments
The problem is to write a program that computes loan payments. The loan can be a car loan, a
                                                                                                 Video Note
student loan, or a home mortgage loan. The program lets the user enter the interest rate, num-   Program computations
ber of years, and loan amount, and displays the monthly and total payments.
   The formula to compute the monthly payment is as follows:

                                       loanAmount * monthlyInterestRate
          monthlyPayment =                             1
                                 1 -
                                       11 + monthlyInterestRate2numberOfYears * 12

You don’t have to know how this formula is derived. Nonetheless, given the monthly interest
rate, number of years, and loan amount, you can use it to compute the monthly payment.
   In the formula, you have to compute 11 + monthlyInterestRate2numberOfYears * 12. The
pow(a, b) method in the Math class can be used to compute a b. The Math class, which             pow(a, b) method
comes with the Java API, is available to all Java programs. For example,
   System.out.println(Math.pow(2, 3)); // Display 8
   System.out.println(Math.pow(4, 0.5)); // Display 4

11 + monthlyInterestRate2numberOfYears * 12 can be computed using Math.pow(1 +
monthlyInterestRate, numberOfYears * 12).
   Here are the steps in developing the program:
   1. Prompt the user to enter the annual interest rate, number of years, and loan amount.
   2. Obtain the monthly interest rate from the annual interest rate.
   3. Compute the monthly payment using the preceding formula.
   4. Compute the total payment, which is the monthly payment multiplied by 12 and multi-
      plied by the number of years.
   5. Display the monthly payment and total payment.
Listing 2.8 gives the complete program.

LISTING 2.8 ComputeLoan.java
 1 import java.util.Scanner;                                                                     import class
 2
 3 public class ComputeLoan {
 4   public static void main(String[] args) {
 5     // Create a Scanner
 6     Scanner input = new Scanner(System.in);                                                   create a Scanner
 7
 8     // Enter yearly interest rate
 9     System.out.print("Enter yearly interest rate, for example 8.25: ");
10     double annualInterestRate = input.nextDouble();                                           enter interest rate
11
12     // Obtain monthly interest rate
13     double monthlyInterestRate = annualInterestRate / 1200;
14
15     // Enter number of years
16     System.out.print(
17       "Enter number of years as an integer, for example 5: ");
18     int numberOfYears = input.nextInt();                                                      enter years
19
20     // Enter loan amount
21     System.out.print("Enter loan amount, for example 120000.95: ");
44 Chapter 2 Elementary Programming
enter loan amount                  22     double loanAmount = input.nextDouble();
                                   23
                                   24     // Calculate payment
monthlyPayment                     25     double monthlyPayment = loanAmount * monthlyInterestRate / (1
                                   26       - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
totalPayment                       27     double totalPayment = monthlyPayment * numberOfYears * 12;
                                   28
                                   29     // Display results
                                   30    System.out.println("The monthly payment is " +
casting                            31      (int)(monthlyPayment * 100) / 100.0);
                                   32    System.out.println("The total payment is " +
casting                            33      (int)(totalPayment * 100) / 100.0);
                                   34   }
                                   35 }


                                    Enter yearly interest rate, for example 8.25: 5.75
                                    Enter number of years as an integer, for example 5: 15
                                    Enter loan amount, for example 120000.95: 250000
                                    The monthly payment is 2076.02
                                    The total payment is 373684.53



                                         line#   10       13                    18       22        25               27
                    variables
                    annualInterestRate           5.75
                    monthlyInterestRate                   0.0047916666666
                    numberOfYears                                               15
                    loanAmount                                                           250000
                    monthlyPayment                                                                 2076.0252175
                    totalPayment                                                                                    373684.539

                                      Line 10 reads the yearly interest rate, which is converted into monthly interest rate in line
                                   13. If you entered an input other than a numeric value, a runtime error would occur.
                                      Choose the most appropriate data type for the variable. For example, numberOfYears is
                                   best declared as an int (line 18), although it could be declared as a long, float, or double.
                                   Note that byte might be the most appropriate for numberOfYears. For simplicity, however,
                                   the examples in this book will use int for integer and double for floating-point values.
                                      The formula for computing the monthly payment is translated into Java code in lines 25–27.
                                      Casting is used in lines 31 and 33 to obtain a new monthlyPayment and totalPayment
                                   with two digits after the decimal point.
                                      The program uses the Scanner class, imported in line 1. The program also uses the Math class;
java.lang package                  why isn’t it imported? The Math class is in the java.lang package. All classes in the java.lang
                                   package are implicitly imported. So, there is no need to explicitly import the Math class.


                                   2.13 Character Data Type and Operations
char type                          The character data type, char, is used to represent a single character. A character literal is
                                   enclosed in single quotation marks. Consider the following code:

                                      char letter = 'A';
                                      char numChar = '4';
                                                                         2.13 Character Data Type and Operations 45
The first statement assigns character A to the char variable letter. The second statement
assigns digit character 4 to the char variable numChar.

      Caution
      A string literal must be enclosed in quotation marks. A character literal is a single character   char literal
      enclosed in single quotation marks. So "A" is a string, and 'A' is a character.


2.13.1 Unicode and ASCII code
Computers use binary numbers internally. A character is stored in a computer as a sequence of           character encoding
0s and 1s. Mapping a character to its binary representation is called encoding. There are differ-
ent ways to encode a character. How characters are encoded is defined by an encoding scheme.
    Java supports Unicode, an encoding scheme established by the Unicode Consortium to                  Unicode
support the interchange, processing, and display of written texts in the world’s diverse lan-
guages. Unicode was originally designed as a 16-bit character encoding. The primitive data              original Unicode
type char was intended to take advantage of this design by providing a simple data type that
could hold any character. However, it turned out that the 65,536 characters possible in a 16-
bit encoding are not sufficient to represent all the characters in the world. The Unicode stan-
dard therefore has been extended to allow up to 1,112,064 characters. Those characters that
go beyond the original 16-bit limit are called supplementary characters. Java supports sup-             supplementary Unicode
plementary characters. The processing and representing of supplementary characters are
beyond the scope of this book. For simplicity, this book considers only the original 16-bit
Unicode characters. These characters can be stored in a char type variable.
    A 16-bit Unicode takes two bytes, preceded by \u, expressed in four hexadecimal digits that
run from '\u0000' to '\uFFFF'. For example, the word “welcome” is translated into Chinese
using two characters,        . The Unicodes of these two characters are “\u6B22\u8FCE”.
    Listing 2.9 gives a program that displays two Chinese characters and three Greek letters.

LISTING 2.9 DisplayUnicode.java
 1 import javax.swing.JOptionPane;
 2
 3 public class DisplayUnicode {
 4   public static void main(String[] args) {
 5     JOptionPane.showMessageDialog(null,
 6       "\u6B22\u8FCE \u03b1 \u03b2 \u03b3",
 7       "\u6B22\u8FCE Welcome",
 8       JOptionPane.INFORMATION_MESSAGE);
 9   }
10 }

    If no Chinese font is installed on your system, you will not be able to see the Chinese char-
acters. The Unicodes for the Greek letters a b g are \u03b1 \u03b2 \u03b3.
    Most computers use ASCII (American Standard Code for Information Interchange), a 7-bit              ASCII
encoding scheme for representing all uppercase and lowercase letters, digits, punctuation
marks, and control characters. Unicode includes ASCII code, with '\u0000' to '\u007F'
corresponding to the 128 ASCII characters. (See Appendix B, “The ASCII Character Set,” for
a list of ASCII characters and their decimal and hexadecimal codes.) You can use ASCII char-
acters such as 'X', '1', and '$' in a Java program as well as Unicodes. Thus, for example,
the following statements are equivalent:

   char letter = 'A';
   char letter = '\u0041'; // Character A's Unicode is 0041

Both statements assign character A to char variable letter.
46 Chapter 2 Elementary Programming

                          Note
char increment and         The increment and decrement operators can also be used on char variables to get the next or
  decrement                preceding Unicode character. For example, the following statements display character b.

                           char ch = 'a';
                           System.out.println(++ch);

                     2.13.2      Escape Sequences for Special Characters
                     Suppose you want to print a message with quotation marks in the output. Can you write a
                     statement like this?
                        System.out.println("He said "Java is fun"");

                     No, this statement has a syntax error. The compiler thinks the second quotation character is
                     the end of the string and does not know what to do with the rest of characters.
                        To overcome this problem, Java defines escape sequences to represent special characters,
backslash            as shown in Table 2.6. An escape sequence begins with the backslash character (\) followed
                     by a character that has a special meaning to the compiler.

                              TABLE 2.6      Java Escape Sequences
                              Character Escape Sequence               Name                   Unicode Code

                                            \b                        Backspace                  \u0008

                                            \t                        Tab                        \u0009

                                            \n                        Linefeed                   \u000A

                                            \f                        Formfeed                   \u000C

                                            \r                        Carriage Return            \u000D

                                            \\                        Backslash                  \u005C

                                            \'                        Single Quote               \u0027

                                            \"                        Double Quote               \u0022

                        So, now you can print the quoted message using the following statement:
                        System.out.println("He said \"Java is fun\"");

                     The output is
                        He said "Java is fun"


                     2.13.3      Casting between char and Numeric Types
                     A char can be cast into any numeric type, and vice versa. When an integer is cast into a
                     char, only its lower 16 bits of data are used; the other part is ignored. For example:

                        char ch = (char)0XAB0041; // the lower 16 bits hex code 0041 is
                                                  // assigned to ch
                        System.out.println(ch);   // ch is character A

                     When a floating-point value is cast into a char, the floating-point value is first cast into an
                     int, which is then cast into a char.

                        char ch = (char)65.25;              // decimal 65 is assigned to ch
                        System.out.println(ch);             // ch is character A
                                                                               2.14 Problem: Counting Monetary Units 47
When a char is cast into a numeric type, the character’s Unicode is cast into the specified
numeric type.
   int i = (int)'A'; // the Unicode of character A is assigned to i
   System.out.println(i); // i is 65

Implicit casting can be used if the result of a casting fits into the target variable. Otherwise,
explicit casting must be used. For example, since the Unicode of 'a' is 97, which is within
the range of a byte, these implicit castings are fine:
   byte b = 'a';
   int i = 'a';

But the following casting is incorrect, because the Unicode \uFFF4 cannot fit into a byte:
   byte b = '\uFFF4';

To force assignment, use explicit casting, as follows:
   byte b = (byte)'\uFFF4';

Any positive integer between 0 and FFFF in hexadecimal can be cast into a character implic-
itly. Any number not in this range must be cast into a char explicitly.

      Note
      All numeric operators can be applied to char operands. A char operand is automatically cast            numeric operators on
      into a number if the other operand is a number or a character. If the other operand is a string, the     characters
      character is concatenated with the string. For example, the following statements

      int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51
      System.out.println("i is " + i); // i is 101
      int j = 2 + 'a'; // (int)'a' is 97
      System.out.println("j is " + j); // j is 99
      System.out.println(j + " is the Unicode for character "
        + (char)j);
      System.out.println("Chapter " + '2');
      display
      i is 101
      j is 99
      99 is the Unicode for character c
      Chapter 2


      Note
      The Unicodes for lowercase letters are consecutive integers starting from the Unicode for 'a',
      then for 'b', 'c', Á , and 'z'. The same is true for the uppercase letters. Furthermore, the
      Unicode for 'a' is greater than the Unicode for 'A'. So 'a' - 'A' is the same as 'b' - 'B'.
      For a lowercase letter ch, its corresponding uppercase letter is (char)('A' + (ch - 'a')).


2.14 Problem: Counting Monetary Units
Suppose you want to develop a program that classifies a given amount of money into smaller
monetary units. The program lets the user enter an amount as a double value representing a
total in dollars and cents, and outputs a report listing the monetary equivalent in dollars, quar-
ters, dimes, nickels, and pennies, as shown in the sample run.
   Your program should report the maximum number of dollars, then the maximum number
of quarters, and so on, in this order.
48 Chapter 2 Elementary Programming
                     Here are the steps in developing the program:
                     1. Prompt the user to enter the amount as a decimal number, such as 11.56.
                     2. Convert the amount (e.g., 11.56) into cents (1156).
                     3. Divide the cents by 100 to find the number of dollars. Obtain the remaining cents using
                        the cents remainder 100.
                     4. Divide the remaining cents by 25 to find the number of quarters. Obtain the remaining
                        cents using the remaining cents remainder 25.
                     5. Divide the remaining cents by 10 to find the number of dimes. Obtain the remaining
                        cents using the remaining cents remainder 10.
                     6. Divide the remaining cents by 5 to find the number of nickels. Obtain the remaining
                        cents using the remaining cents remainder 5.
                     7. The remaining cents are the pennies.
                     8. Display the result.
                   The complete program is given in Listing 2.10.

                   LISTING 2.10 ComputeChange.java
import class        1 import java.util.Scanner;
                    2
                    3 public class ComputeChange {
                    4   public static void main(String[] args) {
                    5     // Create a Scanner
                    6     Scanner input = new Scanner(System.in);
                    7
                    8     // Receive the amount
                    9     System.out.print(
                   10       "Enter an amount in double, for example 11.56: ");
enter input        11     double amount = input.nextDouble();
                   12
                   13     int remainingAmount = (int)(amount * 100);
                   14
                   15     // Find the number of one dollars
dollars            16     int numberOfOneDollars = remainingAmount / 100;
                   17     remainingAmount = remainingAmount % 100;
                   18
                   19     // Find the number of quarters in the remaining amount
quarters           20     int numberOfQuarters = remainingAmount / 25;
                   21     remainingAmount = remainingAmount % 25;
                   22
                   23     // Find the number of dimes in the remaining amount
dimes              24     int numberOfDimes = remainingAmount / 10;
                   25     remainingAmount = remainingAmount % 10;
                   26
                   27     // Find the number of nickels in the remaining amount
nickels            28     int numberOfNickels = remainingAmount / 5;
                   29     remainingAmount = remainingAmount % 5;
                   30
                   31     // Find the number of pennies in the remaining amount
pennies            32     int numberOfPennies = remainingAmount;
                   33
                   34     // Display results
prepare output     35     System.out.println("Your amount " + amount + " consists of \n" +
                                                                  2.14 Problem: Counting Monetary Units 49
36           "\t"   +   numberOfOneDollars + " dollars\n" +
37           "\t"   +   numberOfQuarters + " quarters\n" +
38           "\t"   +   numberOfDimes + " dimes\n" +
39           "\t"   +   numberOfNickels + " nickels\n" +
40           "\t"   +   numberOfPennies + " pennies");
41   }
42 }




 Enter an amount in double, for example 11.56: 11.56
 Your amount 11.56 consists of
        11 dollars
        2 quarters
        0 dimes
        1 nickels
        1 pennies




                line#      11      13     16      17      20      21      24      25      28      29        32
 variables
 Amount                    11.56
 remainingAmount                   1156           56              6               6               1
 numberOfOneDollars                       11
 numberOfQuarters                                         2
 numberOfDimes                                                            0
 numberOfNickles                                                                          1
 numberOfPennies                                                                                            1


    The variable amount stores the amount entered from the console (line 11). This variable is
not changed, because the amount has to be used at the end of the program to display the
results. The program introduces the variable remainingAmount (line 13) to store the chang-
ing remainingAmount.
    The variable amount is a double decimal representing dollars and cents. It is converted to
an int variable remainingAmount, which represents all the cents. For instance, if amount
is 11.56, then the initial remainingAmount is 1156. The division operator yields the inte-
ger part of the division. So 1156 / 100 is 11. The remainder operator obtains the remainder
of the division. So 1156 % 100 is 56.
    The program extracts the maximum number of singles from the total amount and obtains the
remaining amount in the variable remainingAmount (lines 16–17). It then extracts the maxi-
mum number of quarters from remainingAmount and obtains a new remainingAmount
(lines 20–21). Continuing the same process, the program finds the maximum number of dimes,
nickels, and pennies in the remaining amount.
    One serious problem with this example is the possible loss of precision when casting a       loss of precision
double amount to an int remainingAmount. This could lead to an inaccurate result. If you
try to enter the amount 10.03, 10.03 * 100 becomes 1002.9999999999999. You will find
that the program displays 10 dollars and 2 pennies. To fix the problem, enter the amount as an
integer value representing cents (see Exercise 2.9).
50 Chapter 2 Elementary Programming
                               As shown in the sample run, 0 dimes, 1 nickels, and 1 pennies are displayed in the result.
                            It would be better not to display 0 dimes, and to display 1 nickel and 1 penny using the sin-
                            gular forms of the words. You will learn how to use selection statements to modify this pro-
                            gram in the next chapter (see Exercise 3.7).


                            2.15 The String Type
                            The char type represents only one character. To represent a string of characters, use the data
                            type called String. For example, the following code declares the message to be a string with
                            value “Welcome to Java”.

                               String message = "Welcome to Java";

                            String is actually a predefined class in the Java library just like the classes System,
                            JOptionPane, and Scanner. The String type is not a primitive type. It is known as a
                            reference type. Any Java class can be used as a reference type for a variable. Reference data
                            types will be thoroughly discussed in Chapter 8, “Objects and Classes.” For the time being,
                            you need to know only how to declare a String variable, how to assign a string to the vari-
                            able, and how to concatenate strings.
                                As first shown in Listing 2.1, two strings can be concatenated. The plus sign (+) is the
concatenating strings and   concatenation operator if one of the operands is a string. If one of the operands is a nonstring
  numbers                   (e.g., a number), the nonstring value is converted into a string and concatenated with the other
                            string. Here are some examples:

                               // Three strings are concatenated
                               String message = "Welcome " + "to " + "Java";

                               // String Chapter is concatenated with number 2
                               String s = "Chapter" + 2; // s becomes Chapter2

                               // String Supplement is concatenated with character B
                               String s1 = "Supplement" + 'B'; // s1 becomes SupplementB

                            If neither of the operands is a string, the plus sign (+) is the addition operator that adds two
                            numbers.
                               The shorthand += operator can also be used for string concatenation. For example, the fol-
                            lowing code appends the string “and Java is fun” with the string “Welcome to Java” in
                            message.

                               message += " and Java is fun";

                            So the new message is “Welcome to Java and Java is fun”.
                               Suppose that i = 1 and j = 2, what is the output of the following statement?
                               System.out.println("i + j is " + i + j);

                            The output is “i + j is 12” because "i + j is " is concatenated with the value of i first. To
                            force i + j to be executed first, enclose i + j in the parentheses, as follows:
                               System.out.println("i + j is " + ( i + j) );

reading strings                To read a string from the console, invoke the next() method on a Scanner object. For
                            example, the following code reads three strings from the keyboard:
                               Scanner input = new Scanner(System.in);
                               System.out.println("Enter three strings: ");
                               String s1 = input.next();
                                                               2.16 Programming Style and Documentation 51
   String s2 = input.next();
   String s3 = input.next();
   System.out.println("s1 is " + s1);
   System.out.println("s2 is " + s2);
   System.out.println("s3 is " + s3);


 Enter   a string: Welcome to Java
 s1 is   Welcome
 s2 is   to
 s3 is   Java


The next() method reads a string that ends with a whitespace character (i.e., ' ', '\t',
'\f', '\r', or '\n').
  You can use the nextLine() method to read an entire line of text. The nextLine()
method reads a string that ends with the Enter key pressed. For example, the following state-
ments read a line of text.
   Scanner input = new Scanner(System.in);
   System.out.println("Enter a string: ");
   String s = input.nextLine();
   System.out.println("The string entered is " + s);


 Enter a string: Welcome to Java
 The string entered is "Welcome to Java"



     Important Caution
      To avoid input errors, do not use nextLine() after nextByte(), nextShort(), nextInt(),     avoiding input errors
      nextLong(), nextFloat(), nextDouble(), and next(). The reasons will be explained in
      §9.7.3, “How Does Scanner Work?”


2.16 Programming Style and Documentation
Programming style deals with what programs look like. A program can compile and run prop-        programming style
erly even if written on only one line, but writing it all on one line would be bad programming
style because it would be hard to read. Documentation is the body of explanatory remarks and     documentation
comments pertaining to a program. Programming style and documentation are as important as
coding. Good programming style and appropriate documentation reduce the chance of errors
and make programs easy to read. So far you have learned some good programming styles.
This section summarizes them and gives several guidelines. More detailed guidelines can be
found in Supplement I.D, “Java Coding Style Guidelines,” on the Companion Website.

2.16.1 Appropriate Comments and Comment Styles
Include a summary at the beginning of the program to explain what the program does, its key
features, and any unique techniques it uses. In a long program, you should also include com-
ments that introduce each major step and explain anything that is difficult to read. It is
important to make comments concise so that they do not crowd the program or make it diffi-
cult to read.
   In addition to line comment // and block comment /*, Java supports comments of a spe-
cial type, referred to as javadoc comments. javadoc comments begin with /** and end with         javadoc comment
*/. They can be extracted into an HTML file using JDK’s javadoc command. For more
information, see java.sun.com/j2se/javadoc.
52 Chapter 2 Elementary Programming
                                  Use javadoc comments (/** ... */) for commenting on an entire class or an entire
                               method. These comments must precede the class or the method header in order to be extracted
                               in a javadoc HTML file. For commenting on steps inside a method, use line comments (//).

                               2.16.2       Naming Conventions
                               Make sure that you choose descriptive names with straightforward meanings for the variables,
                               constants, classes, and methods in your program. Names are case sensitive. Listed below are
                               the conventions for naming variables, methods, and classes.
naming variables and                 ■   Use lowercase for variables and methods. If a name consists of several words, con-
  methods                                catenate them into one, making the first word lowercase and capitalizing the first let-
                                         ter of each subsequent word—for example, the variables radius and area and the
                                         method showInputDialog.
naming classes                       ■   Capitalize the first letter of each word in a class name—for example, the class names
                                         ComputeArea, Math, and JOptionPane.

naming constants                     ■   Capitalize every letter in a constant, and use underscores between words—for exam-
                                         ple, the constants PI and MAX_VALUE.
                               It is important to follow the naming conventions to make programs easy to read.

                                     Caution
naming classes                       Do not choose class names that are already used in the Java library. For example, since the Math
                                     class is defined in Java, you should not name your class Math.


                                     Tip
using full descriptive names         Avoid using abbreviations for identifiers. Using complete words is more descriptive. For example,
                                     numberOfStudents is better than numStuds, numOfStuds, or numOfStudents.



                               2.16.3       Proper Indentation and Spacing
                               A consistent indentation style makes programs clear and easy to read, debug, and maintain.
indent code                    Indentation is used to illustrate the structural relationships between a program’s components
                               or statements. Java can read the program even if all of the statements are in a straight line, but
                               humans find it easier to read and maintain code that is aligned properly. Indent each subcom-
                               ponent or statement at least two spaces more than the construct within which it is nested.
                                  A single space should be added on both sides of a binary operator, as shown in the follow-
                               ing statement:



                                                              int i= 3+4 * 4;                    Bad style


                                                              int i = 3 + 4 * 4;                 Good style




                                  A single space line should be used to separate segments of the code to make the program
                               easier to read.

                               2.16.4       Block Styles
                               A block is a group of statements surrounded by braces. There are two popular styles, next-line
                               style and end-of-line style, as shown below.
                                                                                       2.17 Programming Errors 53

       public class Test
       {
         public static void main(String[] args)                 public class Test {
         {                                                        public static void main(String[] args) {
           System.out.println("Block Styles");                      System.out.println("Block Styles");
         }                                                        }
       }                                                        }

                          Next-line style                                          End-of-line style



   The next-line style aligns braces vertically and makes programs easy to read, whereas the
end-of-line style saves space and may help avoid some subtle programming errors. Both are
acceptable block styles. The choice depends on personal or organizational preference. You
should use a block style consistently. Mixing styles is not recommended. This book uses the
end-of-line style to be consistent with the Java API source code.


2.17 Programming Errors
Programming errors are unavoidable, even for experienced programmers. Errors can be cate-
gorized into three types: syntax errors, runtime errors, and logic errors.

2.17.1 Syntax Errors
Errors that occur during compilation are called syntax errors or compile errors. Syntax errors         syntax errors
result from errors in code construction, such as mistyping a keyword, omitting some necessary
punctuation, or using an opening brace without a corresponding closing brace. These errors are
usually easy to detect, because the compiler tells you where they are and what caused them.
For example, the following program has a syntax error, as shown in Figure 2.3.




                Compile




FIGURE 2.3   The compiler reports syntax errors.


   1 // ShowSyntaxErrors.java: The program contains syntax errors
   2 public class ShowSyntaxErrors {
   3   public static void main(String[] args) {
   4     i = 30;                                                                                       syntax error
   5     System.out.println(i + 4);
   6   }
   7 }

   Two errors are detected. Both are the result of not declaring variable i. Since a single error
will often display many lines of compile errors, it is a good practice to start debugging from
the top line and work downward. Fixing errors that occur earlier in the program may also fix
additional errors that occur later.
54 Chapter 2 Elementary Programming

                   2.17.2       Runtime Errors
runtime errors     Runtime errors are errors that cause a program to terminate abnormally. They occur while a
                   program is running if the environment detects an operation that is impossible to carry out.
                   Input errors typically cause runtime errors.
                      An input error occurs when the user enters an unexpected input value that the program
                   cannot handle. For instance, if the program expects to read in a number, but instead the user
                   enters a string, this causes data-type errors to occur in the program. To prevent input errors,
                   the program should prompt the user to enter values of the correct type. It may display a mes-
                   sage such as “Please enter an integer” before reading an integer from the keyboard.
                      Another common source of runtime errors is division by zero. This happens when the divi-
                   sor is zero for integer divisions. For instance, the following program would cause a runtime
                   error, as shown in Figure 2.4.



                          Run




                   FIGURE 2.4    The runtime error causes the program to terminate abnormally.


                      1 // ShowRuntimeErrors.java: Program contains runtime errors
                      2 public class ShowRuntimeErrors {
                      3   public static void main(String[] args) {
runtime error         4     int i = 1 / 0 ;
                      5   }
                      6 }


                   2.17.3       Logic Errors
                   Logic errors occur when a program does not perform the way it was intended to. Errors of this
                   kind occur for many different reasons. For example, suppose you wrote the following pro-
                   gram to add number1 to number2.

                      // ShowLogicErrors.java: The program contains a logic error
                      public class ShowLogicErrors {
                        public static void main(String[] args) {
                          // Add number1 to number2
                          int number1 = 3;
                          int number2 = 3;
                          number2 += number1 + number2;
                          System.out.println("number2 is " + number2);
                        }
                      }

                   The program does not have syntax errors or runtime errors, but it does not print the correct
                   result for number2. See if you can find the error.


                   2.17.4       Debugging
                   In general, syntax errors are easy to find and easy to correct, because the compiler gives indi-
                   cations as to where the errors came from and why they are wrong. Runtime errors are not dif-
                   ficult to find, either, since the reasons and locations of the errors are displayed on the console
                   when the program aborts. Finding logic errors, on the other hand, can be very challenging.
                                                                      2.18 (GUI) Getting Input from Input Dialogs 55
   Logic errors are called bugs. The process of finding and correcting errors is called                   bugs
debugging. A common approach is to use a combination of methods to narrow down to the                     debugging
part of the program where the bug is located. You can hand-trace the program (i.e., catch                 hand traces
errors by reading the program), or you can insert print statements in order to show the values
of the variables or the execution flow of the program. This approach might work for a short,
simple program. But for a large, complex program, the most effective approach is to use a
debugger utility.

      Pedagogical NOTE
      An IDE not only helps debug errors but also is an effective pedagogical tool. Supplement II shows   learning tool
      you how to use a debugger to trace programs and how debugging can help you to learn Java
      effectively.


2.18 (GUI) Getting Input from Input Dialogs
You can obtain input from the console. Alternatively, you may obtain input from an input dialog
box by invoking the JOptionPane.showInputDialog method, as shown in Figure 2.5.                           JOptionPane class




                                                               String input =
                                                                 JOptionPane.showInputDialog(
                                                                 "Enter an input");

  Click OK to accept                                               Click Cancel to dismiss the
  input and dismiss the                                            dialog without input
  dialog

FIGURE 2.5    The input dialog box enables the user to enter a string.


   When this method is executed, a dialog is displayed to enable you to enter an input value.
After entering a string, click OK to accept the input and dismiss the dialog box. The input is
returned from the method as a string.
   There are several ways to use the showInputDialog method. For the time being, you need                 showInputDialog method
to know only two ways to invoke it.
   One is to use a statement like this one:
   JOptionPane.showInputDialog(x);

where x is a string for the prompting message.
  The other is to use a statement such as the following:
      String string = JOptionPane.showInputDialog(null, x,
        y, JOptionPane.QUESTION_MESSAGE);

where x is a string for the prompting message and y is a string for the title of the input dialog
box, as shown in the example below.



                                                     String input =
                                                       JOptionPane.showInputDialog(null,
                                                       "Enter an input",
                                                       "Input Dialog Demo",
                                                       JOptionPane.QUESTION_MESSAGE);
56 Chapter 2 Elementary Programming

                           2.18.1 Converting Strings to Numbers
                           The input returned from the input dialog box is a string. If you enter a numeric value such as 123,
                           it returns "123". You have to convert a string into a number to obtain the input as a number.
Integer.parseInt method        To convert a string into an int value, use the parseInt method in the Integer class, as
                           follows:
                              int intValue = Integer.parseInt(intString);

                           where intString is a numeric string such as "123".
Double.parseDouble            To convert a string into a double value, use the parseDouble method in the Double
  method                   class, as follows:
                              double doubleValue = Double.parseDouble(doubleString);

                           where doubleString is a numeric string such as "123.45".
                              The Integer and Double classes are both included in the java.lang package, and thus
                           they are automatically imported.

                           2.18.2      Using Input Dialog Boxes
                           Listing 2.8, ComputeLoan.java, reads input from the console. Alternatively, you can use input
                           dialog boxes.
                              Listing 2.11 gives the complete program. Figure 2.6 shows a sample run of the program.




                                                      (a)                                        (b)




                                                       (c)                                       (d)

                           FIGURE 2.6 The program accepts the annual interest rate (a), number of years (b), and loan
                           amount (c), then displays the monthly payment and total payment (d).

                           LISTING 2.11 ComputeLoanUsingInputDialog.java
                            1 import javax.swing.JOptionPane;
                            2
                            3 public class ComputeLoanUsingInputDialog {
                            4   public static void main(String[] args) {
                            5     // Enter yearly interest rate
enter interest rate         6     String annualInterestRateString = JOptionPane.showInputDialog(
                            7       "Enter yearly interest rate, for example 8.25:");
                            8
                            9     // Convert string to double
convert string to double   10     double annualInterestRate =
                           11       Double.parseDouble(annualInterestRateString);
                           12
                                                                                                             Key Terms 57
13       // Obtain monthly interest rate
14       double monthlyInterestRate = annualInterestRate / 1200;
15
16       // Enter number of years
17       String numberOfYearsString = JOptionPane.showInputDialog(
18         "Enter number of years as an integer, \nfor example 5:");
19
20       // Convert string to int
21       int numberOfYears = Integer.parseInt(numberOfYearsString);
22
23       // Enter loan amount
24       String loanString = JOptionPane.showInputDialog(
25         "Enter loan amount, for example 120000.95:");
26
27       // Convert string to double
28       double loanAmount = Double.parseDouble(loanString);
29
30       // Calculate payment
31       double monthlyPayment = loanAmount * monthlyInterestRate / (1                               monthlyPayment
32         – 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
33       double totalPayment = monthlyPayment * numberOfYears * 12;                                  totalPayment
34
35       // Format to keep two digits after the decimal point
36       monthlyPayment = (int)(monthlyPayment * 100) / 100.0;                                       preparing output
37       totalPayment = (int)(totalPayment * 100) / 100.0;
38
39       // Display results
40       String output = "The monthly payment is " + monthlyPayment +
41         "\nThe total payment is " + totalPayment;
42       JOptionPane.showMessageDialog(null, output );
43   }
44 }

The showInputDialog method in lines 6–7 displays an input dialog. Enter the interest rate
as a double value and click OK to accept the input. The value is returned as a string that is
assigned      to    the    String       variable    annualInterestRateString.            The
Double.parseDouble(annualInterestRateString) (line 11) is used to convert the
string into a double value. If you entered an input other than a numeric value or clicked
Cancel in the input dialog box, a runtime error would occur. In Chapter 13, “Exception Han-
dling,” you will learn how to handle the exception so that the program can continue to run.

     Pedagogical Note
      For obtaining input you can use JOptionPane or Scanner, whichever is convenient. For con-      JOptionPane or Scanner?
      sistency most examples in this book use Scanner for getting input. You can easily revise the
      examples using JOptionPane for getting input.


   KEY TERMS
   algorithm 24                                          data type 25
   assignment operator (=) 30                            debugger 55
   assignment statement 30                               debugging 55
   backslash (\) 46                                      declaration 30
   byte type 27                                          decrement operator (--) 41
   casting 41                                            double type 33
   char type 44                                          encoding 45
   constant 31                                           final 31
58 Chapter 2 Elementary Programming
                     float type     35                                 overflow 33
                     floating-point number 33                          pseudocode 30
                     expression 31                                     primitive data type 25
                     identifier 29                                     runtime error 54
                     increment operator (++) 41                        short type 27
                     incremental development and testing     26        syntax error 53
                     indentation 52                                    supplementary Unicode 45
                     int type 34                                       underflow 33
                     literal 35                                        Unicode 45
                     logic error 54                                    Unix epoch 43
                     long type 35                                      variable 24
                     narrowing (of types) 41                           widening (of types) 41
                     operator 33                                       whitespace 51




                     CHAPTER SUMMARY
                      1. Identifiers are names for things in a program.
                      2. An identifier is a sequence of characters that consists of letters, digits, underscores
                          (_), and dollar signs ($).

                      3. An identifier must start with a letter or an underscore. It cannot start with a digit.
                      4. An identifier cannot be a reserved word.
                      5. An identifier can be of any length.
                      6. Choosing descriptive identifiers can make programs easy to read.
                      7. Variables are used to store data in a program
                      8. To declare a variable is to tell the compiler what type of data a variable can hold.
                      9. By convention, variable names are in lowercase.
                     10. In Java, the equal sign (=) is used as the assignment operator.
                     11. A variable declared in a method must be assigned a value before it can be used.
                     12. A named constant (or simply a constant) represents permanent data that never
                          changes.

                     13. A named constant is declared by using the keyword final.
                     14. By convention, constants are named in uppercase.
                     15. Java provides four integer types (byte, short, int, long) that represent integers of
                          four different sizes.
                                                                                               Chapter Summary 59

16. Java provides two floating-point types (float, double) that represent floating-point
     numbers of two different precisions.

17. Java provides operators that perform numeric operations:       + (addition), – (subtrac-
     tion), * (multiplication), / (division), and % (remainder).

18. Integer arithmetic (/) yields an integer result.
19. The numeric operators in a Java expression are applied the same way as in an arith-
     metic expression.

20. Java provides shorthand operators += (addition assignment), –= (subtraction assign-
     ment), *= (multiplication assignment), /= (division assignment), and %= (remainder
     assignment).

21. The increment operator (++) and the decrement operator (––) increment or decrement
     a variable by 1.

22. When evaluating an expression with values of mixed types, Java automatically con-
     verts the operands to appropriate types.

23. You can explicitly convert a value from one type to another using the (type)exp
     notation.

24. Casting a variable of a type with a small range to a variable of a type with a larger
     range is known as widening a type.

25. Casting a variable of a type with a large range to a variable of a type with a smaller
     range is known as narrowing a type.

26. Widening a type can be performed automatically without explicit casting. Narrowing
     a type must be performed explicitly.

27. Character type (char) represents a single character.
28. The character \ is called the escape character.
29. Java allows you to use escape sequences to represent special characters such as '\t'
     and '\n'.

30. The characters ' ', '\t', '\f', '\r', and '\n’ are known as the whitespace char-
     acters.

31. In computer science, midnight of January 1, 1970, is known as the Unix epoch.
32. Programming errors can be categorized into three types: syntax errors, runtime
     errors, and logic errors.

33. Errors that occur during compilation are called syntax errors or compile errors.
34. Runtime errors are errors that cause a program to terminate abnormally.
35. Logic errors occur when a program does not perform the way it was intended to.
60 Chapter 2 Elementary Programming

                     REVIEW QUESTIONS
                     Sections 2.2–2.7
                     2.1    Which of the following identifiers are valid? Which are Java keywords?
                                         applet, Applet, a++, ––a, 4#R, $4, #44, apps
                                               class, public, int, x, y, radius

                     2.2    Translate the following algorithm into Java code:
                            ■   Step 1: Declare a double variable named miles with initial value 100;
                            ■   Step 2: Declare a double constant named MILES_PER_KILOMETER with value
                                1.609;
                            ■   Step 3: Declare a double variable named kilometers, multiply miles and
                                MILES_PER_KILOMETER, and assign the result to kilometers.
                            ■   Step 4: Display kilometers to the console.
                            What is kilometers after Step 4?
                     2.3    What are the benefits of using constants? Declare an int constant SIZE with
                            value 20.

                     Sections 2.8–2.10
                     2.4    Assume that int a = 1 and double d = 1.0, and that each expression is indepen-
                            dent. What are the results of the following expressions?
                            a   = 46 / 9;
                            a   = 46 % 9 + 4 * 4 - 2;
                            a   = 45 + 43 % 5 * (23 * 3 % 2);
                            a   %= 3 / a + 3;
                            d   = 4 + d * d + 4;
                            d   += 1.5 * 3 + (++a);
                            d   -= 1.5 * 3 + a++;

                     2.5    Show the result of the following remainders.
                            56 % 6
                            78 % -4
                            -34 % 5
                            -34 % -5
                            5 % 1
                            1 % 5

                     2.6    If today is Tuesday, what will be the day in 100 days?
                     2.7    Find the largest and smallest byte, short, int, long, float, and double.
                            Which of these data types requires the least amount of memory?
                     2.8    What is the result of 25 / 4? How would you rewrite the expression if you wished
                            the result to be a floating-point number?
                     2.9    Are the following statements correct? If so, show the output.
                            System.out.println("25 / 4 is " + 25 /              4);
                            System.out.println("25 / 4.0 is " + 25              / 4.0);
                            System.out.println("3 * 2 / 4 is " + 3              * 2 / 4);
                            System.out.println("3.0 * 2 / 4 is " +              3.0 * 2 / 4);

                     2.10 How would you write the following arithmetic expression in Java?
                                                 4                   3 + d12 + a2
                                                       - 91a + bc2 +
                                             31r + 342                  a + bd
                                                                                                  Review Questions 61

2.11 Suppose m and r are integers. Write a Java expression for mr2 to obtain a floating-
       point result.
2.12   Which of these statements are true?
       (a) Any expression can be used as a statement.
       (b) The expression x++ can be used as a statement.
       (c) The statement x = x + 5 is also an expression.
       (d) The statement x = y = x = 0 is illegal.
2.13   Which of the following are correct literals for floating-point numbers?

                     12.3, 12.3e+2, 23.4e-2, –334.4, 20, 39F, 40D

2.14 Identify and fix the errors in the following code:
         1 public class Test {
         2   public void main(string[] args) {
         3     int i;
         4     int k = 100.0;
         5     int j = i + 1;
         6
         7     System.out.println("j is " + j + " and
         8       k is " + k);
         9   }
        10 }

2.15 How do you obtain the current minute using the System.currentTimeMillis()
        method?

Section 2.11
2.16 Can different types of numeric values be used together in a computation?
2.17 What does an explicit conversion from a double to an int do with the fractional
        part of the double value? Does casting change the variable being cast?
2.18    Show the following output.

        float f = 12.5F;
        int i = (int)f;
        System.out.println("f is " + f);
        System.out.println("i is " + i);


Section 2.13
2.19 Use print statements to find out the ASCII code for '1', 'A', 'B', 'a', 'b'. Use
        print statements to find out the character for the decimal code 40, 59, 79, 85, 90. Use
        print statements to find out the character for the hexadecimal code 40, 5A, 71, 72, 7A.
2.20    Which of the following are correct literals for characters?

                               '1', '\u345dE', '\u3fFa', '\b', \t

2.21 How do you display characters \ and "?
2.22 Evaluate the following:
        int i = '1';
        int j = '1' + '2';
        int k = 'a';
        char c = 90;
62 Chapter 2 Elementary Programming

                     2.23 Can the following conversions involving casting be allowed? If so, find the con-
                             verted result.
                             char c = 'A';
                             i = (int)c;
                             float f = 1000.34f;
                             int i = (int)f;

                             double d = 1000.34;
                             int i = (int)d;

                             int i = 97;
                             char c = (char)i;

                     2.24 Show the output of the following program:
                             public class Test {
                               public static void main(String[] args) {
                                 char x = 'a';
                                 char y = 'c';

                                     System.out.println(++x);
                                     System.out.println(y++);
                                     System.out.println(x - y);
                                 }
                             }


                     Section 2.15
                     2.25 Show the output of the following statements (write a program to verify your result):
                             System.out.println("1"          +   1);
                             System.out.println('1'          +   1);
                             System.out.println("1"          +   1 + 1);
                             System.out.println("1"          +   (1 + 1));
                             System.out.println('1'          +   1 + 1);

                     2.26 Evaluate the following expressions (write a program to verify your result):
                             1   +   "Welcome   "   +   1 + 1
                             1   +   "Welcome   "   +   (1 + 1)
                             1   +   "Welcome   "   +   ('\u0001'   + 1)
                             1   +   "Welcome   "   +   'a' + 1


                     Sections 2.16–2.17
                     2.27 What are the naming conventions for class names, method names, constants, and
                             variables? Which of the following items can be a constant, a method, a variable, or
                             a class according to the Java naming conventions?

                                                MAX_VALUE, Test, read, readInt

                     2.28 Reformat the following program according to the programming style and docu-
                             mentation guidelines. Use the next-line brace style.

                             public class Test
                             {
                               // Main method
                               public static void main(String[] args) {
                                                                                                     Programming Exercises 63
            /** Print a line */
            System.out.println("2 % 3 = "+2%3);
            }
        }

2.29 Describe syntax errors, runtime errors, and logic errors.
Section 2.18
2.30 Why do you have to import JOptionPane but not the Math class?
2.31 How do you prompt the user to enter an input using a dialog box?
2.32 How do you convert a string to an integer? How do you convert a string to a double?

PROGRAMMING EXERCISES

      Note
      Students can run all exercises by downloading exercise8e.zip from                                   sample runs
      www.cs.armstrong.edu/liang/intro8e/exercise8e.zip and use the command
      java -cp exercise8e.zip Exercisei_j to run Exercisei_j. For example, to run Exer-
      cise2_1, use

                            java -cp exercise8e.zip Exercise2_1

      This will give you an idea how the program runs.


      Debugging TIP
      The compiler usually gives a reason for a syntax error. If you don’t know how to correct it,        learn from examples
      compare your program closely, character by character, with similar examples in the text.

Sections 2.2–2.9
2.1     (Converting Celsius to Fahrenheit) Write a program that reads a Celsius degree in
        double from the console, then converts it to Fahrenheit and displays the result. The
        formula for the conversion is as follows:

                              fahrenheit = (9 / 5) * celsius + 32

        Hint: In Java, 9 / 5 is 1, but 9.0 / 5 is 1.8.
        Here is a sample run:




        Enter a degree in Celsius: 43
        43 Celsius is 109.4 Fahrenheit




2.2     (Computing the volume of a cylinder) Write a program that reads in the radius and
        length of a cylinder and computes volume using the following formulas:

        area = radius * radius * π
        volume = area * length

        Here is a sample run:
64 Chapter 2 Elementary Programming

                             Enter the radius and length of a cylinder: 5.5 12
                             The area is 95.0331
                             The volume is 1140.4



                     2.3    (Converting feet into meters) Write a program that reads a number in feet, converts it
                            to meters, and displays the result. One foot is 0.305 meter. Here is a sample run:


                             Enter a value for feet: 16
                             16 feet is 4.88 meters



                     2.4    (Converting pounds into kilograms) Write a program that converts pounds into
                            kilograms. The program prompts the user to enter a number in pounds, converts it
                            to kilograms, and displays the result. One pound is 0.454 kilograms. Here is a
                            sample run:


                             Enter a number in pounds: 55.5
                             55.5 pounds is 25.197 kilograms



                     2.5* (Financial application: calculating tips) Write a program that reads the subtotal
                            and the gratuity rate, then computes the gratuity and total. For example, if the user
                            enters 10 for subtotal and 15% for gratuity rate, the program displays $1.5 as gra-
                            tuity and $11.5 as total. Here is a sample run:


                             Enter the subtotal and a gratuity rate: 15.69 15
                             The gratuity is 2.35 and total is 18.04



                     2.6** (Summing the digits in an integer) Write a program that reads an integer between
                            0 and 1000 and adds all the digits in the integer. For example, if an integer is 932,
                            the sum of all its digits is 14.
                            Hint: Use the % operator to extract digits, and use the / operator to remove the
                            extracted digit. For instance, 932 % 10 = 2 and 932 / 10 = 93.
                            Here is a sample run:


                             Enter a number between 0 and 1000: 999
                             The sum of the digits is 27



                     2.7* (Finding the number of years) Write a program that prompts the user to enter the
                            minutes (e.g., 1 billion) and displays the number of years and days for the minutes.
                            For simplicity, assume a year has 365 days. Here is a sample run:

                             Enter the number of minutes: 1000000000
                             1000000000 minutes is approximately 1902 years and 214 days.
                                                                                     Programming Exercises 65
Section 2.13
2.8* (Finding the character of an ASCII code) Write a program that receives an ASCII
       code (an integer between 0 and 128) and displays its character. For example, if the
       user enters 97, the program displays character a. Here is a sample run:


        Enter an ASCII code: 69
        The character for ASCII code 69 is E


2.9* (Financial application: monetary units) Rewrite Listing 2.10, Compute-
       Change.java, to fix the possible loss of accuracy when converting a double value
       to an int value. Enter the input as an integer whose last two digits represent the
       cents. For example, the input 1156 represents 11 dollars and 56 cents.

Section 2.18
2.10* (Using the GUI input) Rewrite Listing 2.10, ComputeChange.java, using the GUI
       input and output.

Comprehensive
2.11* (Financial application: payroll) Write a program that reads the following infor-
       mation and prints a payroll statement:
       Employee’s name (e.g., Smith)
       Number of hours worked in a week (e.g., 10)
       Hourly pay rate (e.g., 6.75)
       Federal tax withholding rate (e.g., 20%)
       State tax withholding rate (e.g., 9%)
       Write this program in two versions: (a) Use dialog boxes to obtain input and dis-
       play output; (b) Use console input and output. A sample run of the console input
       and output is shown below:


        Enter employee's name: Smith
        Enter number of hours worked in a week: 10
        Enter hourly pay rate: 6.75
        Enter federal tax withholding rate: 0.20
        Enter state tax withholding rate: 0.09
        Employee Name: Smith
        Hours Worked: 10.0
        Pay Rate: $6.75
        Gross Pay: $67.5
        Deductions:
          Federal Withholding (20.0%): $13.5
          State Withholding (9.0%): $6.07
          Total Deduction: $19.57
        Net Pay:   $47.92


2.12* (Financial application: calculating interest) If you know the balance and the
       annual percentage interest rate, you can compute the interest on the next monthly
       payment using the following formula:

               interest = balance * 1annualInterestRate / 12002
66 Chapter 2 Elementary Programming
                            Write a program that reads the balance and the annual percentage interest rate and
                            displays the interest for the next month in two versions: (a) Use dialog boxes to
                            obtain input and display output; (b) Use console input and output. Here is a sam-
                            ple run:


                             Enter balance and interest rate (e.g., 3 for 3%): 1000 3.5
                             The interest is 2.91667


                     2.13* (Financial application: calculating the future investment value) Write a program
                            that reads in investment amount, annual interest rate, and number of years, and
                            displays the future investment value using the following formula:

                            futureInvestmentValue =
                              investmentAmount x (1 + monthlyInterestRate)numberOfYears*12

                            For example, if you enter amount 1000, annual interest rate 3.25%, and number of
                            years 1, the future investment value is 1032.98.
                            Hint: Use the Math.pow(a, b) method to compute a raised to the power of b.
                            Here is a sample run:



                             Enter investment amount: 1000
                             Enter monthly interest rate: 4.25
                             Enter number of years: 1
                             Accumulated value is 1043.34




                     2.14* (Health application: computing BMI) Body Mass Index (BMI) is a measure of
                            health on weight. It can be calculated by taking your weight in kilograms and
                            dividing by the square of your height in meters. Write a program that prompts the
Video Note                  user to enter a weight in pounds and height in inches and display the BMI. Note
Compute BMI                 that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. Here is
                            a sample run:



                              Enter weight in pounds: 95.5
                              Enter height in inches: 50
                              BMI is 26.8573



                     2.15** (Financial application: compound value) Suppose you save $100 each month
                              into a savings account with the annual interest rate 5%. So, the monthly interest
                              rate is 0.05 / 12 = 0.00417. After the first month, the value in the account
                              becomes
                                                  100 * (1 + 0.00417) = 100.417

                              After the second month, the value in the account becomes

                                           (100 + 100.417) * (1 + 0.00417) = 201.252
                                                                                       Programming Exercises 67
        After the third month, the value in the account becomes

                       (100 + 201.252) * (1 + 0.00417) = 302.507

        and so on.
        Write a program to display the account value after the sixth month. (In Exercise
        4.30, you will use a loop to simplify the code and display the account value for
        any month.)
2.16    (Science: calculating energy) Write a program that calculates the energy needed
        to heat water from an initial temperature to a final temperature. Your program
        should prompt the user to enter the amount of water in kilograms and the initial
        and final temperatures of the water. The formula to compute the energy is

            Q = M * (final temperature – initial temperature) * 4184

        where M is the weight of water in kilograms, temperatures are in degrees Celsius,
        and energy Q is measured in joules. Here is a sample run:


        Enter the amount of water in kilograms: 55.5
        Enter the initial temperature: 3.5
        Enter the final temperature: 10.5
        The energy needed is 1.62548e+06



2.17*   (Science: wind-chill temperature) How cold is it outside? The temperature alone
        is not enough to provide the answer. Other factors including wind speed, relative
        humidity, and sunshine play important roles in determining coldness outside. In
        2001, the National Weather Service (NWS) implemented the new wind-chill
        temperature to measure the coldness using temperature and wind speed. The for-
        mula is given as follows:

                     twc = 35.74 + 0.6215ta - 35.75v0.16 + 0.4275tav0.16

        where ta is the outside temperature measured in degrees Fahrenheit and v is the speed
        measured in miles per hour. twc is the wind-chill temperature. The formula cannot be
        used for wind speeds below 2 mph or temperatures below -58°F or above 41°F.
        Write a program that prompts the user to enter a temperature between -58°F and
        41°F and a wind speed greater than or equal to 2 and displays the wind-chill
        temperature. Use Math.pow(a, b) to compute v0.16. Here is a sample run:


        Enter the temperature in Fahrenheit: 5.3
        Enter the wind speed miles per hour: 6
        The wind chill index is -5.56707


2.18    (Printing a table) Write a program that displays the following table:
        a        b         pow(a, b)
        1        2         1
        2        3         8
        3        4         81
        4        5         1024
        5        6         15625
68 Chapter 2 Elementary Programming

                     2.19 (Random character) Write a program that displays a random uppercase letter
                            using the System.CurrentTimeMillis() method.
                     2.20   (Geometry: distance of two points) Write a program that prompts the user to enter
                            two points (x1, y1) and (x2, y2) and displays their distances. The formula for
                            computing the distance is 21x2 - x122 + 1y2 - y122 . Note you can use the
                            Math.pow(a, 0.5) to compute 1a. Here is a sample run:



                             Enter x1 and y1: 1.5 -3.4
                             Enter x2 and y2: 4 5
                             The distance of the two points is 8.764131445842194



                     2.21* (Geometry: area of a triangle) Write a program that prompts the user to enter
                            three points (x1, y1), (x2, y2), (x3, y3) of a triangle and displays its area. The
                            formula for computing the area of a triangle is

                                           s = 1side1 + side2 + side32/2;

                                           area = 2s1s - side121s - side221s - side32

                            Here is a sample run.



                             Enter three points for a triangle: 1.5 -3.4 4.6 5 9.5 -3.4
                             The area of the triangle is 33.6



                     2.22 (Geometry: area of a hexagon) Write a program that prompts the user to enter the
                            side of a hexagon and displays its area. The formula for computing the area of a
                            hexagon is
                                                                    3 13 2
                                                          Area =         s ,
                                                                      2

                            where s is the length of a side. Here is a sample run:



                             Enter the side: 5.5
                             The area of the hexagon is 78.5895



                     2.23 (Physics: acceleration) Average acceleration is defined as the change of velocity
                            divided by the time taken to make the change, as shown in the following formula:

                                                                   v1 - v0
                                                             a =
                                                                      t

                            Write a program that prompts the user to enter the starting velocity v0 in
                            meters/second, the ending velocity v1 in meters/second, and the time span t in sec-
                            onds, and displays the average acceleration. Here is a sample run:
                                                                                    Programming Exercises 69

         Enter v0, v1, and t: 5.5 50.9 4.5
         The average acceleration is 10.0889



2.24 (Physics: finding runway length) Given an airplane’s acceleration a and take-off
       speed v, you can compute the minimum runway length needed for an airplane to
       take off using the following formula:

                                                  v2
                                       length =
                                                  2a

       Write a program that prompts the user to enter v in meters/second (m/s) and the
       acceleration a in meters/second squared 1m/s22, and displays the minimum run-
       way length. Here is a sample run:


       Enter v and a: 60 3.5
       The minimum runway length for this airplane is 514.286



2.25* (Current time) Listing 2.6, ShowCurrentTime.java, gives a program that displays
       the current time in GMT. Revise the program so that it prompts the user to enter
       the time zone offset to GMT and displays the time in the specified time zone. Here
       is a sample run:


       Enter the time zone offset to GMT: -5
       The current time is 4:50:34
This page intentionally left blank
                                                          CHAPTER 3
SELECTIONS
Objectives
■   To declare boolean type and write Boolean expressions using comparison operators (§3.2).
■   To program AdditionQuiz using Boolean expressions (§3.3).
■   To implement selection control using one-way if
    statements (§3.4)
■   To program the GuessBirthday game using one-way
    if statements (§3.5).

■   To implement selection control using two-way if
    statements (§3.6).
■   To implement selection control using nested if
    statements (§3.7).
■   To avoid common errors in if statements (§3.8).
■   To program using selection statements for a variety of
    examples(SubtractionQuiz, BMI, ComputeTax) (§3.9–3.11).
■   To generate random numbers using the Math.random()
    method (§3.9).
■   To combine conditions using logical operators (&&, ||,
    and !) (§3.12).
■   To program using selection statements with combined
    conditions (LeapYear, Lottery) (§§3.13–3.14).
■   To implement selection control using switch
    statements (§3.15).
■   To write expressions using the conditional operator (§3.16).
■   To format output using the System.out.printf
    method and to format strings using the String.format
    method (§3.17).
■   To examine the rules governing operator precedence and
    associativity (§3.18).
■   (GUI) To get user confirmation using confirmation
    dialogs (§3.19).
72 Chapter 3 Selections

                       3.1 Introduction
                       If you enter a negative value for radius in Listing 2.2, ComputeAreaWithConsoleInput.java,
                       the program prints an invalid result. If the radius is negative, you don’t want the program to
problem                compute the area. How can you deal with this situation?
                           Like all high-level programming languages, Java provides selection statements that let you
                       choose actions with two or more alternative courses. You can use the following selection
                       statement to replace lines 12–17 in Listing 2.2:
                          if (radius < 0)
                            System.out.println("Incorrect input");
                          else {
                            area = radius * radius * 3.14159;
                            System.out.println("Area is " + area);
                          }

                       Selection statements use conditions. Conditions are Boolean expressions. This chapter first
                       introduces Boolean types, values, comparison operators, and expressions.


                       3.2 boolean Data Type
                       How do you compare two values, such as whether a radius is greater than 0, equal to 0, or less
comparison operators   than 0? Java provides six comparison operators (also known as relational operators), shown
                       in Table 3.1, which can be used to compare two values (assume radius is 5 in the table).

                                          TABLE 3.1 Comparison Operators
                                          Operator      Name                        Example              Result

                                          <             less than                   radius < 0           false

                                          <=            less than or equal to       radius <= 0          false

                                          >             greater than                radius > 0           true

                                          >=            greater than or equal to    radius >= 0          true

                                          ==            equal to                    radius == 0          false

                                          !=            not equal to                radius != 0          true




                            Note
compare characters           You can also compare characters. Comparing characters is the same as comparing their Unicodes.
                             For example, 'a' is larger than 'A' because the Unicode of 'a' is larger than the Unicode of
                             'A'. See Appendix B, “The ASCII Character Sets,” to find the order of characters.


                            Caution
= = vs. =                    The equality comparison operator is two equal signs (==), not a single equal sign (=). The latter
                             symbol is for assignment.

                       The result of the comparison is a Boolean value: true or false. For example, the following
                       statement displays true:
                          double radius = 1;
                          System.out.println(radius > 0);

Boolean variable       A variable that holds a Boolean value is known as a Boolean variable. The boolean data type
                       is used to declare Boolean variables. A boolean variable can hold one of the two values:
                                                               3.3 Problem: A Simple Math Learning Tool 73
true and false. For example, the following statement assigns true to the variable
lightsOn:

   boolean lightsOn = true;

true and false are literals, just like a number such as 10. They are reserved words and can-      Boolean literals
not be used as identifiers in your program.


3.3 Problem: A Simple Math Learning Tool
Suppose you want to develop a program to let a first-grader practice addition. The program
randomly generates two single-digit integers, number1 and number2, and displays to the stu-
                                                                                                  Video Note
dent a question such as “What is 7 + 9?”, as shown in the sample run. After the student types
                                                                                                  Program addition quiz
the answer, the program displays a message to indicate whether it is true or false.
   There are several ways to generate random numbers. For now, generate the first integer using
System.currentTimeMillis() % 10 and the second using System.currentTimeMillis()
* 7 % 10. Listing 3.1 gives the program. Lines 5–6 generate two numbers, number1 and
number2. Line 14 obtains an answer from the user. The answer is graded in line 18 using a
Boolean expression number1 + number2 == answer.

LISTING 3.1 AdditionQuiz.java
 1 import java.util.Scanner;
 2
 3 public class AdditionQuiz {
 4   public static void main(String[] args) {
 5     int number1 = (int)(System.currentTimeMillis() % 10);                                      generate number1
 6     int number2 = (int)(System.currentTimeMillis() * 7 % 10);                                  generate number2
 7
 8     // Create a Scanner
 9     Scanner input = new Scanner(System.in);
10
11     System.out.print(                                                                          show question
12       "What is " + number1 + " + " + number2 + "? ");
13
14     int answer = input.nextInt();
15
16     System.out.println(                                                                        display result
17       number1 + " + " + number2 + " = " + answer + " is " +
18       (number1 + number2 == answer ));
19   }
20 }


 What is 1 + 7? 8
 1 + 7 = 8 is true


 What is 4 + 8? 9
 4 + 8 = 9 is false


 line#            number1            number2            answer             output
   5              4
   6                                 8
  14                                                    9
  16                                                                       4 + 8 = 9 is false
74 Chapter 3 Selections

                          3.4 if Statements
                          The preceding program displays a message such as “6 + 2 = 7 is false.” If you wish the message
why if statement?         to be “6 + 2 = 7 is incorrect,” you have to use a selection statement to carry out this minor change.
                              This section introduces selection statements. Java has several types of selection statements:
                          one-way if statements, two-way if statements, nested if statements, switch statements,
                          and conditional expressions.

                          3.4.1 One-Way if Statements
                          A one-way if statement executes an action if and only if the condition is true. The syntax
                          for a one-way if statement is shown below:
if statement                 if (boolean-expression) {
                               statement(s);
                             }

                          The execution flow chart is shown in Figure 3.1(a).




                          boolean-        false                                                       false
                                                                                 (radius >= 0)
                         expression


                          true                                                       true

                                                          area = radius * radius * PI;
                        Statement(s)
                                                          System.out.println("The area for the circle of" +
                                                            "radius" + radius + "is" + area);




                             (a)                                                        (b)

                    FIGURE 3.1 An if statement executes statements if the boolean-expression evaluates to true.

                            If the boolean-expression evaluates to true, the statements in the block are executed.
                          As an example, see the following code:
                             if (radius >= 0) {
                               area = radius * radius * PI;
                               System.out.println("The area for the circle of radius " +
                                 radius + " is " + area);
                             }

                          The flow chart of the preceding statement is shown in Figure 3.1(b). If the value of radius
                          is greater than or equal to 0, then the area is computed and the result is displayed; otherwise,
                          the two statements in the block will not be executed.
                              The boolean-expression is enclosed in parentheses. For example, the code in (a)
                          below is wrong. It should be corrected, as shown in (b).

                           if i > 0 {                                         if ( i > 0) {
                             System.out.println("i is positive");               System.out.println("i is positive");
                           }                                                  }

                                              (a) Wrong                                          (b) Correct
                                                                            3.5 Problem: Guessing Birthdays         75
The block braces can be omitted if they enclose a single statement. For example, the follow-
ing statements are equivalent.

if (i > 0) {                                                              if (i > 0)
  System.out.println("i is positive");                    Equivalent        System.out.println("i is positive");
}

                         (a)                                                                         (b)


Listing 3.2 gives a program that prompts the user to enter an integer. If the number is a multi-
ple of 5, print HiFive. If the number is divisible by 2, print HiEven.

LISTING 3.2 SimpleIfDemo.java
 1 import java.util.Scanner;
 2
 3 public class SimpleIfDemo {
 4   public static void main(String[] args) {
 5     Scanner input = new Scanner(System.in);
 6     System.out.println("Enter an integer: ");
 7     int number = input.nextInt();                                                                  enter input
 8
 9     if (number % 5 == 0)                                                                           check 5
10       System.out.println("HiFive");
11
12     if (number % 2 == 0)                                                                           check even
13       System.out.println("HiEven");
14   }
15 }


 Enter an integer: 4
 HiEven



 Enter an integer: 30
 HiFive
 HiEven


The program prompts the user to enter an integer (line 7) and displays HiFive if it is divisi-
ble by 5 (lines 9–10) and HiEven if it is divisible by 2 (lines 12–13).


3.5 Problem: Guessing Birthdays
You can find out the date of the month when your friend was born by asking five questions.
Each question asks whether the day is in one of the five sets of numbers.

                                                                                         = 19

                                                                                +


  1  3 5 7           2 3 6 7             4 5 6 7             8 9 10 11         16   17    18    19
  9 11 13 15        10 11 14 15         12 13 14 15         12 13 14 15        20   21    22    23
 17 19 21 23        18 19 22 23         20 21 22 23         24 25 26 27        24   25    26    27
 25 27 29 31        26 27 30 31         28 29 30 31         28 29 30 31        28   29    30    31

      Set1                Set2               Set3                 Set4               Set5
76 Chapter 3 Selections
                           The birthday is the sum of the first numbers in the sets where the day appears. For exam-
                       ple, if the birthday is 19, it appears in Set1, Set2, and Set5. The first numbers in these three
                       sets are 1, 2, and 16. Their sum is 19.
                           Listing 3.3 gives a program that prompts the user to answer whether the day is in Set1
                       (lines 41–47), in Set2 (lines 50–56), in Set3 (lines 59–65), in Set4 (lines 68–74), and in Set5
                       (lines 77–83). If the number is in the set, the program adds the first number in the set to day
                       (lines 47, 56, 65, 74, 83).


                       LISTING 3.3 GuessBirthday.java
                        1 import java.util.Scanner;
                        2
                        3 public class GuessBirthday {
                        4   public static void main(String[] args) {
                        5     String set1 =
                        6       " 1 3 5 7\n" +
                        7       " 9 11 13 15\n" +
                        8       "17 19 21 23\n" +
                        9       "25 27 29 31";
                       10
                       11     String set2 =
                       12       " 2 3 6 7\n" +
                       13       "10 11 14 15\n" +
                       14       "18 19 22 23\n" +
                       15       "26 27 30 31";
                       16
                       17     String set3 =
                       18       " 4 5 6 7\n" +
                       19       "12 13 14 15\n" +
                       20       "20 21 22 23\n" +
                       21       "28 29 30 31";
                       22
                       23     String set4 =
                       24       " 8 9 10 11\n" +
                       25       "12 13 14 15\n" +
                       26       "24 25 26 27\n" +
                       27       "28 29 30 31";
                       28
                       29     String set5 =
                       30       "16 17 18 19\n" +
                       31       "20 21 22 23\n" +
                       32       "24 25 26 27\n" +
                       33       "28 29 30 31";
                       34
day to be determined   35     int day = 0;
                       36
                       37     // Create a Scanner
                       38     Scanner input = new Scanner(System.in);
                       39
                       40     // Prompt the user to answer questions
                       41     System.out.print("Is your birthday in Set1?\n");
                       42     System.out.print(set1);
                       43     System.out.print("\nEnter 0 for No and 1 for Yes: ");
                       44     int answer = input.nextInt();
                       45
in Set1?               46     if (answer == 1)
                       47       day += 1;
                       48
                                                             3.5 Problem: Guessing Birthdays 77
49       // Prompt the user to answer questions
50       System.out.print("\nIs your birthday in Set2?\n" );
51       System.out.print(set2);
52       System.out.print("\nEnter 0 for No and 1 for Yes: ");
53       answer = input.nextInt();
54
55       if (answer == 1)                                                   in Set2?
56         day += 2;
57
58       // Prompt the user to answer questions
59       System.out.print("Is your birthday in Set3?\n");
60       System.out.print(set3);
61       System.out.print("\nEnter 0 for No and 1 for Yes: ");
62       answer = input.nextInt();
63
64       if (answer == 1)                                                   in Set3?
65         day += 4;
66
67       // Prompt the user to answer questions
68       System.out.print("\nIs your birthday in Set4?\n");
69       System.out.print(set4);
70       System.out.print("\nEnter 0 for No and 1 for Yes: ");
71       answer = input.nextInt();
72
73       if (answer == 1)                                                   in Set4?
74         day += 8;
75
76       // Prompt the user to answer questions
77       System.out.print("\nIs your birthday in Set5?\n");
78       System.out.print(set5);
79       System.out.print("\nEnter 0 for No and 1 for Yes: ");
80       answer = input.nextInt();
81
82       if (answer == 1)                                                   in Set5?
83         day += 16;
84
85       System.out.println("\nYour birthday is " + day + "!");
86   }
87 }

 Is your birthday in Set1?
  1 3 5 7
  9 11 13 15
 17 19 21 23
 25 27 29 31
 Enter 0 for No and 1 for Yes: 1
 Is your birthday in Set2?
  2 3 6 7
 10 11 14 15
 18 19 22 23
 26 27 30 31
 Enter 0 for No and 1 for Yes: 1
 Is your birthday in Set3?
  4 5 6 7
 12 13 14 15
 20 21 22 23
 28 29 30 31
 Enter 0 for No and 1 for Yes: 0
78 Chapter 3 Selections

                               Is your birthday in Set4?
                                8 9 10 11
                               12 13 14 15
                               24 25 26 27
                               28 29 30 31
                               Enter 0 for No and 1 for Yes: 0
                               Is your birthday in Set5?
                               16 17 18 19
                               20 21 22 23
                               24 25 26 27
                               28 29 30 31
                               Enter 0 for No and 1 for Yes: 1
                               Your birthday is 19


                               line#                  day                         answer                  output
                                35                    0
                                44                                                1
                                47                    1
                                53                                                1
                                56                    3
                                62                                                0
                                71                                                0
                                80                                                1
                                83                    19
                                                                                                          Your birthday is 19

mathematics behind the game      The game is easy to program. You may wonder how the game was created. The mathematics
                              behind the game is actually quite simple. The numbers are not grouped together by accident.
                              The way they are placed in the five sets is deliberate. The starting numbers in the five sets are 1,
                              2, 4, 8, and 16, which correspond to 1, 10, 100, 1000, and 10000 in binary. A binary number
                              for decimal integers between 1 and 31 has at most five digits, as shown in Figure 3.2(a). Let it
                              be b5b4b3b2b1 . So, b5b4b3b2b1 = b5 0000 + b4 000 + b3 00 + b2 0 + b1 , as shown in
                              Figure 3.2(b). If a day’s binary number has a digit 1 in bk , the number should appear in Setk. For
                              example, number 19 is binary 10011, so it appears in Set1, Set2, and Set5. It is binary 1 + 10 +
                              10000 = 10011 or decimal 1 + 2 + 16 = 19. Number 31 is binary 11111, so it appears in Set1,
                              Set2, Set3, Set4, and Set5. It is binary 1 + 10 + 100 + 1000 + 10000 = 11111 or decimal 1 + 2
                              + 4 + 8 + 16 = 31.

                                                Decimal         Binary                                      10000
                                                                             b5 0 0 0     0
                                                1               00001           b4 0 0                       1000
                                                                                          0
                                                2               00010             b3 0           10000        100
                                                3               00011                     0         10         10
                                                                                     b2   0
                                                ...                                            +     1    +     1
                                                19              10011    +                b1
                                                                                                 10011      11111
                                                ...                          b5 b4 b3 b2 b1
                                                31              11111                                19       31

                                                          (a)                                  (b)

                               FIGURE 3.2 (a) A number between 1 and 31 can be represented using a 5-digit binary
                               number. (b) A 5-digit binary number can be obtained by adding binary numbers 1, 10,
                               100, 1000, or 10000.
                                                                                  3.6 Two-Way if Statements             79

3.6 Two-Way if Statements
A one-way if statement takes an action if the specified condition is true. If the condition is
false, nothing is done. But what if you want to take alternative actions when the condition is
false? You can use a two-way if statement. The actions that a two-way if statement spec-
ifies differ based on whether the condition is true or false.
    Here is the syntax for a two-way if statement:

   if (boolean-expression) {
     statement(s)-for-the-true-case;
   }
   else {
     statement(s)-for-the-false-case;
   }

The flow chart of the statement is shown in Figure 3.3.




                                 true        boolean-         false
                                            expression


       Statement(s) for the true case                          Statement(s) for the false case




FIGURE 3.3An if ... else statement executes statements for the true case if the
boolean-expression evaluates to true; otherwise, statements for the false case are
executed.



   If the boolean-expression evaluates to true, the statement(s) for the true case are exe-
cuted; otherwise, the statement(s) for the false case are executed. For example, consider the
following code:

   if (radius >= 0) {                                                                            two-way if statement
     area = radius * radius * PI;
     System.out.println("The area for the circle of radius " +
       radius + " is " + area);
   }
   else {
     System.out.println("Negative input");
   }

If radius >= 0 is true, area is computed and displayed; if it is false, the message
"Negative input" is printed.
   As usual, the braces can be omitted if there is only one statement within them. The braces
enclosing the System.out.println("Negative input") statement can therefore be
omitted in the preceding example.
80 Chapter 3 Selections
                        Here is another example of using the if ... else statement. The example checks
                      whether a number is even or odd, as follows:

                         if (number % 2 == 0)
                           System.out.println(number + " is even.");
                         else
                           System.out.println(number + " is odd.");


                      3.7 Nested if Statements
                      The statement in an if or if ... else statement can be any legal Java statement, including
                      another if or if ... else statement. The inner if statement is said to be nested inside the
                      outer if statement. The inner if statement can contain another if statement; in fact, there is
                      no limit to the depth of the nesting. For example, the following is a nested if statement:
                         if (i > k) {
nested if statement        if (j > k)
                              System.out.println("i and j are greater than k");
                         }
                         else
                           System.out.println("i is less than or equal to k");

                      The if (j > k) statement is nested inside the if (i > k) statement.
                         The nested if statement can be used to implement multiple alternatives. The statement
                      given in Figure 3.4(a), for instance, assigns a letter grade to the variable grade according to
                      the score, with multiple alternatives.



                              if (score >= 90.0)                                  if (score >= 90.0)
                                grade = 'A';                                        grade = 'A';
                              else                                                else if (score >= 80.0)
                                if (score >= 80.0)                Equivalent        grade = 'B';
                                   grade = 'B';                                   else if (score >= 70.0)
                                else                                                grade = 'C';
                                   if (score >= 70.0)                             else if (score >= 60.0)
                                     grade = 'C';                                   grade = 'D';
                                   else                                           else
                                     if (score >= 60.0)                             grade = 'F';
                                        grade = 'D';             This is better
                                     else
                                       grade = 'F';

                                            (a)                                               (b)

                      FIGURE 3.4   A preferred format for multiple alternative if statements is shown in (b).



                         The execution of this if statement proceeds as follows. The first condition (score >=
                      90.0) is tested. If it is true, the grade becomes 'A'. If it is false, the second condition
                      (score >= 80.0) is tested. If the second condition is true, the grade becomes 'B'. If that
                      condition is false, the third condition and the rest of the conditions (if necessary) continue
                      to be tested until a condition is met or all of the conditions prove to be false. If all of the
                      conditions are false, the grade becomes 'F'. Note that a condition is tested only when all of
                      the conditions that come before it are false.
                         The if statement in Figure 3.4(a) is equivalent to the if statement in Figure 3.4(b). In fact,
                      Figure 3.4(b) is the preferred writing style for multiple alternative if statements. This style
                      avoids deep indentation and makes the program easy to read.
                                                                        3.8 Common Errors in Selection Statements 81

      Tip
      Often, to assign a test condition to a boolean variable, new programmers write code as in (a)           assign boolean variable
      below:

                                                 Equivalent
              if (number % 2 == 0)                                   boolean even
                even = true;                                           = number % 2 == 0;
              else
                even = false;                  This is shorter
                           (a)                                                 (b)

      The code can be simplified by assigning the test value directly to the variable, as shown in (b).


3.8 Common Errors in Selection Statements
The following errors are common among new programmers.
   Common Error 1: Forgetting Necessary Braces
   The braces can be omitted if the block contains a single statement. However, forgetting the
braces when they are needed for grouping multiple statements is a common programming
error. If you modify the code by adding new statements in an if statement without braces,
you will have to insert the braces. For example, the code in (a) below is wrong. It should be
written with braces to group multiple statements, as shown in (b).

if (radius >= 0)                                                 if (radius >= 0) {
  area = radius * radius * PI;                                     area = radius * radius * PI;
  System.out.println("The area "                                   System.out.println("The area "
    + " is " + area);                                                + " is " + area);
                                                                 }

                  (a) Wrong                                                     (b) Correct

   Common Error 2: Wrong Semicolon at the if Line
   Adding a semicolon at the if line, as shown in (a) below, is a common mistake.

                                 Logic Error                                                        Empty Block


if (radius >= 0);                                                    if (radius >= 0) { };
{                                                                    {
  area = radius * radius * PI;                    Equivalent           area = radius * radius * PI;
  System.out.println("The area "                                       System.out.println("The area "
    + " is " + area);                                                    + " is " + area);
}                                                                    }

                     (a)                                                                (b)

    This mistake is hard to find, because it is neither a compilation error nor a runtime error; it
is a logic error. The code in (a) is equivalent to that in (b) with an empty block.
    This error often occurs when you use the next-line block style. Using the end-of-line block
style can help prevent the error.
    Common Error 3: Redundant Testing of Boolean Values
    To test whether a boolean variable is true or false in a test condition, it is redundant to
use the equality comparison operator like the code in (a):

            if (even == true)                    Equivalent          if (even)
              System.out.println(                                      System.out.println(
                "It is even.");                                          "It is even.");

                           (a)                                                  (b)
                                                This is better
82 Chapter 3 Selections
                              Instead, it is better to test the boolean variable directly, as shown in (b). Another good
                           reason for doing this is to avoid errors that are difficult to detect. Using the = operator instead
                           of the == operator to compare equality of two items in a test condition is a common error. It
                           could lead to the following erroneous statement:
                              if (even = true)
                                System.out.println("It is even.");

                           This statement does not have syntax errors. It assigns true to even, so that even is always true.
                              Common Error 4: Dangling else Ambiguity
                              The code in (a) below has two if clauses and one else clause. Which if clause is matched
                           by the else clause? The indentation indicates that the else clause matches the first if clause.
                           However, the else clause actually matches the second if clause. This situation is known as
                           the dangling-else ambiguity. The else clause always matches the most recent unmatched if
                           clause in the same block. So, the statement in (a) is equivalent to the code in (b).


                             int i = 1;                                                int i = 1;
                             int j = 2;                                                int j = 2;
                             int k = 3;                                Equivalent      int k = 3;

                             if (i > j)                                                if (i > j)
                               if (i > k)                             This is better     if (i > k)
                                  System.out.println("A");            with correct         System.out.println("A");
                             else                                     indentation        else
                                  System.out.println("B");                                 System.out.println("B");

                                              (a)                                                      (b)


                             Since (i > j) is false, nothing is printed from the statement in (a) and (b). To force the
                           else clause to match the first if clause, you must add a pair of braces:

                              int i = 1, j = 2, k = 3;

                              if (i > j) {
                                if (i > k)
                                   System.out.println("A");
                              }
                              else
                                System.out.println("B");

                           This statement prints B.


                           3.9 Problem: An Improved Math Learning Tool
                           Suppose you want to develop a program for a first-grader to practice subtraction. The program
                           randomly generates two single-digit integers, number1 and number2, with number1 > =
Video Note
                           number2 and displays to the student a question such as “What is 9 - 2?” After the student
Program subtraction quiz
                           enters the answer, the program displays a message indicating whether it is correct.
                              The previous programs generate random numbers using System.currentTimeMillis().
random() method            A better approach is to use the random() method in the Math class. Invoking this method
                           returns a random double value d such that 0.0 … d 6 1.0. So, (int)(Math.random() *
                           10) returns a random single-digit integer (i.e., a number between 0 and 9).
                              The program may work as follows:
                                 ■   Generate two single-digit integers into number1 and number2.
                                 ■   If number1 < number2, swap number1 with number2.
                                                           3.9 Problem: An Improved Math Learning Tool 83
       ■   Prompt the student to answer “What is number1 – number2?”
       ■   Check the student’s answer and display whether the answer is correct.
The complete program is shown in Listing 3.4.

LISTING 3.4 SubtractionQuiz.java
 1 import java.util.Scanner;
 2
 3 public class SubtractionQuiz {
 4   public static void main(String[] args) {
 5     // 1. Generate two random single-digit integers
 6     int number1 = (int)(Math.random() * 10);                                             random numbers
 7     int number2 = (int)(Math.random() * 10);
 8
 9     // 2. If number1 < number2, swap number1 with number2
10     if (number1 < number2) {
11       int temp = number1;
12       number1 = number2;
13       number2 = temp;
14     }
15
16     // 3. Prompt the student to answer "What is number1 – number2?"
17     System.out.print
18       ("What is " + number1 + " - " + number2 + "? ");
19     Scanner input = new Scanner(System.in);
20     int answer = input.nextInt();                                                        get answer
21
22     // 4. Grade the answer and display the result
23     if (number1 - number2 == answer)                                                     check the answer
24       System.out.println("You are correct!");
25     else
26       System.out.println("Your answer is wrong\n" + number1 + " - "
27          + number2 + " should be " + (number1 - number2));
28   }
29 }


 What is 6 - 6? 0
 You are correct!


 What is 9 - 2? 5
 Your answer is wrong
 9 - 2 should be 7


 line#         number1      number2       temp         answer        output
   6           2
   7                        9
  11                                      2
  12           9
  13                        2
  20                                                   5
  26                                                                 Your answer is wrong
                                                                     9 – 2 should be 7
84 Chapter 3 Selections
                      To swap two variables number1 and number2, a temporary variable temp (line 11) is used
                   to first hold the value in number1. The value in number2 is assigned to number1 (line 12),
                   and the value in temp is assigned to number2 (line 13).


                   3.10 Problem: Computing Body Mass Index
                   Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your
                   weight in kilograms and dividing by the square of your height in meters. The interpretation of
                   BMI for people 16 years or older is as follows:

                           BMI        Interpretation
                          below 16    seriously underweight
                          16–18       underweight
                          18–24       normal weight
                          24–29       overweight
                          29–35       seriously overweight
                          above 35    gravely overweight

                      Write a program that prompts the user to enter a weight in pounds and height in inches and
                   display the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254
                   meters. Listing 3.5 gives the program.

                   LISTING 3.5 ComputeBMI.java
                    1 import java.util.Scanner;
                    2
                    3 public class ComputeAndInterpretBMI {
                    4   public static void main(String[] args) {
                    5     Scanner input = new Scanner(System.in);
                    6
                    7     // Prompt the user to enter weight in pounds
                    8     System.out.print("Enter weight in pounds: ");
input weight        9     double weight = input.nextDouble();
                   10
                   11     // Prompt the user to enter height in inches
                   12     System.out.print("Enter height in inches: ");
input height       13     double height = input.nextDouble();
                   14
                   15     final double KILOGRAMS_PER_POUND = 0.45359237; // Constant
                   16     final double METERS_PER_INCH = 0.0254; // Constant
                   17
                   18     // Compute BMI
                   19     double weightInKilograms = weight * KILOGRAMS_PER_POUND;
                   20     double heightInMeters = height * METERS_PER_INCH;
compute bmi        21     double bmi = weightInKilograms /
                   22       (heightInMeters * heightInMeters);
                   23
                   24     // Display result
display output     25     System.out.printf("Your BMI is %5.2f\n", bmi);
                   26     if (bmi < 16)
                   27       System.out.println("You are seriously underweight");
                   28     else if (bmi < 18)
                   29       System.out.println("You are underweight");
                   30     else if (bmi < 24)
                   31       System.out.println("You are normal weight");
                                                                                3.11 Problem: Computing Taxes 85
32     else if (bmi < 29)
33       System.out.println("You are overweight");
34     else if (bmi < 35)
35       System.out.println("You are seriously overweight");
36     else
37       System.out.println("You are gravely overweight");
38   }
39 }



 Enter weight in pounds: 146
 Enter height in inches: 70
 Your BMI is 20.948603801493316
 You are normal weight


 line# weight        height        WeightInKilograms heightInMeters         bmi        output
   9     146
  13                 70
  19                               66.22448602
  20                                                      1.778
  21                                                                        20.9486
  25                                                                                   Your BMI
                                                                                       is 20.95
  31                                                                                   You are
                                                                                       normal
                                                                                       weight

  Two constants KILOGRAMS_PER_POUND and METERS_PER_INCH are defined in lines
15–16. Using constants here makes programs easy to read.


3.11 Problem: Computing Taxes
The United States federal personal income tax is calculated based on filing status and taxable
income. There are four filing statuses: single filers, married filing jointly, married filing sepa-
                                                                                                      Video Note
rately, and head of household. The tax rates vary every year. Table 3.2 shows the rates for           Use multiple alternative
2009. If you are, say, single with a taxable income of $10,000, the first $8,350 is taxed at 10%      if statements
and the other $1,650 is taxed at 15%. So, your tax is $1,082.5

TABLE 3.2      2009 U.S. Federal Personal Tax Rates
  Marginal                                   Married Filing Jointly
  Tax Rate                Single             or Qualified Widow(er)      Married Filing Separately        Head of Household

  10%                $0 - $8,350                    $0 - $16,700                $0 - $8,350                  $0 - $11,950
  15%             $8,351 - $33,950               $16,701 - $67,900           $8,351 - $33,950             $11,951 - $45,500
  25%             $33,951 - $82,250              $67,901 - $137,050          $33,951 - $68,525           $45,501 - $117,450
  28%            $82,251 - $171,550              $137,051 - $208,850        $68,525 - $104,425           $117,451 - $190,200
  33%            $171,551 - $372,950             $208,851 - $372,950       $104,426 - $186,475           $190,201 - $372,950
  35%                $372,951+                       $372,951+                    $186,476+                    $372,951+
86 Chapter 3 Selections
                       You are to write a program to compute personal income tax. Your program should prompt
                   the user to enter the filing status and taxable income and compute the tax. Enter 0 for single
                   filers, 1 for married filing jointly, 2 for married filing separately, and 3 for head of household.
                       Your program computes the tax for the taxable income based on the filing status. The filing
                   status can be determined using if statements outlined as follows:
                      if (status == 0) {
                        // Compute tax for single filers
                      }
                      else if (status == 1) {
                        // Compute tax for married filing jointly
                      }
                      else if (status == 2) {
                        // Compute tax for married filing separately
                      }
                      else if (status == 3) {
                        // Compute tax for head of household
                      }
                      else {
                        // Display wrong status
                      }

                   For each filing status there are six tax rates. Each rate is applied to a certain amount of taxable
                   income. For example, of a taxable income of $400,000 for single filers, $8,350 is taxed at
                   10%, 133,950 - 8,3502 at 15%, 182,250 - 33,9502 at 25%, 1171,550 - 82,2502 at 28%,
                   1372,950 - 171,5502 at 33%, and 1400,000 - 372,9502 at 35%.
                       Listing 3.6 gives the solution to compute taxes for single filers. The complete solution is
                   left as an exercise.

                   LISTING 3.6 ComputeTax.java
                    1 import java.util.Scanner;
                    2
                    3 public class ComputeTax {
                    4   public static void main(String[] args) {
                    5     // Create a Scanner
                    6     Scanner input = new Scanner(System.in);
                    7
                    8     // Prompt the user to enter filing status
                    9     System.out.print(
                   10       "(0-single filer, 1-married jointly,\n" +
                   11       "2-married separately, 3-head of household)\n" +
                   12       "Enter the filing status: ");
input status       13     int status = input.nextInt();
                   14
                   15     // Prompt the user to enter taxable income
                   16     System.out.print("Enter the taxable income: ");
input income       17     double income = input.nextDouble();
                   18
                   19     // Compute tax
                   20     double tax = 0;
                   21
compute tax        22     if (status == 0) { // Compute tax for single filers
                   23       if (income <= 8350)
                   24         tax = income * 0.10;
                   25       else if (income <= 33950)
                   26         tax = 8350 * 0.10 + (income - 8350) * 0.15;
                   27       else if (income <= 82250)
                   28         tax = 8350 * 0.10 + (33950 - 8350) * 0.15 +
                                                                              3.11 Problem: Computing Taxes 87
29              (income - 33950) * 0.25;
30         else if (income <= 171550)
31           tax = 8350 * 0.10 + (33950 - 8350) *             0.15 +
32              (82250 - 33950) * 0.25 + (income -            82250) * 0.28;
33         else if (income <= 372950)
34           tax = 8350 * 0.10 + (33950 - 8350) *             0.15 +
35              (82250 - 33950) * 0.25 + (171550 -            82250) * 0.28 +
36              (income - 171550) * 0.35;
37         else
38           tax = 8350 * 0.10 + (33950 - 8350) *             0.15 +
39             (82250 - 33950) * 0.25 + (171550 -             82250) * 0.28 +
40             (372950 - 171550) * 0.33 + (income             - 372950) * 0.35;
41       }
42       else if (status == 1) { // Compute tax for married file jointly
43         // Left as exercise
44       }
45       else if (status == 2) { // Compute tax for married separately
46         // Left as exercise
47       }
48       else if (status == 3) { // Compute tax for head of household
49         // Left as exercise
50       }
51       else {
52         System.out.println("Error: invalid status");
53         System.exit(0);                                                                        exit program
54       }
55
56       // Display the result
57       System.out.println("Tax is " + (int)(tax * 100) / 100.0);                                display output
58   }
59 }



 (0-single filer, 1-married jointly,
 2-married separately, 3-head of household)
 Enter the filing status: 0
 Enter the taxable income: 400000
 Tax is 117683.5



 line#            status             income             tax                output
  13              0
  17                                  400000
  20                                                    0
  38                                                     117683.5
  57                                                                        Tax is 117683.5


    The program receives the filing status and taxable income. The multiple alternative if
statements (lines 22, 42, 45, 48, 51) check the filing status and compute the tax based on the
filing status.
    System.exit(0) (line 53) is defined in the System class. Invoking this method termi-          System.exit(0)
nates the program. The argument 0 indicates that the program is terminated normally.
    An initial value of 0 is assigned to tax (line 20). A syntax error would occur if it had no
initial value, because all of the other statements that assign values to tax are within the if
88 Chapter 3 Selections
                              statement. The compiler thinks that these statements may not be executed and therefore
                              reports a syntax error.
test all cases                   To test a program, you should provide the input that covers all cases. For this program,
                              your input should cover all statuses (0, 1, 2, 3). For each status, test the tax for each of the six
                              brackets. So, there are a total of 24 cases.

                                     Tip
                                     For all programs, you should write a small amount of code and test it before moving on to add
incremental development and          more code. This is called incremental development and testing. This approach makes debugging
   testing                           easier, because the errors are likely in the new code you just added.


                              3.12 Logical Operators
                              Sometimes, whether a statement is executed is determined by a combination of several condi-
                              tions. You can use logical operators to combine these conditions. Logical operators, also known
                              as Boolean operators, operate on Boolean values to create a new Boolean value. Table 3.3 gives
                              a list of Boolean operators. Table 3.4 defines the not (!) operator. The not (!) operator negates
                              true to false and false to true. Table 3.5 defines the and (&&) operator. The and (&&) of
                              two Boolean operands is true if and only if both operands are true. Table 3.6 defines the or
                              (||) operator. The or (||) of two Boolean operands is true if at least one of the operands is
                              true. Table 3.7 defines the exclusive or (^) operator. The exclusive or (^) of two Boolean
                              operands is true if and only if the two operands have different Boolean values.


                                                   TABLE 3.3      Boolean Operators
                                                   Operator            Name                    Description

                                                   !                   not                     logical negation
                                                   &&                  and                     logical conjunction
                                                   ||                  or                      logical disjunction
                                                   ^                   exclusive or            logical exclusion


                              TABLE 3.4      Truth Table for Operator !
                              p                        !p                    Example (assume age = 24, gender = ‘F’)

                              true                     false                 !1age 7 182 is false, because 1age 7 182 is true.
                              false                    true                  !(gender == 'M') is true, because (gender == 'M')
                                                                               is false.


                              TABLE 3.5      Truth Table for Operator &&
                              p1              p2               p1 && p2               Example (assume age = 24, gender = ‘F’)

                              false           false            false                  (age > 18) && (gender == 'F') is true,
                                                                                      because (age > 18) and (gender == 'F') are
                                                                                      both true.
                              false           true             false

                              true            false            false                  (age > 18) && (gender != 'F') is false,
                                                                                      because (gender != 'F') is false.

                              true            true             true
                                                                                           3.12 Logical Operators   89
TABLE 3.6      Truth Table for Operator ||
p1        p2       p1 || p2 Example (assume age = 24, gender = ‘F’)

false     false    false     (age > 34) || (gender == 'F') is true, because (gender == 'F')
                             is true.
false     true     true

true      false    true      (age > 34) || (gender == 'M') is false, because (age > 34) and
                             (gender == 'M') are both false.

true      true     true



TABLE 3.7      Truth Table for Operator ^
p1        p2       p1 ^ p2   Example (assume age = 24, gender = ‘F’)
false     false    false     (age > 34) ^ (gender == 'F') is true, because (age > 34) is
                             false but (gender == 'F') is true.
false     true     true

true      false    true      (age > 34) || (gender == 'M') is false, because (age > 34) and
                             (gender == 'M') are both false.

true      true     false


     Listing 3.7 gives a program that checks whether a number is divisible by 2 and 3, by 2 or
3, and by 2 or 3 but not both:

LISTING 3.7 TestBooleanOperators.java
 1 import java.util.Scanner;                                                                      import class
 2
 3 public class TestBooleanOperators {
 4   public static void main(String[] args) {
 5     // Create a Scanner
 6     Scanner input = new Scanner(System.in);
 7
 8     // Receive an input
 9     System.out.print("Enter an integer: ");
10     int number = input.nextInt();                                                              input
11
12     System.out.println("Is " + number +
13       "\n\tdivisible by 2 and 3? " +
14       (number % 2 == 0 && number % 3 == 0 )                                                    and
15       + "\n\tdivisible by 2 or 3? " +
16       (number % 2 == 0 || number % 3 == 0 ) +                                                  or
17       "\n\tdivisible by 2 or 3, but not both? "
18       + (number % 2 == 0 ^ number % 3 == 0 ));                                                 exclusive or
19   }
20 }




 Enter an integer: 18
 Is 18
   divisible by 2 and 3? true
   divisible by 2 or 3? true
   divisible by 2 or 3, but not both? false
90 Chapter 3 Selections
                         A long string is formed by concatenating the substrings in lines 12–18. The three \n charac-
                         ters display the string in four lines. (number % 2 == 0 && number % 3 == 0) (line 14) checks
                         whether the number is divisible by 2 and 3. (number % 2 == 0 || number % 3 == 0) (line 16)
                         checks whether the number is divisible by 2 or 3. (number % 2 == 0 ^ number % 3 == 0) (line
                         20) checks whether the number is divisible by 2 or 3, but not both.

                               Caution
                               In mathematics, the expression

                               1 <= numberOfDaysInAMonth <= 31

                               is correct. However, it is incorrect in Java, because 1 <= numberOfDaysInAMonth is evaluated
                               to a boolean value, which cannot be compared with 31. Here, two operands (a boolean value
incompatible operands          and a numeric value) are incompatible. The correct expression in Java is

                               (1 <= numberOfDaysInAMonth) && (numberOfDaysInAMonth <= 31)


                               Note
                               As shown in the preceding chapter, a char value can be cast into an int value, and vice versa.
                               A boolean value, however, cannot be cast into a value of another type, nor can a value of
cannot cast boolean            another type be cast into a boolean value.


                               Note
De Morgan’s law                De Morgan’s law, named after Indian-born British mathematician and logician Augustus De Morgan
                               (1806–1871), can be used to simplify Boolean expressions. The law states

                               !(condition1 && condition2) is same as !condition1 || !condition2
                               !(condition1 || condition2) is same as !condition1 && !condition2

                               For example,
                               !(n == 2 || n == 3) is same as n != 2 && n != 3
                               !(n % 2 == 0 && n % 3 == 0) is same as n % 2 != 0 || n % 3 != 0

                             If one of the operands of an && operator is false, the expression is false; if one of the
                         operands of an || operator is true, the expression is true. Java uses these properties to
                         improve the performance of these operators. When evaluating p1 && p2, Java first evaluates
                         p1 and then, if p1 is true, evaluates p2; if p1 is false, it does not evaluate p2. When eval-
                         uating p1 || p2, Java first evaluates p1 and then, if p1 is false, evaluates p2; if p1 is true,
conditional operator     it does not evaluate p2. Therefore, && is referred to as the conditional or short-circuit AND
short-circuit operator   operator, and ƒ ƒ is referred to as the conditional or short-circuit OR operator.


                         3.13 Problem: Determining Leap Year
leap year                A year is a leap year if it is divisible by 4 but not by 100 or if it is divisible by 400. So you
                         can use the following Boolean expressions to check whether a year is a leap year:
                            // A leap year is divisible by 4
                            boolean isLeapYear = (year % 4 == 0);
                            // A leap year is divisible by 4 but not by 100
                            isLeapYear = isLeapYear && (year % 100 != 0);
                            // A leap year is divisible by 4 but not by 100 or divisible by 400
                            isLeapYear = isLeapYear || (year % 400 == 0);

                         or you can combine all these expressions into one like this:
                            isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
                                                                                             3.14 Problem: Lottery 91
Listing 3.8 gives the program that lets the user enter a year and checks whether it is a leap
year.

LISTING 3.8 LeapYear.java
 1 import java.util.Scanner;
 2
 3 public class LeapYear {
 4   public static void main(String[] args) {
 5     // Create a Scanner
 6     Scanner input = new Scanner(System.in);
 7     System.out.print("Enter a year: ");
 8     int year = input.nextInt();                                                                    input
 9
10     // Check if the year is a leap year
11     boolean isLeapYear =                                                                           leap year?
12       (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ;
13
14     // Display the result
15     System.out.println(year + " is a leap year? " + isLeapYear);                                   display result
16   }
17 }



 Enter a year: 2008
 2008 is a leap year? true
 Enter a year: 2002
 2002 is a leap year? false



3.14 Problem: Lottery
Suppose you want to develop a program to play lottery. The program randomly generates a
lottery of a two-digit number, prompts the user to enter a two-digit number, and determines
whether the user wins according to the following rule:
   1. If the user input matches the lottery in exact order, the award is $10,000.
   2. If all the digits in the user input match all the digits in the lottery, the award is $3,000.
   3. If one digit in the user input matches a digit in the lottery, the award is $1,000.
The complete program is shown in Listing 3.9.

LISTING 3.9 Lottery.java
 1 import java.util.Scanner;
 2
 3 public class Lottery {
 4   public static void main(String[] args) {
 5     // Generate a lottery
 6     int lottery = (int)(Math.random() * 100);                                                      generate a lottery
 7
 8     // Prompt the user to enter a guess
 9     Scanner input = new Scanner(System.in);
10     System.out.print("Enter your lottery pick (two digits): ");
11     int guess = input.nextInt();                                                                   enter a guess
12
13     //   Get digits from lottery
14     int lotteryDigit1 = lottery / 10;
92 Chapter 3 Selections
                    15        int lotteryDigit2 = lottery % 10;
                    16
                    17        // Get digits from guess
                    18        int guessDigit1 = guess / 10;
                    19        int guessDigit2 = guess % 10;
                    20
                    21        System.out.println("The lottery number is " + lottery);
                    22
                    23        // Check the guess
exact match?        24        if (guess == lottery)
                    25          System.out.println("Exact match: you win $10,000");
match all digits?   26        else if (guessDigit2 == lotteryDigit1
                    27              && guessDigit1 == lotteryDigit2)
                    28          System.out.println("Match all digits: you win $3,000");
match one digit?    29        else if (guessDigit1 == lotteryDigit1
                    30              || guessDigit1 == lotteryDigit2
                    31              || guessDigit2 == lotteryDigit1
                    32              || guessDigit2 == lotteryDigit2)
                    33          System.out.println("Match one digit: you win $1,000");
                    34        else
                    35          System.out.println("Sorry, no match");
                    36   }
                    37 }


                     Enter your lottery pick (two digits): 45
                     The lottery number is 12
                     Sorry, no match



                     Enter your lottery pick: 23
                     The lottery number is 34
                     Match one digit: you win $1,000


                          line#      6       11         14        15         18         19        33
                     variable
                     lottery         34
                     guess                   23
                     lotteryDigit1                      3
                     lotteryDigit2                                4
                     guessDigit1                                             2
                     guessDigit2                                                        3
                     output                                                                       Match one digit:
                                                                                                  you win $1,000

                       The program generates a lottery using the random() method (line 6) and prompts the user to
                    enter a guess (line 11). Note that guess % 10 obtains the last digit from guess and guess / 10
                    obtains the first digit from guess, since guess is a two-digit number (lines 18–19).
                       The program checks the guess against the lottery number in this order:
                       1. First check whether the guess matches the lottery exactly (line 24).
                       2. If not, check whether the reversal of the guess matches the lottery (lines 26–27).
                                                                                    3.15 switch Statements         93
   3. If not, check whether one digit is in the lottery (lines 29–32).
   4. If not, nothing matches.


3.15 switch Statements
The if statement in Listing 3.6, ComputeTax.java, makes selections based on a single true
or false condition. There are four cases for computing taxes, which depend on the value of
status. To fully account for all the cases, nested if statements were used. Overuse of nested
if statements makes a program difficult to read. Java provides a switch statement to handle
multiple conditions efficiently. You could write the following switch statement to replace
the nested if statement in Listing 3.6:

  switch (status) {
    case 0: compute taxes for single filers;
             break;
    case 1: compute taxes for married filing jointly;
             break;
    case 2: compute taxes for married filing separately;
             break;
    case 3: compute taxes for head of household;
             break;
    default: System.out.println("Errors: invalid status");
             System.exit(0);
  }

The flow chart of the preceding switch statement is shown in Figure 3.5.



                    status is 0
                                  Compute tax for single filers             break


                    status is 1
                                  Compute tax for married file jointly      break


                    status is 2
                                  Compute tax for married file separately   break


                    status is 3
                                  Compute tax for head of household         break


                    default
                                  Default actions




FIGURE 3.5 The switch statement checks all cases and executes the statements in the
matched case.

   This statement checks to see whether the status matches the value 0, 1, 2, or 3, in that
order. If matched, the corresponding tax is computed; if not matched, a message is displayed.
Here is the full syntax for the switch statement:

    switch (switch-expression) {                                                                switch statement
      case value1: statement(s)1;
                   break;
94 Chapter 3 Selections
                                     case value2: statement(s)2;
                                                  break;
                                     ...
                                     case valueN: statement(s)N;
                                                  break;
                                     default:     statement(s)-for-default;
                                 }

                            The switch statement observes the following rules:
                                     ■   The switch-expression must yield a value of char, byte, short, or int type
                                         and must always be enclosed in parentheses.
                                     ■   The value1, Á , and valueN must have the same data type as the value of the
                                         switch-expression. Note that value1, Á , and valueN are constant expres-
                                         sions, meaning that they cannot contain variables, such as 1 + x.
                                     ■   When the value in a case statement matches the value of the switch-expression,
                                         the statements starting from this case are executed until either a break statement or
                                         the end of the switch statement is reached.
                                     ■   The keyword break is optional. The break statement immediately ends the
                                         switch statement.

                                     ■   The default case, which is optional, can be used to perform actions when none of
                                         the specified cases matches the switch-expression.
                                     ■   The case statements are checked in sequential order, but the order of the cases
                                         (including the default case) does not matter. However, it is good programming
                                         style to follow the logical sequence of the cases and place the default case at the
                                         end.

                                     Caution
without break                        Do not forget to use a break statement when one is needed. Once a case is matched, the state-
                                     ments starting from the matched case are executed until a break statement or the end of the
fall-through behavior                switch statement is reached. This is referred to as fall-through behavior. For example, the fol-
                                     lowing code prints character a three times if ch is 'a':



                        switch   (ch)    {
                          case   'a':    System.out.println(ch);                                   true
                          case   'b':    System.out.println(ch);                    ch is 'a'              System.out.println(ch)
                          case   'c':    System.out.println(ch);                  false
                        }
                                                                                                   true
                                                                                    ch is 'b'              System.out.println(ch)
                                                                                  false
                                                                                                  true
                                                                                    ch is 'c'              System.out.println(ch)
                                                                                  false




                                     Tip
                                     To avoid programming errors and improve code maintainability, it is a good idea to put a com-
                                     ment in a case clause if break is purposely omitted.
                                                                                           3.17 Formatting Console Output 95

3.16 Conditional Expressions
You might want to assign a value to a variable that is restricted by certain conditions. For
example, the following statement assigns 1 to y if x is greater than 0, and -1 to y if x is less
than or equal to 0.

   if (x > 0)
     y = 1;
   else
     y = -1;

Alternatively, as in this example, you can use a conditional expression to achieve the same
result.

   y = (x > 0) ? 1 : -1;

Conditional expressions are in a completely different style, with no explicit if in the state-
ment. The syntax is shown below:

   boolean-expression ? expression1 : expression2;

The result of this conditional expression is expression1 if boolean-expression is true;                       conditional expression
otherwise the result is expression2.
   Suppose you want to assign the larger number between variable num1 and num2 to max.
You can simply write a statement using the conditional expression:

   max = (num1 > num2) ? num1 : num2;

For another example, the following statement displays the message “num is even” if num is
even, and otherwise displays “num is odd.”

   System.out.println((num % 2 == 0) ? "num is even" : "num is odd");


     Note
      The symbols ? and : appear together in a conditional expression. They form a conditional oper-
      ator. It is called a ternary operator because it uses three operands. It is the only ternary operator
      in Java.


3.17 Formatting Console Output
If you wish to display only two digits after the decimal point in a floating-point value, you
may write the code like this:

   double x = 2.0 / 3;
   System.out.println("x is " + (int)(x * 100) / 100.0);


 x is 0.66


  However, a better way to accomplish this task is to format the output using the printf                      printf
method. The syntax to invoke this method is

   System.out.printf(format, item1, item2, ..., itemk)

where format is a string that may consist of substrings and format specifiers.
96 Chapter 3 Selections
specifier             A format specifier specifies how an item should be displayed. An item may be a numeric
                   value, a character, a Boolean value, or a string. A simple specifier consists of a percent sign
                   (%) followed by a conversion code. Table 3.8 lists some frequently used simple specifiers:

                               TABLE 3.8      Frequently Used Specifiers
                               Specifier      Output                                           Example

                               %b             a Boolean value                                  true or false
                               %c             a character                                      ‘a’
                               %d             a decimal integer                                200
                               %f             a floating-point number                          45.460000
                               %e             a number in standard scientific notation         4.556000e+01
                               %s             a string                                         “Java is cool”

                      Here is an example:

                            int count = 5;                                        items
                            double amount = 45.56;
                            System.out.printf("count is %d and amount is %f", count, amount);




                            display                      count is 5 and amount is 45.560000

                      Items must match the specifiers in order, in number, and in exact type. For example, the
                   specifier for count is %d and for amount is %f. By default, a floating-point value is displayed
                   with six digits after the decimal point. You can specify the width and precision in a specifier,
                   as shown in the examples in Table 3.9.

                   TABLE 3.9    Examples of Specifying Width and Precision
                   Example     Output

                   %5c         Output the character and add four spaces before the character item.

                   %6b         Output the Boolean value and add one space before the false value and two spaces before
                               the true value.

                   %5d         Output the integer item with width at least 5. If the number of digits in the item is 6 5,
                               add spaces before the number. If the number of digits in the item is 7 5, the width is
                               automatically increased.

                   %10.2f      Output the floating-point item with width at least 10 including a decimal point and two
                               digits after the point. Thus there are 7 digits allocated before the decimal point. If the
                               number of digits before the decimal point in the item is 6 7, add spaces before the
                               number. If the number of digits before the decimal point in the item is 7 7, the width is
                               automatically increased.

                   %10.2e      Output the floating-point item with width at least 10 including a decimal point, two digits
                               after the point and the exponent part. If the displayed number in scientific notation has
                               width less than 10, add spaces before the number.

                   %12s        Output the string with width at least 12 characters. If the string item has less than 12 char-
                               acters, add spaces before the string. If the string item has more than 12 characters, the
                               width is automatically increased.
                                                                           3.18 Operator Precedence and Associativity 97
   The code presented in the beginning of this section for displaying only two digits after the
decimal point in a floating-point value can be revised using the printf method as follows:

     double x = 2.0 / 3;
     System.out.printf("x is %4.2f", x);                                % 4 . 2 f           format specifier

     display                     x is 0.67
                                                                field width        conversion code

                                                                           precision


   By default, the output is right justified. You can put the minus sign (-) in the specifier to               left justify
specify that the item is left justified in the output within the specified field. For example, the
following statements

   System.out.printf("%8d%8s%8.1f\n", 1234, "Java", 5.6);
   System.out.printf("%-8d%-8s%-8.1f \n", 1234, "Java", 5.6);

display


       8 characters                  8 characters                   8 characters
               1 2 3 4                       J   a   v   a                    5     .   6

 1 2 3 4                      J a v a                         5 .   6



      Caution
      The items must match the specifiers in exact type. The item for the specifier %f or %e must be a
      floating-point type value such as 40.0, not 40. Thus an int variable cannot match %f or %e.


      Tip
      The % sign denotes a specifier. To output a literal % in the format string, use %%.


3.18 Operator Precedence and Associativity
Operator precedence and associativity determine the order in which operators are evaluated.
Suppose that you have this expression:

   3 + 4 * 4 > 5 * (4 + 3) – 1

What is its value? What is the execution order of the operators?
   Arithmetically, the expression in the parentheses is evaluated first. (Parentheses can be
nested, in which case the expression in the inner parentheses is executed first.) When evaluat-
ing an expression without parentheses, the operators are applied according to the precedence
rule and the associativity rule.
   The precedence rule defines precedence for operators, as shown in Table 3.10, which contains                precedence
the operators you have learned so far. Operators are listed in decreasing order of precedence from
top to bottom. Operators with the same precedence appear in the same group. (See Appendix C,
“Operator Precedence Chart,” for a complete list of Java operators and their precedence.)
   If operators with the same precedence are next to each other, their associativity determines                associativity
the order of evaluation. All binary operators except assignment operators are left associative.
For example, since + and – are of the same precedence and are left associative, the expression

                                                 equivalent
                 a - b + c - d                                          ((a - b) + c) - d
98 Chapter 3 Selections
                                 TABLE 3.10       Operator Precedence Chart
                                 Precedence        Operator

                                                   var++ and var-- (Postfix)
                                                   +, - (Unary plus and minus), ++var and --var (Prefix)
                                                   (type) (Casting)
                                                   ! (Not)
                                                   *, /, % (Multiplication, division, and remainder)
                                                   +, - (Binary addition and subtraction)
                                                   <, <=, >, >= (Comparison)
                                                   ==, != (Equality)
                                                   ^ (Exclusive OR)
                                                   && (AND)
                                                   || (OR)
                                                   =, +=, – =, *=, /=, %= (Assignment operator)



                       Assignment operators are right associative. Therefore, the expression

                                                                  equivalent
                                    a = b += c = 5                                    a = (b += (c = 5))


                       Suppose a, b, and c are 1 before the assignment; after the whole expression is evaluated, a
                    becomes 6, b becomes 6, and c becomes 5. Note that left associativity for the assignment
                    operator would not make sense.

                          Note
                          Java has its own way to evaluate an expression internally. The result of a Java evaluation is the
                          same as that of its corresponding arithmetic evaluation. Interested readers may refer to Supple-
behind the scenes         ment III.B for more discussions on how an expression is evaluated in Java behind the scenes.


                    3.19 (GUI) Confirmation Dialogs
                    You have used showMessageDialog to display a message dialog box and
                    showInputDialog to display an input dialog box. Occasionally it is useful to answer a ques-
                    tion with a confirmation dialog box. A confirmation dialog can be created using the following
                    statement:


                                    int option =
                                       JOptionPane.showConfirmDialog
                                            (null, "Continue");



                       When a button is clicked, the method returns an option value. The value is
                    JOptionPane.YES_OPTION (0) for the Yes button, JOptionPane.NO_OPTION (1) for the No
                    button, and JOptionPane.CANCEL_OPTION (2) for the Cancel button.
                      You may rewrite the guess-birthday program in Listing 3.3 using confirmation dialog
                    boxes, as shown in Listing 3.10. Figure 3.6 shows a sample run of the program for the
                    day 19.
                                                                              3.19 (GUI) Confirmation Dialogs 99

              int option =
                 JOptionPane.showConfirmDialog
                     (null, "Continue");




              (a)                                 (b)                              (c)




               (d)                                 (e)                              (f)

FIGURE 3.6   Click Yes in (a), Yes in (b), No in (c), No in (d), and Yes in (e).



LISTING 3.10 GuessBirthdayUsingConfirmationDialog.java
 1 import javax.swing.JOptionPane;                                                           import class
 2
 3 public class GuessBirthdayUsingConfirmationDialog {
 4   public static void main(String[] args) {
 5     String set1 =                                                                         set1
 6       " 1 3 5 7\n" +
 7       " 9 11 13 15\n" +
 8       "17 19 21 23\n" +
 9       "25 27 29 31";
10
11     String set2 =                                                                         set2
12       " 2 3 6 7\n" +
13       "10 11 14 15\n" +
14       "18 19 22 23\n" +
15       "26 27 30 31";
16
17     String set3 =                                                                         set3
18       " 4 5 6 7\n" +
19       "12 13 14 15\n" +
20       "20 21 22 23\n" +
21       "28 29 30 31";
22
23     String set4 =                                                                         set4
24       " 8 9 10 11\n" +
25       "12 13 14 15\n" +
26       "24 25 26 27\n" +
27       "28 29 30 31";
28
29     String set5 =                                                                         set5
30       "16 17 18 19\n" +
31       "20 21 22 23\n" +
32       "24 25 26 27\n" +
33       "28 29 30 31";
34
100 Chapter 3 Selections
                      35       int day = 0;
                      36
                      37       // Prompt the user to answer questions
confirmation dialog   38       int answer = JOptionPane.showConfirmDialog(null,
                      39         "Is your birthday in these numbers?\n" + set1);
                      40
in set1?              41       if (answer == JOptionPane.YES_OPTION)
                      42         day += 1;
                      43
                      44       answer = JOptionPane.showConfirmDialog(null,
                      45         "Is your birthday in these numbers?\n" + set2);
                      46
in set2?              47       if (answer == JOptionPane.YES_OPTION)
                      48         day += 2;
                      49
                      50       answer = JOptionPane.showConfirmDialog(null,
                      51         "Is your birthday in these numbers?\n" + set3);
                      52
in set3?              53       if (answer == JOptionPane.YES_OPTION)
                      54         day += 4;
                      55
                      56       answer = JOptionPane.showConfirmDialog(null,
                      57         "Is your birthday in these numbers?\n" + set4);
                      58
in set4?              59       if (answer == JOptionPane.YES_OPTION)
                      60         day += 8;
                      61
                      62       answer = JOptionPane.showConfirmDialog(null,
                      63         "Is your birthday in these numbers?\n" + set5);
                      64
in set5?              65       if (answer == JOptionPane.YES_OPTION)
                      66         day += 16;
                      67
                      68       JOptionPane.showMessageDialog(null, "Your birthday is " +
                      69         day + "!");
                      70   }
                      71 }

                         The program displays confirmation dialog boxes to prompt the user to answer whether a
                      number is in Set1 (line 38), Set2 (line 44), Set3 (line 50), Set4 (line 56), and Set5 (line 62). If
                      the answer is Yes, the first number in the set is added to day (lines 42, 48, 54, 60, and 66).

                         KEY TERMS
                         Boolean expression 72                              fall-through behavior 94
                         Boolean value 72                                   operator associativity 97
                         boolean type 72                                    operator precedence 97
                         break statement 94                                 selection statement 74
                         conditional operator 90                            short-circuit evaluation 90
                         dangling-else ambiguity       82


                         CHAPTER SUMMARY
                         1. A boolean variable stores a true or false value.
                         2. The relational operators (<, <=, ==, !=, >, >=) work with numbers and characters, and
                             yield a Boolean value.
                                                                                               Review Questions 101

3. The Boolean operators &&, ||, !, and ^ operate with Boolean values and variables.
4. When evaluating p1 && p2, Java first evaluates p1 and then evaluates p2 if p1 is true;
      if p1 is false, it does not evaluate p2. When evaluating p1 ƒ ƒ p2, Java first evaluates
      p1 and then evaluates p2 if p1 is false; if p1 is true, it does not evaluate p2. There-
      fore, && is referred to as the conditional or short-circuit AND operator, and ƒ ƒ is
      referred to as the conditional or short-circuit OR operator.

5. Selection statements are used for programming with alternative courses. There are
      several types of selection statements: if statements, if ... else statements, nested
      if statements, switch statements, and conditional expressions.

6. The various if statements all make control decisions based on a Boolean expression.
      Based on the true or false evaluation of the expression, these statements take one
      of two possible courses.

7. The switch statement makes control decisions based on a switch expression of type
      char, byte, short, or int.

8. The keyword break is optional in a switch statement, but it is normally used at the
      end of each case in order to terminate the remainder of the switch statement. If the
      break statement is not present, the next case statement will be executed.


REVIEW QUESTIONS
Section 3.2
3.1      List six comparison operators.
3.2      Can the following conversions involving casting be allowed? If so, find the con-
         verted result.
         boolean b = true;
         i = (int)b;
         int i = 1;
         boolean b = (boolean)i;

Sections 3.3–3.11
3.3      What is the printout of the code in (a) and (b) if number is 30 and 35, respec-
         tively?


 if (number % 2 == 0)                                          if (number % 2 == 0)
      System.out.println(number + " is even.");                  System.out.println(number + " is even.");
                                                               else
      System.out.println(number + " is odd.");                   System.out.println(number + " is odd.");

                                   (a)                                                   (b)



3.4      Suppose x = 3 and y = 2; show the output, if any, of the following code. What is
         the output if x = 3 and y = 4? What is the output if x = 2 and y = 2? Draw a flow
         chart of the code:

         if (x > 2) {
           if (y > 2) {
102 Chapter 3 Selections
                                   z = x + y;
                                   System.out.println("z is " + z);
                               }
                             }
                             else
                               System.out.println("x is " + x);

                      3.5    Which of the following statements are equivalent? Which ones are correctly
                             indented?


              if (i > 0) if             if (i > 0) {             if (i > 0)                if (i > 0)
              (j > 0)                     if (j > 0)               if (j > 0)                if (j > 0)
              x = 0; else                    x = 0;                  x = 0;                    x = 0;
              if (k > 0) y = 0;           else if (k > 0)          else if (k > 0)           else if (k > 0)
              else z = 0;                    y = 0;                  y = 0;                     y = 0;
                                        }                          else                    else
                                        else                         z = 0;                  z = 0;
                                          z = 0;

                     (a)                        (b)                       (c)                       (d)



                      3.6    Suppose x = 2 and y = 3. Show the output, if any, of the following code. What is
                             the output if x = 3 and y = 2? What is the output if x = 3 and y = 3?
                             (Hint: Indent the statement correctly first.)

                             if (x > 2)
                               if (y > 2) {
                                  int z = x + y;
                                  System.out.println("z is " + z);
                               }
                             else
                               System.out.println("x is " + x);

                      3.7    Are the following two statements equivalent?


                                                                           if (income <= 10000)
                                   if (income <= 10000)
                                                                             tax = income * 0.1;
                                     tax = income * 0.1;
                                                                           else if (income > 10000 &&
                                   else if (income <= 20000)
                                                                                    income <= 20000)
                                     tax = 1000 +
                                                                             tax = 1000 +
                                       (income – 10000) * 0.15;
                                                                               (income – 10000) * 0.15;



                                  3.8      Which of the following is a possible output from invoking
                                           Math.random()?

                                                         323.4, 0.5, 34, 1.0, 0.0, 0.234

                                  3.9      How do you generate a random integer i such that 0 … i 6 20? How
                                           do you generate a random integer i such that 10 … i 6 20? How do
                                           you generate a random integer i such that 10 … i … 50?
                                  3.10     Write an if statement that assigns 1 to x if y is greater than 0.
                                  3.11     (a) Write an if statement that increases pay by 3% if score is greater
                                           than 90. (b) Write an if statement that increases pay by 3% if score
                                           is greater than 90, otherwise increases pay by 1%.
                                                                                        Review Questions 103

3.12 What is wrong in the following code?
        if (score >= 60.0)
          grade = 'D';
        else if (score >= 70.0)
          grade = 'C';
        else if (score >= 80.0)
          grade = 'B';
        else if (score >= 90.0)
          grade = 'A';
        else
          grade = 'F';

3.13 Rewrite the following statement using a Boolean expression:
        if (count % 10 == 0)
          newLine = true;
        else
          newLine = false;

Sections 3.12–3.14
3.14 Assuming that x is 1, show the result of the following Boolean expressions.
        (true) && (3 > 4)
        !(x > 0) && (x > 0)
        (x > 0) || (x < 0)
        (x != 0) || (x == 0)
        (x >= 0) || (x < 0)
        (x != 1) == !(x == 1)

3.15 Write a Boolean expression that evaluates to true if a number stored in variable
        num is between 1 and 100.
3.16 Write a Boolean expression that evaluates to true if a number stored in variable
        num is between 1 and 100 or the number is negative.
3.17 Assume that x and y are int type. Which of the following are legal Java expres-
        sions?
        x > y > 0
        x = y && y
        x /= y
        x or y
        x and y
        (x != 0) || (x = 0)

3.18 Suppose that x is 1. What is x after the evaluation of the following expression?
        (x >= 1) && (x++ > 1)
        (x > 1) && (x++ > 1)

3.19 What is the value of the expression ch >= 'A' && ch <= 'Z' if ch is 'A', 'p',
        'E', or '5'?
3.20 Suppose, when you run the program, you enter input 2 3 6 from the console. What
        is the output?

        public class Test {
          public static void main(String[] args) {
            java.util.Scanner input = new java.util.Scanner(System.in);
            double x = input.nextDouble();
104 Chapter 3 Selections
                                    double y = input.nextDouble();
                                    double z = input.nextDouble();

                                    System.out.println("(x < y &&     y < z) is " + (x < y && y < z));
                                    System.out.println("(x < y ||     y < z) is " + (x < y || y < z));
                                    System.out.println("!(x < y)      is " + !(x < y));
                                    System.out.println("(x + y <      z) is " + (x + y < z));
                                    System.out.println("(x + y <      z) is " + (x + y < z));
                                }
                            }

                     3.21 Write a Boolean expression that evaluates true if age is greater than 13 and less
                            than 18.
                     3.22 Write a Boolean expression that evaluates true if weight is greater than 50 or
                            height is greater than 160.
                     3.23   Write a Boolean expression that evaluates true if weight is greater than 50 and
                            height is greater than 160.
                     3.24   Write a Boolean expression that evaluates true if either weight is greater than
                            50 or height is greater than 160, but not both.

                     Section 3.15
                     3.25 What data types are required for a switch variable? If the keyword break is not
                            used after a case is processed, what is the next statement to be executed? Can you
                            convert a switch statement to an equivalent if statement, or vice versa? What are
                            the advantages of using a switch statement?
                     3.26   What is y after the following switch statement is executed?
                            x = 3; y = 3;
                            switch (x + 3) {
                              case 6: y = 1;
                              default: y += 1;
                            }

                     3.27 Use a switch statement to rewrite the following if statement and draw the flow
                            chart for the switch statement:
                            if (a == 1)
                              x += 5;
                            else if (a == 2)
                              x += 10;
                            else if (a == 3)
                              x += 16;
                            else if (a == 4)
                              x += 34;

                     3.28 Write a switch statement that assigns a String variable dayName with Sunday,
                            Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, if day is 0, 1, 2, 3, 4,
                            5, 6, accordingly.

                     Section 3.16
                     3.29 Rewrite the following if statement using the conditional operator:
                            if (count % 10 == 0)
                              System.out.print(count + "\n");
                            else
                              System.out.print(count + " ");
                                                                                              Programming Exercises 105

3.30 Rewrite the following statement using a conditional expression:
         if (temperature > 90)
           pay = pay * 1.5;
         else
           pay = pay * 1.1;


Section 3.17
3.31 What are the specifiers for outputting a Boolean value, a character, a decimal inte-
         ger, a floating-point number, and a string?
3.32     What is wrong in the following statements?

         (a) System.out.printf("%5d %d", 1, 2, 3);
         (b) System.out.printf("%5d %f", 1);
         (c) System.out.printf("%5d %f", 1, 2);

3.33 Show the output of the following statements.
         (a)   System.out.printf("amount is %f %e\n", 32.32, 32.32);
         (b)   System.out.printf("amount is %5.4f %5.4e\n", 32.32, 32.32);
         (c)   System.out.printf("%6b\n", (1 > 2));
         (d)   System.out.printf("%6s\n", "Java");
         (e)   System.out.printf("%-6b%s\n", (1 > 2), "Java");
         (f)   System.out.printf("%6b%-s\n", (1 > 2), "Java");

3.34 How do you create a formatted string?

Section 3.18
3.35 List the precedence order of the Boolean operators. Evaluate the following expres-
         sions:
         true || true && false
         true && true || false

3.36 True or false? All the binary operators except = are left associative.
3.37 Evaluate the following expressions:
         2 * 2 - 3 > 2 && 4 - 2 > 5
         2 * 2 - 3 > 2 || 4 - 2 > 5

3.38 Is (x > 0    && x < 10) the same as ((x > 0) && (x < 10))? Is (x > 0 || x < 10)
         the same as ((x > 0) || (x < 10))? Is (x > 0 || x < 10 && y < 0) the same as
         (x > 0 || (x < 10 && y < 0))?

Section 3.19
3.39 How do you display a confirmation dialog? What value is returned when invoking
         JOptionPane.showConfirmDialog?


PROGRAMMING EXERCISES

       Pedagogical Note
       For each exercise, students should carefully analyze the problem requirements and design
       strategies for solving the problem before coding.                                            think before coding
106 Chapter 3 Selections

                                     Pedagogical Note
document analysis and design         Instructors may ask students to document analysis and design for selected exercises. Students
                                     should use their own words to analyze the problem, including the input, output, and what
                                     needs to be computed, and describe how to solve the problem in pseudocode.


                                     Debugging Tip
                                     Before you ask for help, read and explain the program to yourself, and trace it using several
                                     representative inputs by hand or using an IDE debugger. You learn how to program by debug-
learn from mistakes                  ging your own mistakes.

                               Section 3.2
                               3.1* (Algebra: solving quadratic equations) The two roots of a quadratic equation
                                       ax2 + bx + c = 0 can be obtained using the following formula:

                                                            -b + 2b2 - 4ac          -b - 2b2 - 4ac
                                                     r1 =                  and r2 =
                                                                 2a                      2a

                                       b2 - 4ac is called the discriminant of the quadratic equation. If it is positive, the
                                       equation has two real roots. If it is zero, the equation has one root. If it is negative,
                                       the equation has no real roots.
                                       Write a program that prompts the user to enter values for a, b, and c and displays
                                       the result based on the discriminant. If the discriminant is positive, display two
                                       roots. If the discriminant is 0, display one root. Otherwise, display “The equation
                                       has no real roots”.
                                       Note you can use Math.pow(x, 0.5) to compute 1x. Here are some sample
                                       runs.


                                       Enter a, b, c: 1.0 3 1
                                       The roots are -0.381966 and -2.61803



                                       Enter a, b, c: 1 2.0 1
                                       The root is -1



                                       Enter a, b, c: 1 2 3
                                       The equation has no real roots


                               3.2     (Checking whether a number is even) Write a program that reads an integer and
                                       checks whether it is even. Here are the sample runs of this program:


                                       Enter an integer: 25
                                       Is 25 an even number? false



                                       Enter an integer: 2000
                                       Is 2000 an even number? true
                                                                                       Programming Exercises 107
Sections 3.3–3.8
3.3* (Algebra: solving 2 * 2 linear equations) You can use Cramer’s rule to solve the
        following 2 * 2 system of linear equation:

                       ax + by = e               ed - bf     af - ec
                                           x =           y =
                       cx + dy = f               ad - bc     ad - bc

        Write a program that prompts the user to enter a, b, c, d, e, and f and display the
        result. If ad - bc is 0, report that “The equation has no solution”.


        Enter a, b, c, d, e, f: 9.0 4.0 3.0 -5.0 -6.0 -21.0
        x is -2.0 and y is 3.0




        Enter a, b, c, d, e, f: 1.0 2.0 2.0 4.0 4.0 5.0
        The equation has no solution



3.4** (Game: learning addition) Write a program that generates two integers under 100 and
        prompts the user to enter the sum of these two integers. The program then reports true
        if the answer is correct, false otherwise. The program is similar to Listing 3.1.
3.5**   (Game: addition for three numbers) The program in Listing 3.1 generates two
        integers and prompts the user to enter the sum of these two integers. Revise the
        program to generate three single-digit integers and prompt the user to enter the
        sum of these three integers.
3.6*    (Health application: BMI) Revise Listing 3.5, ComputeBMI.java, to let the user
        enter weight, feet, and inches. For example, if a person is 5 feet and 10 inches, you
        will enter 5 for feet and 10 for inches.
3.7     (Financial application: monetary units) Modify Listing 2.10, ComputeChange.java,
        to display the nonzero denominations only, using singular words for single units
        such as 1 dollar and 1 penny, and plural words for more than one unit such as 2 dol-
        lars and 3 pennies. (Use input 23.67 to test your program.)                              Video Note
3.8*    (Sorting three integers) Write a program that sorts three integers. The integers are     Sort three integers
        entered from the input dialogs and stored in variables num1, num2, and num3,
        respectively. The program sorts the numbers so that num1 … num2 … num3.
3.9     (Business: checking ISBN) An ISBN (International Standard Book Number) con-
        sists of 10 digits d1d2d3d4d5d6d7d8d9d10 . The last digit d10 is a checksum, which
        is calculated from the other nine digits using the following formula:

               1d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 +
                    d6 * 6 + d7 * 7 + d8 * 8 + d9 * 92 % 11

        If the checksum is 10, the last digit is denoted X according to the ISBN convention.
        Write a program that prompts the user to enter the first 9 digits and displays the 10-
        digit ISBN (including leading zeros). Your program should read the input as an inte-
        ger. For example, if you enter 013601267, the program should display 0136012671.
3.10* (Game: addition quiz) Listing 3.4, SubtractionQuiz.java, randomly generates a
        subtraction question. Revise the program to randomly generate an addition ques-
        tion with two integers less than 100.
108 Chapter 3 Selections
                     Sections 3.9–3.19
                     3.11*   (Finding the number of days in a month) Write a program that prompts the user
                             to enter the month and year and displays the number of days in the month. For
                             example, if the user entered month 2 and year 2000, the program should display
                             that February 2000 has 29 days. If the user entered month 3 and year 2005, the
                             program should display that March 2005 has 31 days.
                     3.12    (Checking a number) Write a program that prompts the user to enter an integer
                             and checks whether the number is divisible by both 5 and 6, or neither of them,
                             or just one of them. Here are some sample runs for inputs 10, 30, and 23.

                             10 is divisible by 5 or 6, but not both
                             30 is divisible by both 5 and 6
                             23 is not divisible by either 5 or 6

                     3.13    (Financial application: computing taxes) Listing 3.6, ComputeTax.java, gives
                             the source code to compute taxes for single filers. Complete Listing 3.6 to give
                             the complete source code.
                     3.14    (Game: head or tail) Write a program that lets the user guess the head or tail of
                             a coin. The program randomly generates an integer 0 or 1, which represents
                             head or tail. The program prompts the user to enter a guess and reports whether
                             the guess is correct or incorrect.
                     3.15*   (Game: lottery) Revise Listing 3.9, Lottery.java, to generate a lottery of a three-
                             digit number. The program prompts the user to enter a three-digit number and
                             determines whether the user wins according to the following rule:
                             1. If the user input matches the lottery in exact order, the award is $10,000.
                             2. If all the digits in the user input match all the digits in the lottery, the award is
                                $3,000.
                             3. If one digit in the user input matches a digit in the lottery, the award is
                                $1,000.
                     3.16    (Random character) Write a program that displays a random uppercase letter
                             using the Math.random() method.
                     3.17*   (Game: scissor, rock, paper) Write a program that plays the popular scissor-
                             rock-paper game. (A scissor can cut a paper, a rock can knock a scissor, and a
                             paper can wrap a rock.) The program randomly generates a number 0, 1, or 2
                             representing scissor, rock, and paper. The program prompts the user to enter a
                             number 0, 1, or 2 and displays a message indicating whether the user or the
                             computer wins, loses, or draws. Here are sample runs:


                              scissor (0), rock (1), paper (2): 1
                              The computer is scissor. You are rock. You won



                              scissor (0), rock (1), paper (2): 2
                              The computer is paper. You are paper too. It is a draw


                     3.18*   (Using the input dialog box) Rewrite Listing 3.8, LeapYear.java, using the input
                             dialog box.
                     3.19    (Validating triangles) Write a program that reads three edges for a triangle and
                             determines whether the input is valid. The input is valid if the sum of any two
                             edges is greater than the third edge. Here are the sample runs of this program:
                                                                                     Programming Exercises 109

        Enter three edges: 1 2.5 1
        Can edges 1, 2.5, and 1 form a triangle? false



        Enter three edges: 2.5 2 1
        Can edges 2.5, 2, and 1 form a triangle? true



3.20* (Science: wind-chill temperature) Exercise 2.17 gives a formula to compute the
        wind-chill temperature. The formula is valid for temperature in the range between
        -58°F and 41°F and wind speed greater than or equal to 2. Write a program that
        prompts the user to enter a temperature and a wind speed. The program displays
        the wind-chill temperature if the input is valid, otherwise displays a message indi-
        cating whether the temperature and/or wind speed is invalid.

Comprehensives
3.21** (Science: day of the week) Zeller’s congruence is an algorithm developed by
        Christian Zeller to calculate the day of the week. The formula is

                              261m + 12             k     j
                h = aq + j                 k + k + j k + j k + 5jb % 7
                                   10               4     4

        where
        ■ h   is the day of the week (0: Saturday, 1: Sunday, 2: Monday, 3: Tuesday, 4:
            Wednesday, 5: Thursday, 6: Friday).
        ■   q is the day of the month.
        ■   m is the month (3: March, 4: April, Á , 12: December). January and February
            are counted as months 13 and 14 of the previous year.
                                      year
        ■   j is the century (i.e., j      k ).
                                      100
        ■   k is the year of the century (i.e., year % 7).
        Write a program that prompts the user to enter a year, month, and day of the
        month, and displays the name of the day of the week. Here are some sample runs:


        Enter year: (e.g., 2008): 2002
        Enter month: 1-12: 3
        Enter the day of the month: 1-31: 26
        Day of the week is Tuesday




        Enter year: (e.g., 2008): 2011
        Enter month: 1-12: 5
        Enter the day of the month: 1-31: 2
        Day of the week is Thursday



        (Hint: :n; = 1int2n for a positive n. January and February are counted as 13 and
        14 in the formula. So you need to convert the user input 1 to 13 and 2 to 14 for
        the month and change the year to the previous year.)
110 Chapter 3 Selections

                     3.22** (Geometry: point in a circle?) Write a program that prompts the user to enter a
                                 point (x, y) and checks whether the point is within the circle centered at (0, 0)
                                 with radius 10. For example, (4, 5) is inside the circle and (9, 9) is outside the cir-
                                 cle, as shown in Figure 3.7(a).
                                (Hint: A point is in the circle if its distance to (0, 0) is less than or equal to 10. The
                                formula for computing the distance is 21x2 - x122 + 1y2 - y122.) Two sample
                                runs are shown below.)

                                      y-axis                                       y-axis
                                                              (9, 9)
                                                     (4, 5)                                                (6, 4)
                                                                                                 (2, 2)

                                                 (0, 0)                x-axis               (0, 0)          x-axis




                                               (a)                                       (b)

                   FIGURE 3.7    (a) Points inside and outside of the circle; (b) Points inside and outside of the
                   rectangle.


                                Enter a point with two coordinates: 4 5
                                Point (4.0, 5.0) is in the circle



                                Enter a point with two coordinates: 9 9
                                Point (9.0, 9.0) is not in the circle


                     3.23** (Geometry: point in a rectangle?) Write a program that prompts the user to enter a
                                point (x, y) and checks whether the point is within the rectangle centered at (0, 0)
                                with width 10 and height 5. For example, (2, 2) is inside the rectangle and (6, 4) is
                                outside the circle, as shown in Figure 3.7(b).
                                (Hint: A point is in the rectangle if its horizontal distance to (0, 0) is less than or
                                equal to 10 / 2 and its vertical distance to (0, 0) is less than or equal to 5 / 2.] Here
                                are two sample runs. Two sample runs are shown below.)


                                Enter a point with two coordinates: 2 2
                                Point (2.0, 2.0) is in the rectangle



                                 Enter a point with two coordinates: 6 4
                                 Point (6.0, 4.0) is not in the rectangle


                     3.24** (Game: picking a card) Write a program that simulates picking a card from a
                                deck of 52 cards. Your program should display the rank (Ace, 2, 3, 4, 5, 6, 7, 8,
                                9, 10, Jack, Queen, King) and suit (Clubs, Diamonds, Hearts, Spades) of
                                the card. Here is a sample run of the program:
                                                                                                 Programming Exercises 111

             The card you picked is Jack of Hearts


  3.25** (Computing the perimeter of a triangle) Write a program that reads three edges
             for a triangle and computes the perimeter if the input is valid. Otherwise, display
             that the input is invalid. The input is valid if the sum of any two edges is greater
             than the third edge.
  3.26       (Using the &&, || and ^ operators) Write a program that prompts the user to enter
             an integer and determines whether it is divisible by 5 and 6, whether it is divisible
             by 5 or 6, and whether it is divisible by 5 or 6, but not both. Here is a sample run
             of this program:


             Enter   an integer: 10
             Is 10   divisible by 5 and 6? false
             Is 10   divisible by 5 or 6? true
             Is 10   divisible by 5 or 6, but not both? true


  3.27** (Geometry: points in triangle?) Suppose a right triangle is placed in a plane as
             shown below. The right-angle point is placed at (0, 0), and the other two points
             are placed at (200, 0), and (0, 100). Write a program that prompts the user to enter
             a point with x- and y-coordinates and determines whether the point is inside the
             triangle. Here are the sample runs:


                                         (0, 100)
                                                            p2

                                            p1

                                         (0, 0)          (200, 0)


             Enter a point’s x- and y-coordinates: 100.5 25.5
             The point is in the triangle



             Enter a point’s x- and y-coordinates: 100.5 50.5
             The point is not in the triangle


  3.28** (Geometry: two rectangles) Write a program that prompts the user to enter the
             center x-, y-coordinates, width, and height of two rectangles and determines
             whether the second rectangle is inside the first or overlaps with the first, as shown
             in Figure 3.8.

                            w1                                      w1

                   w2
                                                                                        w2
       h1 h2                  (x1, y1)              h1                (x1, y1)
                 (x2, y2)                                                        h2
                                                                                      (x2, y2)

                            (a)                                     (b)

FIGURE 3.8    (a) A rectangle is inside another one. (b) A rectangle overlaps another one.
112 Chapter 3 Selections
                                Here are the sample runs:


                                Enter   r1’s center x-, y-coordinates, width, and height:
                                  2.5   4 2.5 43
                                Enter   r2’s center x-, y-coordinates, width, and height:
                                  1.5   5 0.5 3
                                r2 is   inside r1



                                Enter r1’s center x-, y-coordinates, width, and height:
                                  1 2 3 5.5
                                Enter r2’s center x-, y-coordinates, width, and height:
                                  3 4 4.5 5
                                r2 overlaps r1



                                Enter r1’s center x-, y-coordinates, width, and height:
                                  1 2 3 3
                                Enter r2’s center x-, y-coordinates, width, and height:
                                  40 45 3 2
                                r2 does not overlap r1


                     3.29** (Geometry: two circles) Write a program that prompts the user to enter the center
                                coordinates and radii of two circles and determines whether the second circle is
                                inside the first or overlaps with the first, as shown in Figure 3.9.
                                (Hint: circle2 is inside circle1 if the distance between the two centers 6 = |r1 - r2|
                                and circle2 overlaps circle1 if the distance between the two centers 6 = r1 + r2.)



                                               r1                              r1

                                                    (x1, y1)                        (x1, y1)
                                          r2                                                      r2
                                        (x2, y2)
                                                                                               (x2, y2)


                                                (a)                             (b)

                   FIGURE 3.9   (a) A circle is inside another circle. (b) A circle overlaps another circle.

                                Here are the sample runs:


                                Enter circle1’s center x-, y-coordinates, and radius:
                                  0.5 5.1 13
                                Enter circle2’s center x-, y-coordinates, and radius:
                                  1 1.7 4.5
                                circle2 is inside circle1
                                                         Programming Exercises 113

Enter circle1’s center x-, y-coordinates, and radius:
  3.4 5.7 5.5
Enter circle2’s center x-, y-coordinates, and radius:
  6.7 3.5 3
circle2 overlaps circle1



 Enter circle1’s center x-, y-coordinates, and radius:
   3.4 5.5 1
 Enter circle2’s center x-, y-coordinates, and radius:
   5.5 7.2 1
 circle2 does not overlap circle1
This page intentionally left blank
                                                            CHAPTER 4
LOOPS
Objectives
■   To write programs for executing statements repeatedly using a while loop (§4.2).
■   To develop a program for GuessNumber (§4.2.1).
■   To follow the loop design strategy to develop loops (§4.2.2).
■   To develop a program for SubtractionQuizLoop (§4.2.3).
■   To control a loop with a sentinel value (§4.2.4).
■   To obtain large input from a file using input redirection
    rather than typing from the keyboard (§4.2.4).
■   To write loops using do-while statements (§4.3).
■   To write loops using for statements (§4.4).
■   To discover the similarities and differences of three
    types of loop statements (§4.5).
■   To write nested loops (§4.6).
■   To learn the techniques for minimizing numerical errors (§4.7).
■   To learn loops from a variety of examples (GCD,
    FutureTuition, MonteCarloSimulation) (§4.8).

■   To implement program control with break
    and continue (§4.9).
■   (GUI) To control a loop with a confirmation
    dialog (§4.10).
116 Chapter 4 Loops

                  4.1 Introduction
                  Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It
                  would be tedious to have to write the following statement a hundred times:

                                System.out.println("Welcome to Java!");
                  100 times     System.out.println("Welcome to Java!");
                                ...
                                System.out.println("Welcome to Java!");

problem           So, how do you solve this problem?
why loop?             Java provides a powerful construct called a loop that controls how many times an operation
                  or a sequence of operations is performed in succession. Using a loop statement, you simply
                  tell the computer to print a string a hundred times without having to code the print statement
                  a hundred times, as follows:

                      int count = 0;
                      while (count < 100) {
                        System.out.println("Welcome to Java!");
                        count++;
                      }

                  The variable count is initially 0. The loop checks whether (count < 100) is true. If so, it
                  executes the loop body to print the message "Welcome to Java!" and increments count by
                  1. It repeatedly executes the loop body until (count < 100) becomes false. When (count <
                  100) is false (i.e., when count reaches 100), the loop terminates and the next statement
                  after the loop statement is executed.
                      Loops are constructs that control repeated executions of a block of statements. The concept
                  of looping is fundamental to programming. Java provides three types of loop statements:
                  while loops, do-while loops, and for loops.


                  4.2 The while Loop
                  The syntax for the while loop is as follows:

while loop            while (loop-continuation-condition) {
                        // Loop body
                        Statement(s);
                      }

                  Figure 4.1(a) shows the while-loop flow chart. The part of the loop that contains the statements
loop body         to be repeated is called the loop body. A one-time execution of a loop body is referred to as an
iteration         iteration of the loop. Each loop contains a loop-continuation-condition, a Boolean expression that
                  controls the execution of the body. It is evaluated each time to determine if the loop body is exe-
                  cuted. If its evaluation is true, the loop body is executed; if its evaluation is false, the entire
                  loop terminates and the program control turns to the statement that follows the while loop.
                      The loop for printing Welcome to Java! a hundred times introduced in the preceding
                  section is an example of a while loop. Its flow chart is shown in Figure 4.1(b). The
                  loop-continuation-condition is (count < 100) and loop body contains two state-
                  ments as shown below:                     loop-continuation-condition

                      int count = 0;
                      while (count < 100) {
                        System.out.println("Welcome to Java!");                  loop body
                        count++;
                      }
                                                                                                         4.2 The while Loop 117

                                                                     count = 0;




              loop-
           continuation        false                                                        false
                                                                   (count < 100)?
            condition?


             true                                                      true

           Statement(s)                          System.out.println("Welcome to Java!");
           (loop body)                           count++;




                (a)                                                        (b)

FIGURE 4.1 The while loop repeatedly executes the statements in the loop body when the
loop-continuation-condition evaluates to true.

In this example, you know exactly how many times the loop body needs to be executed. So a
control variable count is used to count the number of executions. This type of loop is known
as a counter-controlled loop.                                                                                 counter-controlled loop

     Note
      The loop-continuation-condition must always appear inside the parentheses. The
      braces enclosing the loop body can be omitted only if the loop body contains one or no
      statement.

Here is another example to help understand how a loop works.
   int sum = 0, i = 1;
   while (i < 10) {
     sum = sum + i;
     i++;
   }
   System.out.println("sum is " + sum); // sum is 45

If i < 10 is true, the program adds i to sum. Variable i is initially set to 1, then incremented
to 2, 3, and up to 10. When i is 10, i < 10 is false, the loop exits. So, the sum is 1 + 2 + 3
+ ... + 9 = 45.
    What happens if the loop is mistakenly written as follows:
   int sum = 0, i = 1;
   while (i < 10) {
     sum = sum + i;
   }

This loop is infinite, because i is always 1 and i < 10 will always be true.

     Caution
      Make sure that the loop-continuation-condition eventually becomes false so that
      the program will terminate. A common programming error involves infinite loops. That is, the            infinite loop
      program cannot terminate because of a mistake in the loop-continuation-condition.
         Programmers often make mistakes to execute a loop one more or less time. This is commonly
      known as the off-by-one error. For example, the following loop displays Welcome to Java 101             off-by-one error
      times rather than 100 times. The error lies in the condition, which should be count < 100 rather
      than count <= 100.
118 Chapter 4 Loops
                            int count = 0;
                            while (count <= 100) {
                              System.out.println("Welcome to Java!");
                              count++;
                            }


                      4.2.1 Problem: Guessing Numbers
                      The problem is to guess what a number a computer has in mind. You will write a program that
                      randomly generates an integer between 0 and 100, inclusive. The program prompts the user to
Video Note
                      enter a number continuously until the number matches the randomly generated number. For
Guess a number
                      each user input, the program tells the user whether the input is too low or too high, so the user
                      can make the next guess intelligently. Here is a sample run:

                          Guess a magic number between 0 and 100
                          Enter your guess: 50
                          Your guess is too high
                          Enter your guess: 25
                          Your guess is too high
                          Enter your guess: 12
                          Your guess is too high
                          Enter your guess: 6
                          Your guess is too low
                          Enter your guess: 9
                          Yes, the number is 9


intelligent guess     The magic number is between 0 and 100. To minimize the number of guesses, enter 50 first.
                      If your guess is too high, the magic number is between 0 and 49. If your guess is too low, the
                      magic number is between 51 and 100. So, you can eliminate half of the numbers from further
                      consideration after one guess.
                          How do you write this program? Do you immediately begin coding? No. It is important to
think before coding   think before coding. Think how you would solve the problem without writing a program. You
                      need first to generate a random number between 0 and 100, inclusive, then to prompt the user
                      to enter a guess, and then to compare the guess with the random number.
code incrementally        It is a good practice to code incrementally one step at a time. For programs involving loops,
                      if you don’t know how to write a loop right away, you may first write the code for executing
                      the loop one time, and then figure out how to repeatedly execute the code in a loop. For this
                      program, you may create an initial draft, as shown in Listing 4.1:

                      LISTING 4.1 GuessNumberOneTime.java
                       1 import java.util.Scanner;
                       2
                       3 public class GuessNumberOneTime {
                       4   public static void main(String[] args) {
                       5     // Generate a random number to be guessed
generate a number      6     int number = (int)(Math.random() * 101);
                       7
                       8     Scanner input = new Scanner(System.in);
                       9     System.out.println("Guess a magic number between 0 and 100");
                      10
                      11     // Prompt the user to guess the number
                      12     System.out.print("\nEnter your guess: ");
enter a guess         13     int guess = input.nextInt();
                                                                                     4.2 The while Loop 119
14
15     if (guess == number)
16       System.out.println("Yes, the number is " + number);                                 correct guess?
17     else if (guess > number)
18       System.out.println("Your guess is too high");                                       too high?
19     else
20       System.out.println("Your guess is too low");                                        too low?
21   }
22 }

When you run this program, it prompts the user to enter a guess only once. To let the user
enter a guess repeatedly, you may put the code in lines 11–20 in a loop as follows:

  while (true) {
    // Prompt the user to guess the number
    System.out.print("\nEnter your guess: ");
    guess = input.nextInt();

    if (guess == number)
      System.out.println("Yes, the number is " + number);
    else if (guess > number)
      System.out.println("Your guess is too high");
    else
      System.out.println("Your guess is too low");
  } // End of loop

This loop repeatedly prompts the user to enter a guess. However, this loop is not correct,
because it never terminates. When guess matches number, the loop should end. So, the loop
can be revised as follows:

  while (guess != number) {
    // Prompt the user to guess the number
    System.out.print("\nEnter your guess: ");
    guess = input.nextInt();

    if (guess == number)
      System.out.println("Yes, the number is " + number);
    else if (guess > number)
      System.out.println("Your guess is too high");
    else
      System.out.println("Your guess is too low");
  } // End of loop

The complete code is given in Listing 4.2.

LISTING 4.2 GuessNumber.java
 1 import java.util.Scanner;
 2
 3 public class GuessNumber {
 4   public static void main(String[] args) {
 5     // Generate a random number to be guessed
 6     int number = (int)(Math.random() * 101);                                              generate a number
 7
 8     Scanner input = new Scanner(System.in);
 9     System.out.println("Guess a magic number between 0 and 100");
10
11     int guess = -1;
12     while (guess != number) {
120 Chapter 4 Loops
enter a guess     13            // Prompt the user to guess the number
                  14            System.out.print("\nEnter your guess: ");
                  15            guess = input.nextInt();
                  16
                  17            if (guess == number)
                  18              System.out.println("Yes, the number is " + number);
                  19            else if (guess > number)
too high?         20              System.out.println("Your guess is too high");
                  21            else
too low?          22              System.out.println("Your guess is too low");
                  23     }      // End of loop
                  24   }
                  25 }



                                      line#   number               guess                output
                                     6        8
                                    11                              -1
                                    15                             50
                      iteration 1 b
                                    20                                                  Your guess is too high
                                      15                           25
                      iteration 2 b
                                      20                                                Your guess is too high
                                      15                           12
                      iteration 3 b
                                      20                                                Your guess is too high
                                      15                            6
                      iteration 4 b
                                      22                                                Your guess is too low
                                      15                            9
                      iteration 5 b
                                      20                                                Yes, the number is 9



                  The program generates the magic number in line 6 and prompts the user to enter a guess con-
                  tinuously in a loop (lines 12–23). For each guess, the program checks whether the guess is
                  correct, too high, or too low (lines 17–22). When the guess is correct, the program exits the
                  loop (line 12). Note that guess is initialized to -1. Initializing it to a value between 0 and 100
                  would be wrong, because that could be the number to be guessed.

                  4.2.2       Loop Design Strategies
                  Writing a correct loop is not an easy task for novice programmers. Consider three steps when
                  writing a loop.
                       Step 1: Identify the statements that need to be repeated.
                       Step 2: Wrap these statements in a loop like this:

                       while (true) {
                         Statements;
                       }

                       Step 3: Code the loop-continuation-condition and add appropriate statements for control-
                       ling the loop.
                                                                                        4.2 The while Loop 121
   while (loop-continuation-condition) {
     Statements;
     Additional statements for controlling the loop;
   }


4.2.3 Problem: An Advanced Math Learning Tool
The Math subtraction learning tool program in Listing 3.4, SubtractionQuiz.java, generates
just one question for each run. You can use a loop to generate questions repeatedly. How do
                                                                                                 Video Note
you write the code to generate five questions? Follow the loop design strategy. First identify
                                                                                                 Multiple subtraction quiz
the statements that need to be repeated. These are the statements for obtaining two random
numbers, prompting the user with a subtraction question, and grading the question. Second,
wrap the statements in a loop. Third, add a loop control variable and the loop-continuation-
condition to execute the loop five times.
   Listing 4.3 gives a program that generates five questions and, after a student answers all
five, reports the number of correct answers. The program also displays the time spent on the
test and lists all the questions.


LISTING 4.3 SubtractionQuizLoop.java
 1 import java.util.Scanner;
 2
 3 public class SubtractionQuizLoop {
 4   public static void main(String[] args) {
 5     final int NUMBER_OF_QUESTIONS = 5; // Number of questions
 6     int correctCount = 0; // Count the number of correct answers
 7     int count = 0; // Count the number of questions
 8     long startTime = System.currentTimeMillis();                                              get start time
 9     String output = ""; // output string is initially empty
10     Scanner input = new Scanner(System.in);
11
12     while (count < NUMBER_OF_QUESTIONS) {                                                     loop
13       // 1. Generate two random single-digit integers
14       int number1 = (int)(Math.random() * 10);
15       int number2 = (int)(Math.random() * 10);
16
17       // 2. If number1 < number2, swap number1 with number2
18       if (number1 < number2) {
19         int temp = number1;
20         number1 = number2;
21         number2 = temp;
22       }
23
24       // 3. Prompt the student to answer "What is number1 – number2?"
25       System.out.print(                                                                       display a question
26         "What is " + number1 + " - " + number2 + "? ");
27       int answer = input.nextInt();
28
29       // 4. Grade the answer and display the result
30       if (number1 - number2 == answer) {                                                      grade an answer
31         System.out.println("You are correct!");
32         correctCount++;                                                                       increase correct count
33       }
34       else
35         System.out.println("Your answer is wrong.\n" + number1
36            + " - " + number2 + " should be " + (number1 - number2));
37
122 Chapter 4 Loops
                            38           // Increase the count
increase control variable   39           count++;
                            40
prepare output              41           output += "\n" + number1 + "-" + number2 + "=" + answer +
                            42             ((number1 - number2 == answer) ? " correct" : " wrong");
end loop                    43       }
                            44
get end time                45       long endTime = System.currentTimeMillis();
test time                   46       long testTime = endTime - startTime;
                            47
display result              48       System.out.println("Correct count is " + correctCount +
                            49         "\nTest time is " + testTime / 1000 + " seconds\n" + output);
                            50   }
                            51 }



                                What is 9 – 2? 7
                                You are correct!
                                What is 3 – 0? 3
                                You are correct!
                                What is 3 – 2? 1
                                You are correct!
                                What is 7 – 4? 4
                                Your answer is wrong.
                                7 – 4 should be 3
                                What is 7 – 5? 4
                                Your answer is wrong.
                                7 – 5 should be 2
                                Correct count is 3
                                Test time is 1021 seconds
                                9–2=7     correct
                                3–0=3     correct
                                3–2=1     correct
                                7–4=4     wrong
                                7–5=4     wrong



                            The program uses the control variable count to control the execution of the loop. count is
                            initially 0 (line 7) and is increased by 1 in each iteration (line 39). A subtraction question is
                            displayed and processed in each iteration. The program obtains the time before the test starts
                            in line 8 and the time after the test ends in line 45, and computes the test time in line 46. The
                            test time is in milliseconds and is converted to seconds in line 49.

                            4.2.4        Controlling a Loop with a Sentinel Value
                            Another common technique for controlling a loop is to designate a special value when read-
sentinel value              ing and processing a set of values. This special input value, known as a sentinel value, signi-
                            fies the end of the loop. A loop that uses a sentinel value to control its execution is called a
                            sentinel-controlled loop.
                               Listing 4.4 writes a program that reads and calculates the sum of an unspecified number of
                            integers. The input 0 signifies the end of the input. Do you need to declare a new variable for
                            each input value? No. Just use one variable named data (line 12) to store the input value and
                            use a variable named sum (line 15) to store the total. Whenever a value is read, assign it to
                            data and, if it is not zero, add it to sum (line 17).
                                                                                             4.2 The while Loop 123

LISTING 4.4 SentinelValue.java
 1 import java.util.Scanner;
 2
 3 public class SentinelValue {
 4   /** Main method */
 5   public static void main(String[] args) {
 6     // Create a Scanner
 7     Scanner input = new Scanner(System.in);
 8
 9     // Read an initial data
10     System.out.print(
11       "Enter an int value (the program exits if the input is 0): ");
12     int data = input.nextInt();                                                                    input
13
14     // Keep reading data until the input is 0
15     int sum = 0;
16     while (data != 0) {                                                                            loop
17       sum += data;
18
19       // Read the next data
20       System.out.print(
21         "Enter an int value (the program exits if the input is 0): ");
22       data = input.nextInt();
23     }                                                                                              end of loop
24
25     System.out.println("The sum is " + sum);                                                       display result
26   }
27 }



    Enter an int value (the program exits if the input is 0): 2
    Enter an int value (the program exits if the input is 0): 3
    Enter an int value (the program exits if the input is 0): 4
    Enter an int value (the program exits if the input is 0): 0
    The sum is 9



                  line#      data                  sum                    output
                  12         2
                  15                               0
                  17                               2
  iteration 1 b
                  22         3
                  17                               5
  iteration 2 b
                  22         4
                  17                               9
  iteration 3 b
                  22         0
                  25                                                      The sum is 9

If data is not 0, it is added to sum (line 17) and the next item of input data is read (lines
20–22). If data is 0, the loop body is no longer executed and the while loop terminates. The
input value 0 is the sentinel value for this loop. Note that if the first input read is 0, the loop
body never executes, and the resulting sum is 0.
124 Chapter 4 Loops

                           Caution
                           Don’t use floating-point values for equality checking in a loop control. Since floating-point values
numeric error              are approximations for some values, using them could result in imprecise counter values and inac-
                           curate results.
                           Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1:

                           double item = 1; double sum = 0;
                           while (item != 0) { // No guarantee item will be 0
                             sum += item;
                             item -= 0.1;
                           }
                           System.out.println(sum);

                           Variable item starts with 1 and is reduced by 0.1 every time the loop body is executed. The
                           loop should terminate when item becomes 0. However, there is no guarantee that item will be
                           exactly 0, because the floating-point arithmetic is approximated. This loop seems OK on the sur-
                           face, but it is actually an infinite loop.


                     4.2.5      Input and Output Redirections
                     In the preceding example, if you have a large number of data to enter, it would be cumber-
                     some to type from the keyboard. You may store the data separated by whitespaces in a text
                     file, say input.txt, and run the program using the following command:

                        java SentinelValue < input.txt

input redirection       This command is called input redirection. The program takes the input from the file
                     input.txt rather than having the user to type the data from the keyboard at runtime. Suppose
                     the contents of the file are

                        2 3 4 5 6 7 8 9 12 23 32
                        23 45 67 89 92 12 34 35 3 1 2 4 0

                     The program should get sum to be 518.
output redirection       Similarly, there is output redirection, which sends the output to a file rather than displaying
                     it on the console. The command for output redirection is:

                        java ClassName > output.txt

                     Input and output redirection can be used in the same command. For example, the following
                     command gets input from input.txt and sends output to output.txt:

                        java SentinelValue < input.txt > output.txt

                     Please run the program and see what contents are in output.txt.


                     4.3 The do-while Loop
                     The do-while loop is a variation of the while loop. Its syntax is given below:

do-while loop           do {
                          // Loop body;
                          Statement(s);
                        } while (loop-continuation-condition);

                     Its execution flow chart is shown in Figure 4.2.
                                                                                        4.3 The do-while Loop 125


                                            Statement(s)
                                            (loop body)




                                               loop-
                                    true    continuation
                                             condition?


                                                  false


FIGURE 4.2The do-while loop executes the loop body first, then checks the loop-
continuation-condition to determine whether to continue or terminate the loop.
   The loop body is executed first. Then the loop-continuation-condition is evalu-
ated. If the evaluation is true, the loop body is executed again; if it is false, the do-while
loop terminates. The difference between a while loop and a do-while loop is the order in
which the loop-continuation-condition is evaluated and the loop body executed. The
while loop and the do-while loop have equal expressive power. Sometimes one is a more
convenient choice than the other. For example, you can rewrite the while loop in Listing 4.4
using a do-while loop, as shown in Listing 4.5:

LISTING 4.5 TestDoWhile.java
 1 import java.util.Scanner;
 2
 3 public class TestDoWhile {
 4   /** Main method */
 5   public static void main(String[] args) {
 6     int data;
 7     int sum = 0;
 8
 9     // Create a Scanner
10     Scanner input = new Scanner(System.in);
11
12     // Keep reading data until the input is 0
13     do {                                                                                      loop
14       // Read the next data
15       System.out.print(
16         "Enter an int value (the program exits if the input is 0): ");
17       data = input.nextInt();
18
19       sum += data;
20     } while (data != 0);                                                                      end loop
21
22     System.out.println("The sum is " + sum);
23   }
24 }

    Enter an int value       (the   program   exits   if   the   input   is   0):   3
    Enter an int value       (the   program   exits   if   the   input   is   0):   5
    Enter an int value       (the   program   exits   if   the   input   is   0):   6
    Enter an int value       (the   program   exits   if   the   input   is   0):   0
    The sum is 14
126 Chapter 4 Loops

                        Tip
                        Use the do-while loop if you have statements inside the loop that must be executed at least
                        once, as in the case of the do-while loop in the preceding TestDoWhile program. These
                        statements must appear before the loop as well as inside it if you use a while loop.


                  4.4 The for Loop
                  Often you write a loop in the following common form:
                      i = initialValue; // Initialize loop control variable
                      while (i < endValue) {
                        // Loop body
                        ...
                        i++; // Adjust loop control variable
                      }

                  A for loop can be used to simplify the proceding loop:
                      for (i = initialValue; i < endValue; i++) {
                        // Loop body
                        ...
                      }

                  In general, the syntax of a for loop is as shown below:
for loop              for (initial-action; loop-continuation-condition;
                           action-after-each-iteration) {
                        // Loop body;
                        Statement(s);
                      }

                  The flow chart of the for loop is shown in Figure 4.3(a).



                                    Initial-Action                                        i = 0




                                       loop-
                                    continuation        false                                             false
                                                                                      (i < 100)?
                                     condition?


                                      true                                              true

                                    Statement(s)                              System.out.println(
                                    (loop body)                                  "Welcome to Java");



                              action-after-each-iteration                                  i++




                                         (a)                                                (b)

                  FIGURE 4.3 A for loop performs an initial action once, then repeatedly executes the
                  statements in the loop body, and performs an action after an iteration when the loop-
                  continuation-condition evaluates to true.
                                                                                                              4.4 The for Loop 127
   The for loop statement starts with the keyword for, followed by a pair of parentheses
enclosing the control structure of the loop. This structure consists of initial-action,
loop-continuation-condition, and action-after-each-iteration. The control
structure is followed by the loop body enclosed inside braces. The initial-action, loop-
continuation-condition, and action-after-each-iteration are separated by
semicolons.
   A for loop generally uses a variable to control how many times the loop body is executed
and when the loop terminates. This variable is referred to as a control variable. The initial-                   control variable
action often initializes a control variable, the action-after-each-iteration usually
increments or decrements the control variable, and the loop-continuation-condition
tests whether the control variable has reached a termination value. For example, the following
for loop prints Welcome to Java! a hundred times:

   int i;
   for (i = 0; i < 100; i++) {
     System.out.println("Welcome to Java!");
   }

The flow chart of the statement is shown in Figure 4.3(b). The for loop initializes i to 0, then
repeatedly executes the println statement and evaluates i++ while i is less than 100.
   The initial-action, i = 0, initializes the control variable, i. The loop-                                     initial-action
continuation-condition, i < 100, is a Boolean expression. The expression is evaluated
right after the initialization and at the beginning of each iteration. If this condition is true,
the loop body is executed. If it is false, the loop terminates and the program control turns to
the line following the loop.
   The action-after-each-iteration, i++, is a statement that adjusts the control vari-                           action-after-each-
able. This statement is executed after each iteration. It increments the control variable. Even-                   iteration
tually, the value of the control variable should force the loop-continuation-condition
to become false. Otherwise the loop is infinite.
   The loop control variable can be declared and initialized in the for loop. Here is an example:

   for (int i = 0 ; i < 100; i++) {
     System.out.println("Welcome to Java!");
   }

   If there is only one statement in the loop body, as in this example, the braces can be omitted.               omitting braces


      Tip
      The control variable must be declared inside the control structure of the loop or before the loop. If      declare control variable
      the loop control variable is used only in the loop, and not elsewhere, it is good programming prac-
      tice to declare it in the initial-action of the for loop. If the variable is declared inside the
      loop control structure, it cannot be referenced outside the loop. In the preceding code, for exam-
      ple, you cannot reference i outside the for loop, because it is declared inside the for loop.


      Note
      The initial-action in a for loop can be a list of zero or more comma-separated variable                    for loop variations
      declaration statements or assignment expressions. For example,

      for (int i = 0, j = 0 ; (i + j < 10); i++, j++) {
        // Do something
      }

      The action-after-each-iteration in a for loop can be a list of zero or more comma-
      separated statements. For example,

      for (int i = 1; i < 100; System.out.println(i), i++ );
128 Chapter 4 Loops
                                         This example is correct, but it is a bad example, because it makes the code difficult to read. Nor-
                                         mally, you declare and initialize a control variable as an initial action and increment or decrement
                                         the control variable as an action after each iteration.

                                        Note
                                         If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus
                                         the statement given below in (a), which is an infinite loop, is the same as in (b). To avoid confu-
                                         sion, though, it is better to use the equivalent loop in (c):

                       for ( ; ; ) {                   Equivalent        for ( ; true; ) {              Equivalent            while (true) {
                         // Do something                                   // Do something                                      // Do something
                       }                                                 }                                                    }
                                                                                                      This is better
                                  (a)                                               (b)                                              (c)


                             4.5 Which Loop to Use?
pretest loop                 The while loop and for loop are called pretest loops because the continuation condition is
posttest loop                checked before the loop body is executed. The do-while loop is called a posttest loop
                             because the condition is checked after the loop body is executed. The three forms of loop
                             statements, while, do-while, and for, are expressively equivalent; that is, you can write a
                             loop in any of these three forms. For example, a while loop in (a) in the following figure can
                             always be converted into the for loop in (b):

       while (loop-continuation-condition) {                                            for ( ; loop-continuation-condition; ) {
           // Loop body                                              Equivalent             // Loop body
       }                                                                                }

                            (a)                                                                                   (b)

                                A for loop in (a) in the next figure can generally be converted into the while loop in
                             (b) except in certain special cases (see Review Question 4.17 for such a case):

                for (initial-action;                                                         initial-action;
                       loop-continuation-condition;                        Equivalent        while (loop-continuation-condition) {
                       action-after-each-iteration) {                                            // Loop body;
                    // Loop body;                                                                action-after-each-iteration;
                }                                                                            }

                                        (a)                                                                            (b)

                                Use the loop statement that is most intuitive and comfortable for you. In general, a for loop
                             may be used if the number of repetitions is known in advance, as, for example, when you need to
                             print a message a hundred times. A while loop may be used if the number of repetitions is not
                             fixed, as in the case of reading the numbers until the input is 0. A do-while loop can be used to
                             replace a while loop if the loop body has to be executed before the continuation condition is tested.

                                        Caution
                                         Adding a semicolon at the end of the for clause before the loop body is a common mistake, as
                                         shown below in (a). In (a), the semicolon signifies the end of the loop prematurely. The loop
                                         body is actually empty, as shown in (b). (a) and (b) are equivalent.
                                                                               Error                                                Empty Body

                                   for (int i = 0; i < 10; i++);                                 for (int i = 0; i < 10; i++) { };
                                   {                                                             {
                                     System.out.println("i is " + i);                              System.out.println("i is " + i);
                                   }                                                             }

                                                            (a)                                                         (b)
                                                                                                           4.6 Nested Loops   129
      Similarly, the loop in (c) is also wrong. (c) is equivalent to (d).


                            Error                                              Empty Body

  int i = 0;                                                int i = 0;
  while (i < 10);                                           while (i < 10) { };
  {                                                         {
    System.out.println("i is " + i);                          System.out.println("i is " + i);
    i++;                                                      i++;
  }                                                         }

                          (c)                                                    (d)



      These errors often occur when you use the next-line block style. Using the end-of-line block style
      can avoid errors of this type.
      In the case of the do-while loop, the semicolon is needed to end the loop.


                                int i = 0;
                                do {
                                  System.out.println("i is " + i);
                                  i++;
                                } while (i < 10);

                                                               Correct



4.6 Nested Loops
Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is
repeated, the inner loops are reentered, and started anew.
   Listing 4.6 presents a program that uses nested for loops to print a multiplication table.

LISTING 4.6 MultiplicationTable.java
 1 public class MultiplicationTable {
 2   /** Main method */
 3   public static void main(String[] args) {
 4     // Display the table heading
 5     System.out.println("           Multiplication Table");                                                 table title
 6
 7     // Display the number title
 8     System.out.print("    ");
 9     for (int j = 1; j <= 9; j++)
10       System.out.print("   " + j);
11
12     System.out.println("\n———————————————————————————————————————");
13
14     // Print table body
15     for (int i = 1; i <= 9; i++) {                                                                         outer loop
16       System.out.print(i + " | ");
17       for (int j = 1; j <= 9; j++) {                                                                       inner loop
18         // Display the product and align properly
19         System.out.printf("%4d", i * j);
20       }
21       System.out.println()
22     }
23   }
24 }
130 Chapter 4 Loops

                                         Multiplication Table
                                     1   2   3   4   5   6   7   8   9
                              ———————————————————————————————————————-
                              1 |    1   2   3   4   5   6   7   8   9
                              2 |    2   4   6   8 10 12 14 16 18
                              3 |    3   6   9 12 15 18 21 24 27
                              4 |    4   8 12 16 20 24 28 32 36
                              5 |    5 10 15 20 25 30 35 40 45
                              6 |    6 12 18 24 30 36 42 48 54
                              7 |    7 14 21 28 35 42 49 56 63
                              8 |    8 16 24 32 40 48 56 64 72
                              9 |    9 18 27 36 45 54 63 72 81



                          The program displays a title (line 5) on the first line in the output. The first for loop (lines
                          9–10) displays the numbers 1 through 9 on the second line. A dash (-) line is displayed on the
                          third line (line 12).
                             The next loop (lines 15–22) is a nested for loop with the control variable i in the outer
                          loop and j in the inner loop. For each i, the product i * j is displayed on a line in the inner
                          loop, with j being 1, 2, 3, Á , 9.


                          4.7 Minimizing Numeric Errors
                          Numeric errors involving floating-point numbers are inevitable. This section discusses how to
                          minimize such errors through an example.
Video Note
                            Listing 4.7 presents an example summing a series that starts with 0.01 and ends with
Minimize numeric errors
                          1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03
                          and so on.

                          LISTING 4.7 TestSum.java
                           1 public class TestSum {
                           2   public static void main(String[] args) {
                           3     // Initialize sum
                           4     float sum = 0;
                           5
                           6     // Add 0.01, 0.02, ..., 0.99, 1 to sum
loop                       7     for (float i = 0.01f; i <= 1.0f; i = i + 0.01f)
                           8       sum += i;
                           9
                          10     // Display result
                          11     System.out.println("The sum is " + sum);
                          12   }
                          13 }



                              The sum is 50.499985



                          The for loop (lines 7–8) repeatedly adds the control variable i to sum. This variable, which
                          begins with 0.01, is incremented by 0.01 after each iteration. The loop terminates when i
                          exceeds 1.0.
                              The for loop initial action can be any statement, but it is often used to initialize a control
                          variable. From this example, you can see that a control variable can be a float type. In fact,
                          it can be any data type.
                                                                                                4.8 Case Studies 131
   The exact sum should be 50.50, but the answer is 50.499985. The result is imprecise
because computers use a fixed number of bits to represent floating-point numbers, and thus
they cannot represent some floating-point numbers exactly. If you change float in the pro-
gram to double, as follows, you should see a slight improvement in precision, because a             double precision
double variable takes 64 bits, whereas a float variable takes 32.

   // Initialize sum
   double sum = 0;

   // Add 0.01, 0.02, ..., 0.99, 1 to sum
   for (double i = 0.01; i <= 1.0; i = i + 0.01)
     sum += i;

However, you will be stunned to see that the result is actually 49.50000000000003. What             numeric error
went wrong? If you print out i for each iteration in the loop, you will see that the last i is
slightly larger than 1 (not exactly 1). This causes the last i not to be added into sum. The fun-
damental problem is that the floating-point numbers are represented by approximation. To fix
the problem, use an integer count to ensure that all the numbers are added to sum. Here is the
new loop:

   double currentValue = 0.01;
   for (int count = 0; count < 100; count++) {
     sum += currentValue;
     currentValue += 0.01;
   }

After this loop, sum is 50.50000000000003. This loop adds the numbers from small to big.
What happens if you add numbers from big to small (i.e., 1.0, 0.99, 0.98, Á , 0.02, 0.01
in this order) as follows:

   double currentValue = 1.0;
   for (int count = 0; count < 100; count++) {
     sum += currentValue;
     currentValue -= 0.01;
   }

After this loop, sum is 50.49999999999995. Adding from big to small is less accurate than
adding from small to big. This phenomenon is an artifact of the finite-precision arithmetic.
Adding a very small number to a very big number can have no effect if the result requires
more precision than the variable can store. For example, the inaccurate result of
100000000.0 + 0.000000001 is 100000000.0. To obtain more accurate results, carefully
select the order of computation. Adding the smaller numbers before the big numbers is one
way to minimize error.                                                                              avoiding numeric error


4.8 Case Studies
Loops are fundamental in programming. The ability to write loops is essential in learning Java
programming. If you can write programs using loops, you know how to program! For this rea-
son, this section presents three additional examples of solving problems using loops.

4.8.1 Problem: Finding the Greatest Common Divisor
The greatest common divisor of two integers 4 and 2 is 2. The greatest common divisor of
two integers 16 and 24 is 8. How do you find the greatest common divisor? Let the two input
integers be n1 and n2. You know that number 1 is a common divisor, but it may not be the
132 Chapter 4 Loops
                        greatest common divisor. So, you can check whether k (for k = 2, 3, 4, and so on) is a com-
                        mon divisor for n1 and n2, until k is greater than n1 or n2. Store the common divisor in a
gcd                     variable named gcd. Initially, gcd is 1. Whenever a new common divisor is found, it becomes
                        the new gcd. When you have checked all the possible common divisors from 2 up to n1 or n2,
                        the value in variable gcd is the greatest common divisor. The idea can be translated into the
                        following loop:

                           int gcd = 1; // Initial gcd is 1
                           int k = 2; // Possible gcd
                           while (k <= n1 && k <= n2) {
                             if (n1 % k == 0 && n2 % k == 0)
                               gcd = k; // Update gcd
                             k++; // Next possible gcd
                           }

                           // After the loop, gcd is the greatest common divisor for n1 and n2

                        Listing 4.8 presents the program that prompts the user to enter two positive integers and finds
                        their greatest common divisor.

                        LISTING 4.8 GreatestCommonDivisor.java
                         1 import java.util.Scanner;
                         2
                         3 public class GreatestCommonDivisor {
                         4   /** Main method */
                         5   public static void main(String[] args) {
                         6     // Create a Scanner
                         7     Scanner input = new Scanner(System.in);
                         8
                         9     // Prompt the user to enter two integers
                        10     System.out.print("Enter first integer: ");
input                   11     int n1 = input.nextInt();
                        12     System.out.print("Enter second integer: ");
input                   13     int n2 = input.nextInt();
                        14
gcd                     15     int gcd = 1; // Initial gcd is 1
                        16     int k = 2; // Possible gcd
                        17     while (k <= n1 && k <= n2) {
check divisor           18       if (n1 % k == 0 && n2 % k == 0)
                        19         gcd = k; // Update gcd
                        20       k++;
                        21     }
                        22
output                  23     System.out.println("The greatest common divisor for " + n1 +
                        24       " and " + n2 + " is " + gcd);
                        25   }
                        26 }



                            Enter first integer: 125
                            Enter second integer: 2525
                            The greatest common divisor for 125 and 2525 is 25


                        How did you write this program? Did you immediately begin to write the code? No. It is
                        important to think before you type. Thinking enables you to generate a logical solution for the
think before you type   problem without concern about how to write the code. Once you have a logical solution, type
                                                                                                    4.8 Case Studies 133
the code to translate the solution into a Java program. The translation is not unique. For exam-
ple, you could use a for loop to rewrite the code as follows:

   for (int k = 2; k <= n1 && k <= n2; k++) {
     if (n1 % k == 0 && n2 % k == 0)
       gcd = k;
   }

A problem often has multiple solutions. The gcd problem can be solved in many ways. Exer-            multiple solutions
cise 4.15 suggests another solution. A more efficient solution is to use the classic Euclidean
algorithm. See http://www.cut-the-knot.org/blue/Euclid.shtml for more information.
   You might think that a divisor for a number n1 cannot be greater than n1 / 2. So you              erroneous solutions
would attempt to improve the program using the following loop:

   for (int k = 2; k <= n1 / 2 && k <= n2 / 2 ; k++) {
     if (n1 % k == 0 && n2 % k == 0)
       gcd = k;
   }

This revision is wrong. Can you find the reason? See Review Question 4.14 for the answer.


4.8.2     Problem: Predicating the Future Tuition
Suppose that the tuition for a university is $10,000 this year and tuition increases 7% every
year. In how many years will the tuition be doubled?
   Before you can write a program to solve this problem, first consider how to solve it by
hand. The tuition for the second year is the tuition for the first year * 1.07. The tuition for a
future year is the tuition of its preceding year * 1.07. So, the tuition for each year can be
computed as follows:

   double tuition = 10000;           int year = 1       //   Year   1
   tuition = tuition * 1.07;         year++;            //   Year   2
   tuition = tuition * 1.07;         year++;            //   Year   3
   tuition = tuition * 1.07;         year++;            //   Year   4
   ...

Keep computing tuition for a new year until it is at least 20000. By then you will know how
many years it will take for the tuition to be doubled. You can now translate the logic into the
following loop:

   double tuition = 10000;   // Year 1
   int year = 1;
   while (tuition < 20000) {
     tuition = tuition * 1.07;
     year++;
   }

The complete program is shown in Listing 4.9.


LISTING 4.9 FutureTuition.java
 1 public class FutureTuition {
 2   public static void main(String[] args) {
 3     double tuition = 10000;   // Year 1
 4     int year = 1;
 5     while (tuition < 20000) {                                                                     loop
134 Chapter 4 Loops
next year’s tuition       6       tuition = tuition * 1.07;
                          7       year++;
                          8     }
                          9
                         10     System.out.println("Tuition will be doubled in "
                         11       + year + " years");
                         12   }
                         13 }


                             Tuition will be doubled in 12 years



                         The while loop (lines 5–8) is used to repeatedly compute the tuition for a new year. The loop
                         terminates when tuition is greater than or equal to 20000.

                         4.8.3     Problem: Problem: Monte Carlo Simulation
                         Monte Carlo simulation uses random numbers and probability to solve problems. This
                         method has a wide range of applications in computational mathematics, physics, chemistry,
                         and finance. This section gives an example of using Monte Carlo simulation for estimating p.
                            To estimate p using the Monte Carlo method, draw a circle with its bounding square as
                         shown below.

                                                                          y

                                                                      1


                                                                                   x
                                                             –1                1


                                                                     –1


                            Assume the radius of the circle is 1. So, the circle area is p and the square area is 4. Ran-
                         domly generate a point in the square. The probability for the point to fall in the circle is
                         circleArea / squareArea = π / 4.
                            Write a program that randomly generates 1000000 points in the square and let
                         numberOfHits denote the number of points that fall in the circle. So, numberOfHits is
                         approximately 1000000 * (π / 4). p can be approximated as 4 * numberOfHits /
                         1000000. The complete program is shown in Listing 4.10.

                         LISTING 4.10 MonteCarloSimulation.java
                          1 public class MonteCarloSimulation {
                          2   public static void main(String[] args) {
                          3     final int NUMBER_OF_TRIALS = 10000000;
                          4     int numberOfHits = 0;
                          5
                          6     for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
generate random points    7       double x = Math.random() * 2.0 - 1;
                          8       double y = Math.random() * 2.0 - 1;
check inside circle       9       if (x * x + y * y <= 1)
                         10         numberOfHits++;
                         11     }
                         12
estimate pi              13     double pi = 4.0 * numberOfHits / NUMBER_OF_TRIALS;
                                                                              4.9 Keywords break and continue 135
14     System.out.println("PI is " + pi);
15   }
16 }



    PI is 3.14124



The program repeatedly generates a random point (x, y) in the square in lines 7–8:

  double x = Math.random() * 2.0 - 1;
  double y = Math.random() * 2.0 - 1;

If x2 + y 2 … 1, the point is inside the circle and numberOfHits is incremented by 1. p is
approximately 4 * numberOfHits / NUMBER_OF_TRIALS (line 13).


4.9 Keywords break and continue
     Pedagogical Note
     Two keywords, break and continue, can be used in loop statements to provide additional
     controls. Using break and continue can simplify programming in some cases. Overusing or
     improperly using them, however, can make programs difficult to read and debug. (Note to instruc-
     tors: You may skip this section without affecting the rest of the book.)

You have used the keyword break in a switch statement. You can also use break in a loop                 break
to immediately terminate the loop. Listing 4.11 presents a program to demonstrate the effect
of using break in a loop.

LISTING 4.11 TestBreak.java
 1 public class TestBreak {
 2   public static void main(String[] args) {
 3     int sum = 0;
 4     int number = 0;
 5
 6     while (number < 20) {
 7       number++;
 8       sum += number;
 9       if (sum >= 100)
10         break;                                                                                       break
11     }
12
13     System.out.println("The number is " + number);
14     System.out.println("The sum is " + sum);
15   }
16 }



    The number is 14
    The sum is 105



The program in Listing 4.11 adds integers from 1 to 20 in this order to sum until sum is
greater than or equal to 100. Without the if statement (line 9), the program calculates the
sum of the numbers from 1 to 20. But with the if statement, the loop terminates when sum
becomes greater than or equal to 100. Without the if statement, the output would be:
136 Chapter 4 Loops

                      The number is 20
                      The sum is 210



continue          You can also use the continue keyword in a loop. When it is encountered, it ends the current
                  iteration. Program control goes to the end of the loop body. In other words, continue breaks
                  out of an iteration while the break keyword breaks out of a loop. Listing 4.12 presents a pro-
                  gram to demonstrate the effect of using continue in a loop.

                  LISTING 4.12 TestContinue.java
                   1 public class TestContinue {
                   2   public static void main(String[] args) {
                   3     int sum = 0;
                   4     int number = 0;
                   5
                   6     while (number < 20) {
                   7       number++;
                   8       if (number == 10 || number == 11)
continue           9         continue;
                  10       sum += number;
                  11     }
                  12
                  13     System.out.println("The sum is " + sum);
                  14   }
                  15 }


                      The sum is 189


                  The program in Listing 4.12 adds integers from 1 to 20 except 10 and 11 to sum. With the if
                  statement in the program (line 8), the continue statement is executed when number
                  becomes 10 or 11. The continue statement ends the current iteration so that the rest of the
                  statement in the loop body is not executed; therefore, number is not added to sum when it is
                  10 or 11. Without the if statement in the program, the output would be as follows:


                      The sum is 210


                  In this case, all of the numbers are added to sum, even when number is 10 or 11. Therefore,
                  the result is 210, which is 21 more than it was with the if statement.

                       Note
                        The continue statement is always inside a loop. In the while and do-while loops, the
                        loop-continuation-condition is evaluated immediately after the continue state-
                        ment. In the for loop, the action-after-each-iteration is performed, then the
                        loop-continuation-condition is evaluated, immediately after the continue
                        statement.

                     You can always write a program without using break or continue in a loop. See Review
                  Question 4.18. In general, using break and continue is appropriate only if it simplifies cod-
                  ing and makes programs easier to read.
                     Listing 4.2 gives a program for guessing a number. You can rewrite it using a break state-
                  ment, as shown in Listing 4.13.
                                                                              4.9 Keywords break and continue 137

LISTING 4.13 GuessNumberUsingBreak.java
 1 import java.util.Scanner;
 2
 3 public class GuessNumberUsingBreak {
 4   public static void main(String[] args) {
 5     // Generate a random number to be guessed
 6     int number = (int)(Math.random() * 101);                                                         generate a number
 7
 8     Scanner input = new Scanner(System.in);
 9     System.out.println("Guess a magic number between 0 and 100");
10
11     while (true) {                                                                                   loop continuously
12       // Prompt the user to guess the number
13       System.out.print("\nEnter your guess: ");                                                      enter a guess
14       int guess = input.nextInt();
15
16       if (guess == number) {
17         System.out.println("Yes, the number is " + number);
18         break;                                                                                       break
19       }
20       else if (guess > number)
21         System.out.println("Your guess is too high");
22       else
23         System.out.println("Your guess is too low");
24     } // End of loop
25   }
26 }

Using the break statement makes this program simpler and easier to read. However, you
should use break and continue with caution. Too many break and continue statements
will produce a loop with many exit points and make the program difficult to read.

      Note
      Some programming languages have a goto statement. The goto statement indiscriminately             goto
      transfers control to any statement in the program and executes it. This makes your program vul-
      nerable to errors. The break and continue statements in Java are different from goto state-
      ments. They operate only in a loop or a switch statement. The break statement breaks out of
      the loop, and the continue statement breaks out of the current iteration in the loop.


4.9.1 Problem: Displaying Prime Numbers
An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3,
5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.
   The problem is to display the first 50 prime numbers in five lines, each of which contains
ten numbers. The problem can be broken into the following tasks:

      ■   Determine whether a given number is prime.
      ■   For number = 2, 3, 4, 5, 6, Á , test whether it is prime.
      ■   Count the prime numbers.
      ■   Print each prime number, and print ten numbers per line.

Obviously, you need to write a loop and repeatedly test whether a new number is prime. If the
number is prime, increase the count by 1. The count is 0 initially. When it reaches 50, the
loop terminates.
138 Chapter 4 Loops
                        Here is the algorithm for the problem:

                        Set the number of prime numbers to be printed as
                          a constant NUMBER_OF_PRIMES;
                        Use count to track the number of prime numbers and
                          set an initial count to 0;
                        Set an initial number to 2;

                        while (count < NUMBER_OF_PRIMES) {
                          Test whether number is prime;

                            if number is prime {
                              Print the prime number and increase the count;
                            }

                            Increment number by 1;
                        }

                      To test whether a number is prime, check whether it is divisible by 2, 3, 4, up to number/2.
                      If a divisor is found, the number is not a prime. The algorithm can be described as follows:

                        Use a boolean variable isPrime to denote whether
                          the number is prime; Set isPrime to true initially;

                        for (int divisor = 2; divisor <= number / 2; divisor++) {
                          if (number % divisor == 0) {
                            Set isPrime to false
                            Exit the loop;
                          }
                        }

                      The complete program is given in Listing 4.14.

                      LISTING 4.14 PrimeNumber.java
                       1 public class PrimeNumber {
                       2   public static void main(String[] args) {
                       3     final int NUMBER_OF_PRIMES = 50; // Number of primes to display
                       4     final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
                       5     int count = 0; // Count the number of prime numbers
                       6     int number = 2; // A number to be tested for primeness
                       7
                       8     System.out.println("The first 50 prime numbers are \n");
                       9
                      10     // Repeatedly find prime numbers
count prime numbers   11     while (count < NUMBER_OF_PRIMES) {
                      12       // Assume the number is prime
                      13       boolean isPrime = true; // Is the current number prime?
                      14
                      15       // Test whether number is prime
check primeness       16       for (int divisor = 2; divisor <= number / 2; divisor++) {
                      17         if (number % divisor == 0) { // If true, number is not prime
                      18           isPrime = false; // Set isPrime to false
exit loop             19           break; // Exit the for loop
                      20         }
                      21       }
                      22
                      23       // Print the prime number and increase the count
print if prime        24       if (isPrime) {
                      25         count++; // Increase the count
                                          4.10 (GUI) Controlling a Loop with a Confirmation Dialog 139
26
27         if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
28           // Print the number and advance to the new line
29           System.out.println(number);
30         }
31         else
32           System.out.print(number + " ");
33       }
34
35       // Check if the next number is prime
36       number++;
37     }
38   }
39 }


    The first 50 prime numbers are

    2 3 5 7 11 13 17 19 23 29
    31 37 41 43 47 53 59 61 67 71
    73 79 83 89 97 101 103 107 109 113
    127 131 137 139 149 151 157 163 167 173
    179 181 191 193 197 199 211 223 227 229


This is a complex program for novice programmers. The key to developing a programmatic
solution to this problem, and to many other problems, is to break it into subproblems and       subproblem
develop solutions for each of them in turn. Do not attempt to develop a complete solution in
the first trial. Instead, begin by writing the code to determine whether a given number is
prime, then expand the program to test whether other numbers are prime in a loop.
    To determine whether a number is prime, check whether it is divisible by a number
between 2 and number/2 inclusive (line 16). If so, it is not a prime number (line 18); other-
wise, it is a prime number. For a prime number, display it. If the count is divisible by 10
(lines 27–30), advance to a new line. The program ends when the count reaches 50.
    The program uses the break statement in line 19 to exit the for loop as soon as the num-
ber is found to be a nonprime. You can rewrite the loop (lines 16–21) without using the break
statement, as follows:

   for (int divisor = 2; divisor <= number / 2 && isPrime;
        divisor++) {
     // If true, the number is not prime
     if (number % divisor == 0) {
       // Set isPrime to false, if the number is not prime
       isPrime = false;
     }
   }

However, using the break statement makes the program simpler and easier to read in this case.


4.10 (GUI) Controlling a Loop with a Confirmation Dialog
A sentinel-controlled loop can be implemented using a confirmation dialog. The answers Yes      confirmation dialog
or No continue or terminate the loop. The template of the loop may look as follows:
   int option = JOptionPane.YES_OPTION;
   while (option == JOptionPane.YES_OPTION) {
     System.out.println("continue loop");
     option = JOptionPane.showConfirmDialog(null, "Continue?");
   }
140 Chapter 4 Loops
                                Listing 4.15 rewrites Listing 4.4, SentinelValue.java, using a confirmation dialog box. A sam-
                                ple run is shown in Figure 4.4.

                      y

                  1


                                x
         –1                 1
                          (a)                                     (b)

                 –1




                          (c)                                      (d)                                  (e)

        FIGURE 4.4 The user enters 3 in (a), clicks Yes in (b), enters 5 in (c), clicks No in (d), and the result is
        shown in (e).


                                LISTING 4.15 SentinelValueUsingConfirmationDialog.java
                                 1 import javax.swing.JOptionPane;
                                 2
                                 3 public class SentinelValueUsingConfirmationDialog {
                                 4   public static void main(String[] args) {
                                 5     int sum = 0;
                                 6
                                 7     // Keep reading data until the user answers No
confirmation option              8     int option = JOptionPane.YES_OPTION;
check option                     9     while (option == JOptionPane.YES_OPTION) {
                                10       // Read the next data
input dialog                    11       String dataString = JOptionPane.showInputDialog(
                                12         "Enter an int value: ");
                                13       int data = Integer.parseInt(dataString);
                                14
                                15       sum += data;
                                16
confirmation dialog             17       option = JOptionPane.showConfirmDialog(null, "Continue?");
                                18     }
                                19
message dialog                  20     JOptionPane.showMessageDialog(null, "The sum is " + sum);
                                21   }
                                22 }

                                A program displays an input dialog to prompt the user to enter an integer (line 11) and adds it
                                to sum (line 15). Line 17 displays a confirmation dialog to let the user decide whether to con-
                                tinue the input. If the user clicks Yes, the loop continues; otherwise the loop exits. Finally the
                                program displays the result in a message dialog box (line 20).

                                    KEY TERMS
                                    break statement 136                              for loop     126
                                    continue statement 136                           loop control structure    127
                                    do-while loop 124                                infinite loop 117
                                                                                                Chapter Summary 141
 input redirection 124                              loop body 116
 iteration 116                                      nested loop 129
 labeled continue statement     136                 off-by-one error 124
 loop 116                                           output redirection 124
 loop-continuation-                                 sentinel value 122
   condition 116                                    while loop 116




 CHAPTER SUMMARY
 1. There are three types of repetition statements: the while loop, the do-while loop,
     and the for loop.

 2. The part of the loop that contains the statements to be repeated is called the loop body.

 3. A one-time execution of a loop body is referred to as an iteration of the loop.
 4. An infinite loop is a loop statement that executes infinitely.

 5. In designing loops, you need to consider both the loop control structure and the loop
     body.

 6. The while loop checks the loop-continuation-condition first. If the condition
     is true, the loop body is executed; if it is false, the loop terminates.

 7. The do-while loop is similar to the while loop, except that the do-while loop exe-
     cutes the loop body first and then checks the loop-continuation-condition to
     decide whether to continue or to terminate.

 8. Since the  while loop and the do-while loop contain the loop-continuation-
     condition, which is dependent on the loop body, the number of repetitions is deter-
     mined by the loop body. The while loop and the do-while loop often are used when
     the number of repetitions is unspecified.

 9. A sentinel value is a special value that signifies the end of the loop.

10. The for loop generally is used to execute a loop body a predictable number of times;
     this number is not determined by the loop body.

11. The for loop control has three parts. The first part is an initial action that often initial-
     izes a control variable. The second part, the loop-continuation-condition, determines
     whether the loop body is to be executed. The third part is executed after each iteration
     and is often used to adjust the control variable. Usually, the loop control variables are
     initialized and changed in the control structure.

12. The while loop and for loop are called pretest loops because the continuation condi-
     tion is checked before the loop body is executed.

13. The do-while loop is called posttest loop because the condition is checked after the
     loop body is executed.

14. Two keywords, break and continue, can be used in a loop.
142 Chapter 4 Loops

                         15. The break keyword immediately ends the innermost loop, which contains the break.

                         16. The continue keyword only ends the current iteration.

                          REVIEW QUESTIONS
                          Sections 4.2–4.4
                          4.1     Analyze the following code. Is count < 100 always true, always false, or
                                  sometimes true or sometimes false at Point A, Point B, and Point C?

                                  int count = 0;
                                  while (count < 100) {
                                    // Point A
                                    System.out.println("Welcome to Java!\n");
                                    count++;
                                    // Point B
                                  }
                                    // Point C

                          4.2     What is wrong if guess is initialized to 0 in line 11 in Listing 4.2?
                          4.3     How many times is the following loop body repeated? What is the printout of the
                                  loop?

     int i = 1;                          int i = 1;                            int i = 1;
     while (i < 10)                      while (i < 10)                        while (i < 10)
       if (i % 2 == 0)                     if (i % 2 == 0)                       if ((i++) % 2 == 0)
         System.out.println(i);               System.out.println(i++);                System.out.println(i);

                 (a)                                     (b)                                    (c)


                          4.4     What are the differences between a while loop and a do-while loop? Convert
                                  the following while loop into a do-while loop.
                                  int sum = 0;
                                  int number = input.nextInt();
                                  while (number != 0) {
                                    sum += number;
                                    number = input.nextInt();
                                  }

                          4.5     Do the following two loops result in the same value in sum?


                            for (int i = 0; i < 10; ++i ) {           for (int i = 0; i < 10; i++ ) {
                                sum += i;                                 sum += i;
                            }                                         }

                                              (a)                                       (b)

                          4.6     What are the three parts of a for loop control? Write a for loop that prints the
                                  numbers from 1 to 100.
                          4.7     Suppose the input is 2 3 4 5 0. What is the output of the following code?

                                  import java.util.Scanner;
                                  public class Test {
                                                                                  Review Questions 143
          public static void main(String[] args) {
            Scanner input = new Scanner(System.in);

              int number, max;
              number = input.nextInt();
              max = number;

              while (number != 0) {
                number = input.nextInt();
                if (number > max)
                  max = number;
              }

              System.out.println("max is " + max);
              System.out.println("number " + number);
          }
      }

4.8   Suppose the input is 2 3 4 5 0. What is the output of the following code?
      import java.util.Scanner;

      public class Test {
        public static void main(String[] args) {
          Scanner input = new Scanner(System.in);

              int number, sum = 0, count;

              for (count = 0; count < 5; count++) {
                number = input.nextInt();
                sum += number;
              }

              System.out.println("sum is " + sum);
              System.out.println("count is " + count);
          }
      }

4.9   Suppose the input is 2 3 4 5 0. What is the output of the following code?

      import java.util.Scanner;

      public class Test {
        public static void main(String[] args) {
          Scanner input = new Scanner(System.in);

              int number, max;
              number = input.nextInt();
              max = number;

              do {
                number = input.nextInt();
                if (number > max)
                  max = number;
              } while (number != 0);

              System.out.println("max is " + max);
              System.out.println("number " + number);
          }
      }
144 Chapter 4 Loops

                      4.10 What does the following statement do?
                              for ( ; ; ) {
                                do something;
                              }

                      4.11 If a variable is declared in the for loop control, can it be used after the loop exits?
                      4.12 Can you convert a for loop to a while loop? List the advantages of using for
                              loops.
                      4.13 Convert the following for loop statement to a while loop and to a do-while loop:
                              long sum = 0;
                              for (int i = 0; i <= 1000; i++)
                                sum = sum + i;

                      4.14 Will the program work if n1 and n2 are replaced by n1 / 2 and n2 / 2 in line 17 in
                              Listing 4.8?

                      Section 4.9
                      4.15 What is the keyword break for? What is the keyword continue for? Will the fol-
                              lowing program terminate? If so, give the output.

                  int balance = 1000;                                   int balance = 1000;
                  while (true) {                                        while (true) {
                    if (balance < 9)                                      if (balance < 9)
                      break;                                                continue;
                      balance = balance - 9;                                 balance = balance - 9;
                  }                                                     }

                  System.out.println("Balance is "                      System.out.println("Balance is "
                    + balance);                                           + balance);

                                        (a)                                                 (b)

                      4.16 Can you always convert a     while loop into a for loop? Convert the following
                              while loop into a for loop.

                              int i = 1;
                              int sum = 0;
                              while (sum < 10000) {
                                sum = sum + i;
                                i++;
                              }

                      4.17 The for loop on the left is converted into the while loop on the right. What is
                              wrong? Correct it.

                        for (int i = 0; i < 4; i++) {                          int i = 0;
                          if (i % 3 == 0) continue;             Converted      while (i < 4) {
                          sum += i;                             Wrong            if(i % 3 == 0) continue;
                        }                                       conversion       sum += i;
                                                                                 i++;
                                                                               }
                                                                                   Review Questions 145

4.18 Rewrite the programs TestBreak and TestContinue in Listings 4.11 and 4.12
        without using break and continue.
4.19 After the break statement is executed in the following loop, which statement is
        executed? Show the output.

        for (int i = 1; i < 4; i++) {
          for (int j = 1; j < 4; j++) {
            if (i * j > 2)
              break;
                System.out.println(i * j);
            }
            System.out.println(i);
        }


4.20 After the continue statement is executed in the following loop, which statement
        is executed? Show the output.

        for (int i = 1; i < 4; i++) {
          for (int j = 1; j < 4; j++) {
            if (i * j > 2)
              continue;
                System.out.println(i * j);
            }
            System.out.println(i);
        }



Comprehensive
4.21 Identify and fix the errors in the following code:

         1 public class Test {
         2   public void main(String[] args) {
         3     for (int i = 0; i < 10; i++);
         4        sum += i;
         5
         6     if (i < j);
         7       System.out.println(i)
         8     else
         9       System.out.println(j);
        10
        11     while (j < 10);
        12     {
        13       j++;
        14     };
        15
        16     do {
        17       j++;
        18     } while (j < 10)
        19   }
        20 }
146 Chapter 4 Loops

                                4.22 What is wrong with the following programs?

1 public class ShowErrors {                                   1 public class ShowErrors {
2   public static void main(String[] args) {                  2   public static void main(String[] args) {
3     int i;                                                  3     for (int i = 0; i < 10; i++);
4     int j = 5;                                              4       System.out.println(i + 4);
5                                                             5   }
6     if (j > 3)                                              6 }
7       System.out.println(i + 4);
8   }
9 }
                          (a)                                                            (b)

                                4.23 Show the output of the following programs. (Tip: Draw a table and list the vari-
                                       ables in the columns to trace these programs.)

 public class Test {                                          public class Test {
   /** Main method */                                           /** Main method */
   public static void main(String[] args) {                     public static void main(String[] args) {
     for (int i = 1; i < 5; i++) {                                int i = 0;
       int j = 0;                                                 while (i < 5) {
       while (j < i) {                                              for (int j = i; j > 1; j-)
          System.out.print(j + " ");                                   System.out.print(j + " ");
                 j++;                                               System.out.println("****");
             }                                                            i++;
         }                                                            }
     }                                                            }
 }                                                            }

                           (a)                                                          (b)


 public class Test {                                          public class Test {
   public static void main(String[] args) {                     public static void main(String[] args) {
     int i = 5;                                                   int i = 1;
     while (i >= 1) {                                             do {
       int num = 1;                                                 int num = 1;
       for (int j = 1; j <= i; j++) {                               for (int j = 1; j <= i; j++) {
          System.out.print(num + "xxx");                               System.out.print(num + "G");
          num *= 2;                                                    num += 2;
             }                                                            }
             System.out.println();                                      System.out.println();
             i--;                                                       i++;
         }                                                            } while (i <= 5);
     }                                                            }
 }                                                            }

                           (c)                                                          (d)

                                4.24 What is the output of the following program? Explain the reason.
                                       int x = 80000000;
                                       while (x > 0)
                                         x++;
                                       System.out.println("x is " + x);

                                4.25 Count the number of iterations in the following loops.
                                                                                                     Programming Exercises 147

int count = 0;                                                    for (int count = 0;
while (count < n) {                                                    count <= n; count++) {
    count++;                                                      }
}

                          (a)                                                                 (b)



int count = 5;                                                    int count = 5;
while (count < n) {                                               while (count < n) {
    count++;                                                        count = count + 3;
}                                                                 }

                           (c)                                                                 (d)



PROGRAMMING EXERCISES

       Pedagogical Note
       For each problem, read it several times until you understand the problem. Think how to solve
       the problem before coding. Translate your logic into a program.                                     read and think before coding

       A problem often can be solved in many different ways. Students are encouraged to explore
       various solutions.                                                                                  explore solutions

Sections 4.2–4.7
4.1* (Counting positive and negative numbers and computing the average of numbers)
         Write a program that reads an unspecified number of integers, determines how
         many positive and negative values have been read, and computes the total and
         average of the input values (not counting zeros). Your program ends with the input
         0. Display the average as a floating-point number. Here is a sample run:




    Enter an int value, the program exits if the input is 0:
      1 2 -1 3 0
    The number of positives is 3
    The number of negatives is 1
    The total is 5
    The average is 1.25




4.2      (Repeating additions) Listing 4.3, SubtractionQuizLoop.java, generates five ran-
         dom subtraction questions. Revise the program to generate ten random addition
         questions for two integers between 1 and 15. Display the correct count and test
         time.
4.3      (Conversion from kilograms to pounds) Write a program that displays the follow-
         ing table (note that 1 kilogram is 2.2 pounds):

         Kilograms              Pounds

         1                       2.2
         3                       6.6
         ...
         197                433.4
         199                437.8
148 Chapter 4 Loops

                      4.4    (Conversion from miles to kilometers) Write a program that displays the following
                             table (note that 1 mile is 1.609 kilometers):

                             Miles         Kilometers

                             1             1.609
                             2             3.218
                             ...
                             9             14.481
                             10            16.090


                      4.5    (Conversion from kilograms to pounds) Write a program that displays the follow-
                             ing two tables side by side (note that 1 kilogram is 2.2 pounds):

                             Kilograms       Pounds              Pounds            Kilograms

                             1               2.2                 20                9.09
                             3               6.6                 25                11.36
                             ...
                             197             433.4               510               231.82
                             199             437.8               515               234.09


                      4.6    (Conversion from miles to kilometers) Write a program that displays the following
                             two tables side by side (note that 1 mile is 1.609 kilometers):

                             Miles         Kilometers       Kilometers            Miles

                             1             1.609            20                    12.430
                             2             3.218            25                    15.538
                             ...
                             9             14.481           60                    37.290
                             10            16.090           65                    40.398


                      4.7** (Financial application: computing future tuition) Suppose that the tuition for a
                             university is $10,000 this year and increases 5% every year. Write a program that
                             computes the tuition in ten years and the total cost of four years’ worth of tuition
                             starting ten years from now.
                      4.8    (Finding the highest score) Write a program that prompts the user to enter the
                             number of students and each student’s name and score, and finally displays the
                             name of the student with the highest score.
                      4.9* (Finding the two highest scores) Write a program that prompts the user to
                             enter the number of students and each student’s name and score, and finally
                             displays the student with the highest score and the student with the second-
                             highest score.
                      4.10 (Finding numbers divisible by 5 and 6) Write a program that displays all the num-
                             bers from 100 to 1000, ten per line, that are divisible by 5 and 6.
                      4.11 (Finding numbers divisible by 5 or 6, but not both) Write a program that displays
                             all the numbers from 100 to 200, ten per line, that are divisible by 5 or 6, but not
                             both.
                      4.12 (Finding the smallest n such that n2 7 12,000) Use a while loop to find the small-
                             est integer n such that n2 is greater than 12,000.
                      4.13 (Finding the largest n such that n3 6 12,000) Use a while loop to find the largest
                             integer n such that n3 is less than 12,000.
                      4.14* (Displaying the ACSII character table) Write a program that prints the characters
                             in the ASCII character table from ‘!' to ‘~'. Print ten characters per line. The
                             ASCII table is shown in Appendix B.
                                                                                                            Programming Exercises 149
Section 4.8
4.15* (Computing the greatest common divisor) Another solution for Listing 4.8 to find
       the greatest common divisor of two integers n1 and n2 is as follows: First find d
       to be the minimum of n1 and n2, then check whether d, d-1, d-2, Á , 2, or 1 is
       a divisor for both n1 and n2 in this order. The first such common divisor is the
       greatest common divisor for n1 and n2. Write a program that prompts the user to
       enter two positive integers and displays the gcd.
4.16** (Finding the factors of an integer) Write a program that reads an integer and dis-
       plays all its smallest factors in increasing order. For example, if the input integer
       is 120, the output should be as follows: 2, 2, 2, 3, 5.
4.17** (Displaying pyramid) Write a program that prompts the user to enter an integer
       from 1 to 15 and displays a pyramid, as shown in the following sample run:


 Enter the number of lines: 7
                                                          1
                                                     2    1   2
                                                3    2    1   2       3
                                            4   3    2    1   2       3    4
                                   5        4   3    2    1   2       3    4    5
                               6   5        4   3    2    1   2       3    4    5       6
                          7    6   5        4   3    2    1   2       3    4    5       6   7


4.18* (Printing four patterns using loops) Use nested loops that print the following pat-
          terns in four separate programs:
          Pattern I                Pattern II                 Pattern III                       Pattern IV
          1                        1 2 3 4 5 6                                      1           1 2 3 4 5 6
          1 2                      1 2 3 4 5                                    2 1                 1 2 3 4 5
          1 2 3                    1 2 3 4                                 3 2 1                      1 2 3 4
          1 2 3 4                  1 2 3                                  4 3 2 1                         1 2 3
          1 2 3 4 5                1 2                            5 4 3 2 1                                1 2
          1 2 3 4 5 6              1                          6 5 4 3 2 1                                       1

4.19** (Printing numbers in a pyramid pattern) Write a nested for loop that prints the
          following output:
                                                         1
                                                 1        2       1
                                        1        2       4        2         1
                              1         2        4        8       4         2           1
                      1       2         4        8       16       8         4           2       1
                  1   2       4         8       16       32   16            8           4       2     1
              1   2   4       8        16       32       64   32           16           8       4     2     1
      1       2   4   8       16       32       64   128      64           32       16          8      4     2      1

4.20* (Printing prime numbers between 2 and 1000) Modify Listing 4.14 to print all the
          prime numbers between 2 and 1000, inclusive. Display eight prime numbers per line.

Comprehensive
4.21** (Financial application: comparing loans with various interest rates) Write a pro-
          gram that lets the user enter the loan amount and loan period in number of years
150 Chapter 4 Loops
                                      and displays the monthly and total payments for each interest rate starting from
                                      5% to 8%, with an increment of 1/8. Here is a sample run:


                             Loan Amount: 10000
                             Number of Years: 5
                             Interest Rate                            Monthly Payment             Total Payment
                             5%                                      188.71                       11322.74
                             5.125%                                  189.28                       11357.13
                             5.25%                                   189.85                       11391.59
                             ...
                             7.875%                                  202.17                       12129.97
                             8.0%                                    202.76                       12165.83



                                   For the formula to compute monthly payment, see Listing 2.8, ComputeLoan.java.
                            4.22** (Financial application: loan amortization schedule) The monthly payment for a
                                   given loan pays the principal and the interest. The monthly interest is computed
                                   by multiplying the monthly interest rate and the balance (the remaining princi-
    Video Note
                                   pal). The principal paid for the month is therefore the monthly payment minus the
    Display loan schedule
                                   monthly interest. Write a program that lets the user enter the loan amount, num-
                                   ber of years, and interest rate and displays the amortization schedule for the loan.
                                   Here is a sample run:


                             Loan Amount: 10000
                             Number of Years: 1
                             Annual Interest Rate: 7%

                             Monthly Payment: 865.26
                             Total Payment: 10383.21
                             Payment#                   Interest                Principal                Balance
                             1                          58.33                   806.93                   9193.07
                             2                          53.62                   811.64                   8381.43
                             ...
                             11                         10.0                    855.26                   860.27
                             12                         5.01                    860.25                   0.01



                              Note
                               The balance after the last payment may not be zero. If so, the last payment should be the normal
                               monthly payment plus the final balance.

                                      Hint: Write a loop to print the table. Since the monthly payment is the same for
                                      each month, it should be computed before the loop. The balance is initially the
                                      loan amount. For each iteration in the loop, compute the interest and principal,
                                      and update the balance. The loop may look like this:

                                      for (i = 1; i <= numberOfYears * 12; i++) {
                                        interest = monthlyInterestRate * balance;
                                        principal = monthlyPayment - interest;
                                        balance = balance - principal;
                                        System.out.println(i + "\t\t" + interest
                                          + "\t\t" + principal + "\t\t" + balance);
                                      }
                                                                                        Programming Exercises 151

4.23* (Obtaining more accurate results) In computing the following series, you will obtain
         more accurate results by computing from right to left rather than from left to right:
                                           1    1            1
                                           1 ++ + Á +
                                           2    3            n
         Write a program that compares the results of the summation of the preceding
         series, computing from left to right and from right to left with n = 50000.
4.24*    (Summing a series) Write a program to sum the following series:
                         1  3 5 7  9    11       95   97
                           + + + +    +    + Á +    +
                         3  5 7 9  11   13       97   99
4.25** (Computing p) You can approximate p by using the following series:
                                    1  1 1 1   1          1        1
               p = 4a1 -              + - + -    + Á +        -        b
                                    3  5 7 9  11       2i - 1   2i + 1
       Write a program that displays the p value for i = 10000, 20000, Á , and
       100000.
4.26** (Computing e) You can approximate e using the following series:
                                           1    1    1    1        1
                                e = 1 +       +    +    +    + Á +
                                           1!   2!   3!   4!       i!
       Write a program that displays the e value for i = 10000, 20000, Á , and
       100000.
                                                                1         1
       (Hint: Since i! = i * (i - 1) * Á * 2 * 1, then is
                                                                i! i(i - 1)!
       Initialize e and item to be 1 and keep adding a new item to e. The new item is
       the previous item divided by i for i = 2, 3, 4, Á .)
4.27** (Displaying leap years) Write a program that displays all the leap years, ten per
       line, in the twenty-first century (from 2001 to 2100).
4.28** (Displaying the first days of each month) Write a program that prompts the user to
       enter the year and first day of the year, and displays the first day of each month in
       the year on the console. For example, if the user entered the year 2005, and 6 for
       Saturday, January 1, 2005, your program should display the following output
       (note that Sunday is 0):

         January 1, 2005 is Saturday
         ...
         December 1, 2005 is Thursday

4.29** (Displaying calendars) Write a program that prompts the user to enter the year and
         first day of the year and displays the calendar table for the year on the console. For
         example, if the user entered the year 2005, and 6 for Saturday, January 1, 2005,
         your program should display the calendar for each month in the year, as follows:

                                                  January 2005

                           Sun        Mon        Tue   Wed       Thu   Fri   Sat
                                                                              1
                                2      3          4     5         6     7     8
                                9     10         11    12        13    14    15
                               16     17         18    19        20    21    22
                               23     24         25    26        27    28    29
                               30     31
                         ...
152 Chapter 4 Loops
                                                                 December 2005

                                                 Sun    Mon     Tue    Wed     Thu     Fri   Sat
                                                                                1       2     3
                                                  4      5       6       7      8       9    10
                                                 11     12      13      14     15     16     17
                                                 18     19      20      21     22     23     24
                                                 25     26      27      28     29     30     31


                      4.30* (Financial application: compound value) Suppose you save $100 each month into
                               a savings account with the annual interest rate 5%. So, the monthly interest rate is
                               0.05 / 12 = 0.00417. After the first month, the value in the account becomes

                                                       100 * (1 + 0.00417) = 100.417

                               After the second month, the value in the account becomes

                                              (100 + 100.417) * (1 + 0.00417) = 201.252

                               After the third month, the value in the account becomes

                                              (100 + 201.252) * (1 + 0.00417) = 302.507

                               and so on.
                               Write a program that prompts the user to enter an amount (e.g., 100), the annual
                               interest rate (e.g., 5), and the number of months (e.g., 6) and displays the amount
                               in the savings account after the given month.
                      4.31*    (Financial application: computing CD value) Suppose you put $10,000 into a CD
                               with an annual percentage yield of 5.75%. After one month, the CD is worth

                                                10000 + 10000 * 5.75 / 1200 = 10047.91

                               After two months, the CD is worth

                                            10047.91 + 10047.91 * 5.75 / 1200 = 10096.06

                               After three months, the CD is worth

                                            10096.06 + 10096.06 * 5.75 / 1200 = 10144.43

                               and so on.
                               Write a program that prompts the user to enter an amount (e.g., 10000), the annual
                               percentage yield (e.g., 5.75), and the number of months (e.g., 18) and displays a
                               table as shown in the sample run.


                       Enter the initial deposit amount: 10000
                       Enter annual percentage yield: 5.75
                       Enter maturity period (number of months): 18
                       Month                      CD Value
                       1                          10047.91
                       2                          10096.06
                       ...
                       17                         10846.56
                       18                         10898.54
                                                                                          Programming Exercises 153

4.32** (Game: lottery) Revise Listing 3.9, Lottery.java, to generate a lottery of a two-
        digit number. The two digits in the number are distinct.
        (Hint: Generate the first digit. Use a loop to continuously generate the second
        digit until it is different from the first digit.)
4.33** (Perfect number) A positive integer is called a perfect number if it is equal to the
        sum of all of its positive divisors, excluding itself. For example, 6 is the first perfect
        number because 6 = 3 + 2 + 1. The next is 28 = 14 + 7 + 4 + 2 + 1. There are four
        perfect numbers less than 10000. Write a program to find all these four numbers.
4.34*** (Game: scissor, rock, paper) Exercise 3.17 gives a program that plays the
        scissor-rock-paper game. Revise the program to let the user continuously play
        until either the user or the computer wins more than two times.
4.35*      (Summation) Write a program that computes the following summation.
                     1               1                 1                          1
                             +                  +             + Á +
                 1 + 22          22 + 23            23 + 24               2624 + 2625

4.36** (Business application: checking ISBN) Use loops to simplify Exercise 3.19.
4.37** (Decimal to binary) Write a program that prompts the user to enter a decimal
           integer and displays its corresponding binary value. Don’t use Java’s
           Integer.toBinaryString(int) in this program.
4.38**     (Decimal to hex) Write a program that prompts the user to enter a decimal integer
           and displays its corresponding hexadecimal value. Don’t use Java’s
           Integer.toHexString(int) in this program.
4.39*      (Financial application: finding the sales amount) You have just started a sales
           job in a department store. Your pay consists of a base salary and a commission.
           The base salary is $5,000. The scheme shown below is used to determine the
           commission rate.
                         Sales Amount                         Commission Rate

                         $0.01–$5,000                               8 percent
                         $5,000.01–$10,000                         10 percent
                         $10,000.01 and above                      12 percent

           Your goal is to earn $30,000 a year. Write a program that finds out the minimum
           amount of sales you have to generate in order to make $30,000.
4.40       (Simulation: head or tail) Write a program that simulates flipping a coin one
           million times and displays the number of heads and tails.
4.41**     (Occurrence of max numbers) Write a program that reads integers, finds the
           largest of them, and counts its occurrences. Assume that the input ends with
           number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the
           largest is 5 and the occurrence count for 5 is 4.
           (Hint: Maintain two variables, max and count. max stores the current max num-
           ber, and count stores its occurrences. Initially, assign the first number to max
           and 1 to count. Compare each subsequent number with max. If the number is
           greater than max, assign it to max and reset count to 1. If the number is equal to
           max, increment count by 1.)


 Enter numbers: 3 5 2 5 5 5 0
 The largest number is 5
 The occurrence count of the largest number is 4
154 Chapter 4 Loops

                      4.42* (Financial application: finding the sales amount) Rewrite Exercise 4.39 as follows:
                              ■   Use a for loop instead of a do-while loop.
                              ■   Let the user enter COMMISSION_SOUGHT instead of fixing it as a constant.
                      4.43* (Simulation: clock countdown) Write a program that prompts the user to enter the
                              number of seconds, displays a message at every second, and terminates when the
                              time expires. Here is a sample run:

                       Enter the number of second: 3
                       2 seconds remaining
                       1 second remaining
                       Stopped


                      4.44** (Monte Carlo simulation) A square is divided into four smaller regions as shown
                              below in (a). If you throw a dart into the square 1000000 times, what is the prob-
                              ability for a dart to fall into an odd-numbered region? Write a program to simulate
                              the process and display the result.
                              (Hint: Place the center of the square in the center of a coordinate system, as
                              shown in (b). Randomly generate a point in the square and count the number of
                              times a point falls into an odd-numbered region.)



                                                                2                      2
                                                        3                      3
                                              1
                                                                     1
                                                            4                      4


                                                  (a)                    (b)

                      4.45* (Math: combinations) Write a program that displays all possible combinations for
                              picking two numbers from integers 1 to 7. Also display the total number of all
                              combinations.

                       1 2
                       1 3
                       ...
                       ...


                      4.46* (Computer architecture: bit-level operations) A short value is stored in 16 bits.
                              Write a program that prompts the user to enter a short integer and displays the 16
                              bits for the integer. Here are sample runs:

                       Enter an integer: 5
                       The bits are 0000000000000101



                       Enter an integer: -5
                       The bits are 1111111111111011


                              (Hint: You need to use the bitwise right shift operator (>>) and the bitwise AND
                              operator (&), which are covered in Supplement III.D on the Companion Website.)
                                                         CHAPTER 5
METHODS
Objectives
■   To define methods (§5.2).
■   To invoke methods with a return value (§5.3).
■   To invoke methods without a return value (§5.4).
■   To pass arguments by value (§5.5).
■   To develop reusable code that is modular, easy to read,
    easy to debug, and easy to maintain (§5.6).
■   To write a method that converts decimals to
    hexadecimals (§5.7).
■   To use method overloading and understand ambiguous
    overloading (§5.8).
■   To determine the scope of variables (§5.9).
■   To solve mathematics problems using the methods
    in the Math class (§§5.10–5.11).
■   To apply the concept of method abstraction in
    software development (§5.12).
■   To design and implement methods using stepwise
    refinement (§5.12).
156 Chapter 5 Methods

                    5.1 Introduction
problem             Suppose that you need to find the sum of integers from 1 to 10, from 20 to 30, and from 35
                    to 45, respectively. You may write the code as follows:

                       int sum = 0;
                       for (int i = 1; i <= 10; i++)
                         sum += i;
                       System.out.println("Sum from 1 to 10 is " + sum);

                       sum = 0;
                       for (int i = 20; i <= 30; i++)
                         sum += i;
                       System.out.println("Sum from 20 to 30 is " + sum);

                       sum = 0;
                       for (int i = 35; i <= 45; i++)
                         sum += i;
                       System.out.println("Sum from 35 to 45 is " + sum);

                    You may have observed that computing sum from 1 to 10, from 20 to 30, and from 35 to 45
                    are very similar except that the starting and ending integers are different. Wouldn’t it be nice
                    if we could write the common code once and reuse it without rewriting it? We can do so by
why methods?        defining a method. The method is for creating reusable code.
                       The preceding code can be simplified as follows:

define sum method       1 public static int sum(int i1, int i2) {
                        2   int sum = 0;
                        3   for (int i = i1; i <= i2; i++)
                        4     sum += i;
                        5
                        6   return sum;
                        7 }
                        8
main method             9 public static void main(String[] args) {
invoke sum             10   System.out.println("Sum from 1 to 10 is " + sum(1, 10));
                       11   System.out.println("Sum from 20 to 30 is " + sum(20, 30));
                       12   System.out.println("Sum from 35 to 45 is " + sum(35, 45));
                       13 }

                    Lines 1–7 define the method named sum with two parameters i and j. The statements in the
                    main method invoke sum(1, 10) to compute the sum from 1 to 10, sum(20, 30) to com-
                    pute the sum from 20 to 30, and sum(35, 45) to compute the sum from 35 to 45.
                       A method is a collection of statements grouped together to perform an operation. In earlier
                    chapters you have used predefined methods such as System.out.println, JOption-
                    Pane.showMessageDialog, JOptionPane.showInputDialog, Integer.parseInt,
                    Double.parseDouble, System.exit, Math.pow, and Math.random. These methods are
                    defined in the Java library. In this chapter, you will learn how to define your own methods and
                    apply method abstraction to solve complex problems.


                    5.2 Defining a Method
                    The syntax for defining a method is as follows:

                       modifier returnValueType methodName(list of parameters) {
                         // Method body;
                       }
                                                                                                     5.2 Defining a Method 157
Let’s look at a method created to find which of two integers is bigger. This method, named
max, has two int parameters, num1 and num2, the larger of which is returned by the method.
Figure 5.1 illustrates the components of this method.

                                             Define a method                                           Invoke a method
                                             return value     method  formal
                                 modifier        type          name parameters

               method        public static int max(int num1, int num2) {                           int z = max(x, y);
               header
                                 int result;
               method
                                                                   parameter list    method                 actual parameters
               body              if (num1 > num2)
                                                                                    signature                  (arguments)
                                   result = num1;
                                 else
                                   result = num2;

                                 return result;                   return value
                             }

FIGURE 5.1 A method definition consists of a method header and a method body.

   The method header specifies the modifiers, return value type, method name, and                               method header
parameters of the method. The static modifier is used for all the methods in this chapter. The
reason for using it will be discussed in Chapter 8, “Objects and Classes.”
   A method may return a value. The returnValueType is the data type of the value the
method returns. Some methods perform desired operations without returning a value. In this
case, the returnValueType is the keyword void. For example, the returnValueType is
void in the main method, as well as in System.exit, System.out.println, and
JOptionPane.showMessageDialog. If a method returns a value, it is called a value-                               value-returning method
returning method, otherwise it is a void method.                                                                void method
   The variables defined in the method header are known as formal parameters or simply
parameters. A parameter is like a placeholder. When a method is invoked, you pass a value to the                parameter
parameter. This value is referred to as an actual parameter or argument. The parameter list                     argument
refers to the type, order, and number of the parameters of a method. The method name and the                    parameter list
parameter list together constitute the method signature. Parameters are optional; that is, a method             method signature
may contain no parameters. For example, the Math.random() method has no parameters.
   The method body contains a collection of statements that define what the method does.
The method body of the max method uses an if statement to determine which number is
larger and return the value of that number. In order for a value-returning method to return a
result, a return statement using the keyword return is required. The method terminates when
a return statement is executed.

      Note
      In certain other languages, methods are referred to as procedures and functions. A value-returning
      method is called a function; a void method is called a procedure.

      Caution
      In the method header, you need to declare a separate data type for each parameter. For instance,
      max(int num1, int num2) is correct, but max(int num1, num2) is wrong.


      Note
      We say “define a method” and “declare a variable.” We are making a subtle distinction here. A             define vs. declare
      definition defines what the defined item is, but a declaration usually involves allocating memory
      to store data for the declared item.
158 Chapter 5 Methods

                           5.3 Calling a Method
                           In creating a method, you define what the method is to do. To use a method, you have to call
                           or invoke it. There are two ways to call a method, depending on whether the method returns a
                           value or not.
                              If the method returns a value, a call to the method is usually treated as a value. For example,

                              int larger = max(3, 4);

                           calls max(3, 4) and assigns the result of the method to the variable larger. Another exam-
                           ple of a call that is treated as a value is

                              System.out.println(max(3, 4));

                           which prints the return value of the method call max(3, 4).
                             If the method returns void, a call to the method must be a statement. For example, the
                           method println returns void. The following call is a statement:

                              System.out.println("Welcome to Java!");


                                 Note
                                 A value-returning method can also be invoked as a statement in Java. In this case, the caller sim-
                                 ply ignores the return value. This is not often done but is permissible if the caller is not interested
                                 in the return value.

                           When a program calls a method, program control is transferred to the called method. A called
                           method returns control to the caller when its return statement is executed or when its method-
                           ending closing brace is reached.
                              Listing 5.1 shows a complete program that is used to test the max method.

                           LISTING 5.1 TestMax.java
Video Note                  1 public class TestMax {
Define/invoke max method
                            2   /** Main method */
main method                 3   public static void main(String[] args) {
                            4     int i = 5;
                            5     int j = 2;
invoke max                  6     int k = max(i, j) ;
                            7     System.out.println("The maximum between " + i +
                            8       " and " + j + " is " + k);
                            9   }
                           10
                           11   /** Return the max between two numbers */
define method              12   public static int max(int num1, int num2) {
                           13     int result;
                           14
                           15     if (num1 > num2)
                           16       result = num1;
                           17     else
                           18       result = num2;
                           19
                           20     return result;
                           21   }
                           22 }


                               The maximum between 5 and 2 is 5
                                                                                                             5.3 Calling a Method 159

                      line#          i         j          k         num1           num2             result
                      4              5
                      5                        2
                      12                                            5              2
 Invoking max         13                                                                            undefined
                      16                                                                            5
                      6                                   5



This program contains the main method and the max method. The main method is just like                            main method
any other method except that it is invoked by the JVM.
   The main method’s header is always the same. Like the one in this example, it includes the
modifiers public and static, return value type void, method name main, and a parameter
of the String[] type. String[] indicates that the parameter is an array of String, a sub-
ject addressed in Chapter 6.
   The statements in main may invoke other methods that are defined in the class that con-
tains the main method or in other classes. In this example, the main method invokes max(i,
j), which is defined in the same class with the main method.
   When the max method is invoked (line 6), variable i’s value 5 is passed to num1, and vari-                      max method
able j’s value 2 is passed to num2 in the max method. The flow of control transfers to the max
method. The max method is executed. When the return statement in the max method is exe-
cuted, the max method returns the control to its caller (in this case the caller is the main
method). This process is illustrated in Figure 5.2.


                                                                pass the value i

                                                                          pass the value j


        public static void main(String[] args) {                          public static int max(int num1, int num2) {
          int i = 5;                                                        int result;
          int j = 2;
          int k = max(i, j);                                                  if (num1 > num2)
                                                                                result = num1;
            System.out.println(                                               else
              "The maximum between " + i +                                      result = num2;
              " and " + j + " is " + k);
        }                                                                     return result;
                                                                          }


FIGURE 5.2 When the max method is invoked, the flow of control transfers to it. Once the max method is finished, it
returns control back to the caller.



     Caution
      A return statement is required for a value-returning method. The method shown below in (a) is
      logically correct, but it has a compile error because the Java compiler thinks it possible that this
      method returns no value.
      To fix this problem, delete if (n < 0) in (a), so that the compiler will see a return statement
      to be reached regardless of how the if statement is evaluated.
160 Chapter 5 Methods

                  public static int sign(int n) {                           public static int sign(int n) {
                    if (n > 0)                               Should be        if (n > 0)
                      return 1;                                                 return 1;
                    else if (n == 0)                                          else if (n == 0)
                      return 0;                                                 return 0;
                    else if (n < 0)                                           else
                      return –1;                                                return –1;
                  }                                                         }

                                  (a)                                                          (b)



                                     Note
reusing method                       Methods enable code sharing and reuse. The max method can be invoked from any class besides
                                     TestMax. If you create a new class, you can invoke the max method using Class-
                                     Name.methodName (i.e., TestMax.max).


                              5.3.1 Call Stacks
stack                         Each time a method is invoked, the system stores parameters and variables in an area of mem-
                              ory known as a stack, which stores elements in last-in, first-out fashion. When a method calls
                              another method, the caller’s stack space is kept intact, and new space is created to handle the
                              new method call. When a method finishes its work and returns to its caller, its associated
                              space is released.
                                 Understanding call stacks helps you to comprehend how methods are invoked. The vari-
                              ables defined in the main method are i, j, and k. The variables defined in the max method are
                              num1, num2, and result. The variables num1 and num2 are defined in the method signature
                              and are parameters of the method. Their values are passed through method invocation. Figure
                              5.3 illustrates the variables in the stack.

                         Space required for              Space required for
                         the max method                  the max method
                                                                  result: 5
                                        num2: 2                       num2: 2
                                        num1: 5                       num1: 5
   Space required for    Space required for              Space required for            Space required for
   the main method       the main method                 the main method               the main method
                k:                        k:                              k:                        k: 5          Stack is empty
                j: 2                      j: 2                            j: 2                      j: 2
                i: 5                      i: 5                            i: 5                      i: 5
  (a) The main          (b) The max                     (c) The max method            (d) The max method is      (e) The main
  method is invoked.    method is invoked.              is being executed.            finished and the return    method is finished.
                                                                                      value is sent to k.

FIGURE 5.3 When the max method is invoked, the flow of control transfers to the max method. Once the max method is
finished, it returns control back to the caller.


                              5.4 void Method Example
                              The preceding section gives an example of a value-returning method. This section shows how
                              to define and invoke a void method. Listing 5.2 gives a program that defines a method named
Video Note
Use void method               printGrade and invokes it to print the grade for a given score.

                              LISTING 5.2 TestVoidMethod.java
                               1 public class TestVoidMethod {
main method                    2   public static void main(String[] args) {
                               3     System.out.print("The grade is ");
                                                                              5.4 void Method Example 161
 4     printGrade(78.5);                                                                     invoke printGrade
 5
 6     System.out.print("The grade is ");
 7     printGrade(59.5);                                                                     printGrade method
 8   }
 9
10   public static void printGrade(double score) {
11     if (score >= 90.0) {
12       System.out.println('A');
13     }
14     else if (score >= 80.0) {
15       System.out.println('B');
16     }
17     else if (score >= 70.0) {
18       System.out.println('C');
19     }
20     else if (score >= 60.0) {
21       System.out.println('D');
22     }
23     else {
24       System.out.println('F');
25     }
26   }
27 }



    The grade is C
    The grade is F



The printGrade method is a void method. It does not return any value. A call to a void       invoke void method
method must be a statement. So, it is invoked as a statement in line 4 in the main method.
Like any Java statement, it is terminated with a semicolon.
   To see the differences between a void and a value-returning method, let us redesign the   void vs. value-returned
printGrade method to return a value. The new method, which we call getGrade, returns
the grade as shown in Listing 5.3.

LISTING 5.3 TestReturnGradeMethod.java
 1 public class TestReturnGradeMethod {
 2   public static void main(String[] args) {                                                main method
 3     System.out.print("The grade is " + getGrade(78.5) );
 4     System.out.print("\nThe grade is " + getGrade(59.5) );                                invoke printGrade
 5   }
 6
 7   public static char getGrade(double score) {                                             printGrade method
 8     if (score >= 90.0)
 9       return 'A';
10     else if (score >= 80.0)
11       return 'B';
12     else if (score >= 70.0)
13       return 'C';
14     else if (score >= 60.0)
15       return 'D';
16     else
17       return 'F';
18   }
19 }
162 Chapter 5 Methods

                                  The grade is C
                                  The grade is F




                              The getGrade method defined in lines 7–18 returns a character grade based on the numeric
                              score value. The caller invokes this method in lines 3–4.
                                 The getGrade method can be invoked by a caller wherever a character may appear. The
                              printGrade method does not return any value. It must be also invoked as a statement.


                                   Note
return in void method               A return statement is not needed for a void method, but it can be used for terminating the
                                    method and returning to the method’s caller. The syntax is simply

                                    return;

                                    This is not often done, but sometimes it is useful for circumventing the normal flow of control in
                                    a void method. For example, the following code has a return statement to terminate the method
                                    when the score is invalid.

                                    public static void printGrade(double score) {
                                      if (score < 0 || score > 100) {
                                        System.out.println("Invalid score");
                                        return;
                                      }

                                        if (score >= 90.0) {
                                          System.out.println('A');
                                        }
                                        else if (score >= 80.0) {
                                          System.out.println('B');
                                        }
                                        else if (score >= 70.0) {
                                          System.out.println('C');
                                        }
                                        else if (score >= 60.0) {
                                          System.out.println('D');
                                        }
                                        else {
                                          System.out.println('F');
                                        }
                                    }


                              5.5 Passing Parameters by Values
                              The power of a method is its ability to work with parameters. You can use println to print
                              any string and max to find the maximum between any two int values. When calling a
                              method, you need to provide arguments, which must be given in the same order as their
parameter order association   respective parameters in the method signature. This is known as parameter order association.
                              For example, the following method prints a message n times:
                                 public static void nPrintln(String message, int n) {
                                   for (int i = 0; i < n; i++)
                                     System.out.println(message);
                                 }

                              You can use nPrintln("Hello", 3) to print "Hello" three times. The nPrintln("Hello",
                              3) statement passes the actual string parameter "Hello" to the parameter message; passes 3 to n;
                                                                                  5.5 Passing Parameters by Values 163
and prints "Hello" three times. However, the statement nPrintln(3, "Hello") would be
wrong. The data type of 3 does not match the data type for the first parameter, message, nor does
the second parameter, "Hello", match the second parameter, n.

      Caution
      The arguments must match the parameters in order, number, and compatible type, as defined in
      the method signature. Compatible type means that you can pass an argument to a parameter
      without explicit casting, such as passing an int value argument to a double value parameter.

When you invoke a method with a parameter, the value of the argument is passed to the para-
meter. This is referred to as pass-by-value. If the argument is a variable rather than a literal     pass-by-value
value, the value of the variable is passed to the parameter. The variable is not affected, regard-
less of the changes made to the parameter inside the method. As shown in Listing 5.4, the
value of x (1) is passed to the parameter n to invoke the increment method (line 5). n is
incremented by 1 in the method (line 10), but x is not changed no matter what the method
does.

LISTING 5.4 Increment.java
 1 public class Increment {
 2   public static void main(String[] args) {
 3     int x = 1;
 4     System.out.println("Before the call, x is " + x);
 5     increment(x);                                                                                 invoke increment
 6     System.out.println("after the call, x is " + x);
 7   }
 8
 9   public static void increment(int n) {
10     n++;                                                                                          increment n
11     System.out.println("n inside the method is " + n);
12   }
13 }



    Before the call, x is 1
    n inside the method is 2
    after the call, x is 1


Listing 5.5 gives another program that demonstrates the effect of passing by value. The pro-
gram creates a method for swapping two variables. The swap method is invoked by passing
two arguments. Interestingly, the values of the arguments are not changed after the method is
invoked.

LISTING 5.5 TestPassByValue.java
 1 public class TestPassByValue {
 2   /** Main method */
 3   public static void main(String[] args) {
 4     // Declare and initialize variables
 5     int num1 = 1;
 6     int num2 = 2;
 7
 8     System.out.println("Before invoking the swap method, num1 is " +
 9       num1 + " and num2 is " + num2);
10
11     // Invoke the swap method to attempt to swap two variables
12     swap(num1, num2);                                                                             false swap
164 Chapter 5 Methods
                                13
                                14         System.out.println("After invoking the swap method, num1 is " +
                                15           num1 + " and num2 is " + num2);
                                16     }
                                17
                                18     /** Swap two variables */
                                19     public static void swap(int n1, int n2) {
                                20       System.out.println("\tInside the swap method");
                                21       System.out.println("\t\tBefore swapping n1 is " + n1
                                22         + " n2 is " + n2);
                                23
                                24         // Swap n1 with n2
                                25         int temp = n1;
                                26         n1 = n2;
                                27         n2 = temp;
                                28
                                29         System.out.println("\t\tAfter swapping n1 is " + n1
                                30           + " n2 is " + n2);
                                31     }
                                32 }


                                      Before invoking the swap method, num1 is 1 and num2 is 2
                                        Inside the swap method
                                          Before swapping n1 is 1 n2 is 2
                                          After swapping n1 is 2 n2 is 1
                                      After invoking the swap method, num1 is 1 and num2 is 2


                                Before the swap method is invoked (line 12), num1 is 1 and num2 is 2. After the swap method
                                is invoked, num1 is still 1 and num2 is still 2. Their values have not been swapped. As shown
                                in Figure 5.4, the values of the arguments num1 and num2 are passed to n1 and n2, but n1 and
                                n2 have their own memory locations independent of num1 and num2. Therefore, changes in
                                n1 and n2 do not affect the contents of num1 and num2.
                                    Another twist is to change the parameter name n1 in swap to num1. What effect does this
                                have? No change occurs, because it makes no difference whether the parameter and the argu-
                                ment have the same name. The parameter is a variable in the method with its own memory
                                space. The variable is allocated when the method is invoked, and it disappears when the
                                method is returned to its caller.

                                                    The values of num1 and num2 are
                                                    passed to n1 and n2. Executing swap
                                                    does not affect num1 and num2.


                                        Space required for the
                                        swap method
                                                     temp:
                                                        n2: 2
                                                        n1: 1
             Space required for the     Space required for the          Space required for the
             main method                main method                     main method              Stack is empty

                          num2: 2                    num2: 2                         num2: 2
                          num1: 1                    num1: 1                         num1: 1
             The main method           The swap method                 The swap method           The main method
             is invoked.               is invoked.                     is finished.              is finished.

FIGURE 5.4     The values of the variables are passed to the parameters of the method.
                                                                                                  5.6 Modularizing Code 165

     Note
      For simplicity, Java programmers often say passing an argument x to a parameter y, which actu-
      ally means passing the value of x to y.



5.6 Modularizing Code
Methods can be used to reduce redundant code and enable code reuse. Methods can also be
used to modularize code and improve the quality of the program.
                                                                                                         Video Note
   Listing 4.8 gives a program that prompts the user to enter two integers and displays their            Modularize code
greatest common divisor. You can rewrite the program using a method, as shown in Listing 5.6.

LISTING 5.6 GreatestCommonDivisorMethod.java
 1 import java.util.Scanner;
 2
 3 public class GreatestCommonDivisorMethod {
 4   /** Main method */
 5   public static void main(String[] args) {
 6     // Create a Scanner
 7     Scanner input = new Scanner(System.in);
 8
 9     // Prompt the user to enter two integers
10     System.out.print("Enter first integer: ");
11     int n1 = input.nextInt();
12     System.out.print("Enter second integer: ");
13     int n2 = input.nextInt();
14
15     System.out.println("The greatest common divisor for " + n1 +
16       " and " + n2 + " is " + gcd(n1, n2) );                                                          invoke gcd
17   }
18
19   /** Return the gcd of two integers */
20   public static int gcd(int n1, int n2) {                                                             compute gcd
21     int gcd = 1; // Initial gcd is 1
22     int k = 2; // Possible gcd
23
24     while (k <= n1 && k <= n2) {
25       if (n1 % k == 0 && n2 % k == 0)
26         gcd = k; // Update gcd
27       k++;
28     }
29
30     return gcd; // Return gcd                                                                         return gcd
31   }
32 }



    Enter first integer: 45
    Enter second integer: 75
    The greatest common divisor for 45 and 75 is 15



By encapsulating the code for obtaining the gcd in a method, this program has several
advantages:
   1. It isolates the problem for computing the gcd from the rest of the code in the main
      method. Thus, the logic becomes clear and the program is easier to read.
166 Chapter 5 Methods
                             2. The errors on computing gcd are confined in the gcd method, which narrows the scope
                                of debugging.
                             3. The gcd method now can be reused by other programs.
                           Listing 5.7 applies the concept of code modularization to improve Listing 4.14, PrimeNum-
                           ber.java.

                           LISTING 5.7 PrimeNumberMethod.java
                            1 public class PrimeNumberMethod {
                            2   public static void main(String[] args) {
                            3     System.out.println("The first 50 prime numbers are \n");
invoke printPrimeNumbers    4     printPrimeNumbers(50);
                            5   }
                            6
printPrimeNumbers           7   public static void printPrimeNumbers(int numberOfPrimes) {
  method                    8     final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
                            9     int count = 0; // Count the number of prime numbers
                           10     int number = 2; // A number to be tested for primeness
                           11
                           12     // Repeatedly find prime numbers
                           13     while (count < numberOfPrimes) {
                           14       // Print the prime number and increase the count
invoke isPrime             15       if (isPrime(number) ) {
                           16         count++; // Increase the count
                           17
                           18         if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
                           19           // Print the number and advance to the new line
                           20           System.out.printf("%-5s\n", number);
                           21         }
                           22         else
                           23           System.out.printf("%-5s", number);
                           24       }
                           25
                           26       // Check whether the next number is prime
                           27       number++;
                           28     }
                           29   }
                           30
                           31   /** Check whether number is prime */
isPrime method             32   public static boolean isPrime(int number) {
                           33     for (int divisor = 2; divisor <= number / 2; divisor++) {
                           34       if (number % divisor == 0) { // If true, number is not prime
                           35         return false; // number is not a prime
                           36       }
                           37     }
                           38
                           39     return true; // number is prime
                           40   }
                           41 }



                               The first 50 prime numbers are
                               2     3     5     7     11     13    17    19    23    29
                               31    37    41    43    47     53    59    61    67    71
                               73    79    83    89    97     101   103   107   109   113
                               127   131   137   139   149    151   157   163   167   173
                               179   181   191   193   197    199   211   223   227   229
                                                 5.7 Problem: Converting Decimals to Hexadecimals 167
We divided a large problem into two subproblems. As a result, the new program is easier to
read and easier to debug. Moreover, the methods printPrimeNumbers and isPrime can be
reused by other programs.


5.7 Problem: Converting Decimals to Hexadecimals
Hexadecimals are often used in computer systems programming. Appendix F introduces
number systems. This section presents a program that converts a decimal to a hexadecimal.
    To convert a decimal number d to a hexadecimal number is to find the hexadecimal digits
hn , hn - 1 , hn - 2 , Á , h2 , h1 , and h0 such that

                  d = hn * 16n + hn - 1 * 16n - 1 + hn - 2 * 16n - 2 + Á
                   + h2 * 162 + h1 * 161 + h0 * 160

These numbers can be found by successively dividing d by 16 until the quotient is 0. The
remainders are h0 , h1 , h2 , Á , hn - 2 , hn - 1 , and hn .
   For example, the decimal number 123 is 7B in hexadecimal. The conversion is done as fol-
lows:

                                  0         7        Quotient

                             16   7    16 123
                                  0       112
                                  7        11        Remainder


                                  h1        h0


    Listing 5.8 gives a program that prompts the user to enter a decimal number and converts
it into a hex number as a string.


LISTING 5.8 Decimal2HexConversion.java
 1 import java.util.Scanner;
 2
 3 public class Decimal2HexConversion {
 4   /** Main method */
 5   public static void main(String[] args) {
 6     // Create a Scanner
 7     Scanner input = new Scanner(System.in);
 8
 9     // Prompt the user to enter a decimal integer
10     System.out.print("Enter a decimal number: ");
11     int decimal = input.nextInt();                                                          input string
12
13     System.out.println("The hex number for decimal " +
14       decimal + " is " + decimalToHex(decimal) );                                           hex to decimal
15   }
16
17   /** Convert a decimal to a hex as a string */
18   public static String decimalToHex(int decimal) {
19     String hex = "";
20
21     while (decimal != 0) {
22       int hexValue = decimal % 16;
23       hex = toHexChar(hexValue) + hex;
24       decimal = decimal / 16;
168 Chapter 5 Methods
                      25          }
                      26
hex char to decimal   27          return hex;
to uppercase          28      }
                      29
                      30      /** Convert an integer to a single hex digit in a character */
                      31      public static char toHexChar(int hexValue) {
                      32        if (hexValue <= 9 && hexValue >= 0)
                      33          return (char)(hexValue + '0') ;
                      34        else // hexValue <= 15 && hexValue >= 10
                      35          return (char)(hexValue - 10 + 'A') ;
                      36      }
                      37 }



                          Enter a decimal number: 1234
                          The hex number for decimal 1234 is 4D2




                                           line#       decimal     hex        hexValue      toHexChar(hexValue)
                                           19          1234        “”
                                           22                                 2
                             iteration 1   23                      “2”                      2
                                           24          77
                                           22                                 13
                             iteration 2   23                      “D2”                     D
                                           24          4
                                           22                                 4
                             iteration 3   23                      “4D2”                    4
                                           24          0


                      The program uses the decimalToHex method (lines 18–28) to convert a decimal integer to a
                      hex number as a string. The method gets the remainder of the division of the decimal integer
                      by 16 (line 22). The remainder is converted into a character by invoking the toHexChar
                      method (line 23). The character is then appended to the hex string (line 23). The hex string is
                      initially empty (line 19). Divide the decimal number by 16 to remove a hex digit from the
                      number (line 24). The method repeatedly performs these operations in a loop until quotient
                      becomes 0 (lines 21–25).
                          The toHexChar method (lines 31–36) converts a hexValue between 0 and 15 into a hex
                      character. If hexValue is between 0 and 9, it is converted to (char)(hexValue + '0')
                      (line 33). Recall when adding a character with an integer, the character’s Unicode is used in
                      the evaluation. For example, if hexValue is 5, (char)(hexValue + '0') returns '5'. Sim-
                      ilarly, if hexValue is between 10 and 15, it is converted to (char)(hexValue + 'A') (line
                      35). For example, if hexValue is 11, (char)(hexValue + 'A') returns 'B'.


                      5.8 Overloading Methods
                      The max method that was used earlier works only with the int data type. But what if you
                      need to determine which of two floating-point numbers has the maximum value? The solution
                                                                                 5.8 Overloading Methods 169
is to create another method with the same name but different parameters, as shown in the fol-
lowing code:
  public static double max(double num1, double num2) {
    if (num1 > num2)
      return num1;
    else
      return num2;
  }

If you call max with int parameters, the max method that expects int parameters will be
invoked; if you call max with double parameters, the max method that expects double para-
meters will be invoked. This is referred to as method overloading; that is, two methods have    method overloading
the same name but different parameter lists within one class. The Java compiler determines
which method is used based on the method signature.
   Listing 5.9 is a program that creates three methods. The first finds the maximum integer,
the second finds the maximum double, and the third finds the maximum among three double
values. All three methods are named max.


LISTING 5.9 TestMethodOverloading.java
 1 public class TestMethodOverloading {
 2   /** Main method */
 3   public static void main(String[] args) {
 4     // Invoke the max method with int parameters
 5     System.out.println("The maximum between 3 and 4 is "
 6       + max(3, 4) );
 7
 8     // Invoke the max method with the double parameters
 9     System.out.println("The maximum between 3.0 and 5.4 is "
10       + max(3.0, 5.4) );
11
12     // Invoke the max method with three double parameters
13     System.out.println("The maximum between 3.0, 5.4, and 10.14 is "
14       + max(3.0, 5.4, 10.14) );
15   }
16
17   /** Return the max between two int values */
18   public static int max(int num1, int num2) {                                                overloaded max
19     if (num1 > num2)
20       return num1;
21     else
22       return num2;
23   }
24
25   /** Find the max between two double values */
26   public static double max(double num1, double num2) {                                       overloaded max
27     if (num1 > num2)
28       return num1;
29     else
30       return num2;
31   }
32
33   /** Return the max among three double values */
34   public static double max(double num1, double num2, double num3) {                          overloaded max
35     return max(max(num1, num2), num3);
36   }
37 }
170 Chapter 5 Methods

                           The maximum between 3 and 4 is 4
                           The maximum between 3.0 and 5.4 is 5.4
                           The maximum between 3.0, 5.4, and 10.14 is 10.14




                       When calling max(3, 4) (line 6), the max method for finding the maximum of two integers is
                       invoked. When calling max(3.0, 5.4) (line 10), the max method for finding the maximum of
                       two doubles is invoked. When calling max(3.0, 5.4, 10.14) (line 14), the max method for
                       finding the maximum of three double values is invoked.
                           Can you invoke the max method with an int value and a double value, such as max(2,
                       2.5)? If so, which of the max methods is invoked? The answer to the first question is yes. The
                       answer to the second is that the max method for finding the maximum of two double values
                       is invoked. The argument value 2 is automatically converted into a double value and passed
                       to this method.
                           You may be wondering why the method max(double, double) is not invoked for the call
                       max(3, 4). Both max(double, double) and max(int, int) are possible matches for
                       max(3, 4). The Java compiler finds the most specific method for a method invocation. Since
                       the method max(int, int) is more specific than max(double, double), max(int, int)
                       is used to invoke max(3, 4).


                            Note
                             Overloaded methods must have different parameter lists. You cannot overload methods based on
                             different modifiers or return types.


                            Note
                             Sometimes there are two or more possible matches for an invocation of a method, but the com-
ambiguous invocation         piler cannot determine the most specific match. This is referred to as ambiguous invocation.
                             Ambiguous invocation causes a compile error. Consider the following code:

                             public class AmbiguousOverloading {
                               public static void main(String[] args) {
                                 System.out.println(max(1, 2) );
                               }

                                 public static double max(int num1, double num2) {
                                   if (num1 > num2)
                                     return num1;
                                   else
                                     return num2;
                                 }

                                 public static double max(double num1, int num2) {
                                   if (num1 > num2)
                                     return num1;
                                   else
                                     return num2;
                                 }
                             }


                             Both max(int, double) and max(double, int) are possible candidates to match
                             max(1, 2). Since neither is more specific than the other, the invocation is ambiguous,
                             resulting in a compile error.
                                                                                               5.9 The Scope of Variables 171

5.9 The Scope of Variables
The scope of a variable is the part of the program where the variable can be referenced. A
variable defined inside a method is referred to as a local variable.                                             local variable
    The scope of a local variable starts from its declaration and continues to the end of the
block that contains the variable. A local variable must be declared and assigned a value before
it can be used.
    A parameter is actually a local variable. The scope of a method parameter covers the entire
method.
    A variable declared in the initial-action part of a for-loop header has its scope in the entire
loop. But a variable declared inside a for-loop body has its scope limited in the loop body
from its declaration to the end of the block that contains the variable, as shown in Figure 5.5.
                                              public static void method1() {
                                                 .
                                                 .
                                                 for (int i = 1; i < 10; i++) {
                                                   .
                   The scope of i                  .
                                                   int j;
                                                   .
                   The scope of j                  .
                                                   .
                                                 }
                                              }

FIGURE 5.5 A variable declared in the initial action part of a for-loop header has its scope
in the entire loop.
   You can declare a local variable with the same name in different blocks in a method, but you
cannot declare a local variable twice in the same block or in nested blocks, as shown in Figure 5.6.

             It is fine to declare i in two                                         It is wrong to declare i in two
             nonnested blocks                                                       nested blocks

               public static void method1() {                                            public static void method2() {
                 int x = 1;
                 int y = 1;                                                                  int i = 1;
                                                                                             int sum = 0;
                   for (int i = 1; i < 10; i++) {
                     x += i;                                                                 for (int i = 1; i < 10; i++)
                   }                                                                           sum += i;
                                                                                             }
                   for (int i = 1; i < 10; i++) {
                     y += i;                                                             }
                   }
               }


FIGURE 5.6    A variable can be declared multiple times in nonnested blocks but only once in nested blocks.

      Caution
      Do not declare a variable inside a block and then attempt to use it outside the block. Here is an
      example of a common mistake:

      for (int i = 0; i < 10; i++) {
      }
      System.out.println(i);
172 Chapter 5 Methods
                        The last statement would cause a syntax error, because variable i is not defined outside of the
                        for loop.



                  5.10 The Math Class
                  The Math class contains the methods needed to perform basic mathematical functions. You
                  have already used the pow(a, b) method to compute ab in Listing 2.8, ComputeLoan.java,
                  and the Math.random() method in Listing 3.4, SubtractionQuiz.java. This section intro-
                  duces other useful methods in the Math class. They can be categorized as trigonometric meth-
                  ods, exponent methods, and service methods. Besides methods, the Math class provides two
                  useful double constants, PI and E (the base of natural logarithms). You can use these con-
                  stants as Math.PI and Math.E in any program.

                  5.10.1 Trigonometric Methods
                  The Math class contains the following trigonometric methods:
                    /** Return the trigonometric sine of an angle in radians */
                    public static double sin(double radians)

                    /** Return the trigonometric cosine of an angle in radians */
                    public static double cos(double radians)

                    /** Return the trigonometric tangent of an angle in radians */
                    public static double tan(double radians)

                    /** Convert the angle in degrees to an angle in radians */
                    public static double toRadians(double degree)

                    /** Convert the angle in radians to an angle in degrees */
                    public static double toDegrees(double radians)

                    /** Return the angle in radians for the inverse of sin */
                    public static double asin(double a)

                    /** Return the angle in radians for the inverse of cos */
                    public static double acos(double a)

                    /** Return the angle in radians for the inverse of tan */
                    public static double atan(double a)

                  The parameter for sin, cos, and tan is an angle in radians. The return value for asin, acos,
                  and atan is a degree in radians in the range between -p/2 and p/2. One degree is equal to
                  p/180 in radians, 90 degrees is equal to p/2 in radians, and 30 degrees is equal to p/6 in
                  radians.
                     For example,

                    Math.toDegrees(Math.PI / 2) returns 90.0
                    Math.toRadians(30) returns π/6
                    Math.sin(0) returns 0.0
                    Math.sin(Math.toRadians(270)) returns -1.0
                    Math.sin(Math.PI / 6) returns 0.5
                    Math.sin(Math.PI / 2) returns 1.0
                    Math.cos(0) returns 1.0
                    Math.cos(Math.PI / 6) returns 0.866
                    Math.cos(Math.PI / 2) returns 0
                    Math.asin(0.5) returns π/6
                                                                   5.10 The Math Class 173

5.10.2     Exponent Methods
There are five methods related to exponents in the Math class:

  /** Return e raised to the power of x (ex) */
  public static double exp(double x)

  /** Return the natural logarithm of x (ln(x) = loge(x)) */
  public static double log(double x)

  /** Return the base 10 logarithm of x (log10(x)) */
  public static double log10(double x)

  /** Return a raised to the power of b (ab) */
  public static double pow(double a, double b)

  /** Return the square root of x ( 1x) for x >= 0 */
  public static double sqrt(double x)

  For example,

  Math.exp(1) returns 2.71828
  Math.log(Math.E) returns 1.0
  Math.log10(10) returns 1.0
  Math.pow(2, 3) returns 8.0
  Math.pow(3, 2) returns 9.0
  Math.pow(3.5, 2.5) returns 22.91765
  Math.sqrt(4) returns 2.0
  Math.sqrt(10.5) returns 3.24


5.10.3     The Rounding Methods
The Math class contains five rounding methods:
  /** x is rounded up to its nearest integer. This integer is
    * returned as a double value. */
  public static double ceil(double x)

  /** x is rounded down to its nearest integer. This integer is
    * returned as a double value. */
  public static double floor(double x)

  /** x is rounded to its nearest integer. If x is equally close
    * to two integers, the even one is returned as a double. */
  public static double rint(double x)

  /** Return (int)Math.floor(x + 0.5). */
  public static int round(float x)

  /** Return (long)Math.floor(x + 0.5). */
  public static long round(double x)

For example,
  Math.ceil(2.1) returns 3.0
  Math.ceil(2.0) returns 2.0
  Math.ceil(-2.0) returns –2.0
  Math.ceil(-2.1) returns -2.0
  Math.floor(2.1) returns 2.0
  Math.floor(2.0) returns 2.0
174 Chapter 5 Methods
                     Math.floor(-2.0) returns –2.0
                     Math.floor(-2.1) returns -3.0
                     Math.rint(2.1) returns 2.0
                     Math.rint(-2.0) returns –2.0
                     Math.rint(-2.1) returns -2.0
                     Math.rint(2.5) returns 2.0
                     Math.rint(3.5) returns 4.0
                     Math.rint(-2.5) returns -2.0
                     Math.round(2.6f) returns 3 // Returns int
                     Math.round(2.0) returns 2 // Returns long
                     Math.round(-2.0f) returns -2
                     Math.round(-2.6) returns -3

                  5.10.4        The min, max, and abs Methods
                  The min and max methods are overloaded to return the minimum and maximum numbers
                  between two numbers (int, long, float, or double). For example, max(3.4, 5.0)
                  returns 5.0, and min(3, 2) returns 2.
                     The abs method is overloaded to return the absolute value of the number (int, long,
                  float, and double). For example,
                     Math.max(2, 3) returns 3
                     Math.max(2.5, 3) returns 3.0
                     Math.min(2.5, 3.6) returns 2.5
                     Math.abs(-2) returns 2
                     Math.abs(-2.1) returns 2.1

                  5.10.5        The random Method
                  You have used the random() method to generate a random double value greater than or equal to
                  0.0 and less than 1.0 (0 <= Math.random() < 1.0). This method is very useful. You can use it to
                  write a simple expression to generate random numbers in any range. For example,
                                                                  Returns a random integer
                                  1int2 1Math.random1 2 * 102 ¡
                                                                  between 0 and 9
                                50 + 1int2 1Math.random1 2 * 502 ¡ Returns a random integer
                                                                     between 50 and 99

                  In general,
                                                                Returns a random number between
                                a + Math.random1 2 * b ¡
                                                                a and a + b excluding a + b




                  FIGURE 5.7     You can view the documentation for Java API online.
                                                         5.11 Case Study: Generating Random Characters 175

     Tip
      You can view the complete documentation for the Math class online at http://java.sun.com/
      javase/6/docs/api/index.html, as shown in Figure 5.7.


     Note
      Not all classes need a main method. The Math class and JOptionPane class do not have
      main methods. These classes contain methods for other classes to use.



5.11 Case Study: Generating Random Characters
Computer programs process numerical data and characters. You have seen many examples
that involve numerical data. It is also important to understand characters and how to process
them. This section presents an example for generating random characters.
   As introduced in §2.13, every character has a unique Unicode between 0 and FFFF in
hexadecimal (65535 in decimal). To generate a random character is to generate a random inte-
ger between 0 and 65535 using the following expression (note that since 0 <= Math.ran-
dom() < 1.0, you have to add 1 to 65535):

   (int)(Math.random() * (65535 + 1))

Now let us consider how to generate a random lowercase letter. The Unicodes for lowercase
letters are consecutive integers starting from the Unicode for 'a', then that for 'b', 'c', Á ,
and 'z'. The Unicode for 'a' is
   (int)'a'

So a random integer between (int)'a' and (int)'z' is

   (int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)

As discussed in §2.13.3, all numeric operators can be applied to the char operands. The char
operand is cast into a number if the other operand is a number or a character. Thus the pre-
ceding expression can be simplified as follows:

   'a' + Math.random() * ('z' - 'a' + 1)

and a random lowercase letter is
   (char)('a' + Math.random() * ('z' - 'a' + 1))

To generalize the foregoing discussion, a random character between any two characters ch1
and ch2 with ch1 < ch2 can be generated as follows:

   (char)(ch1 + Math.random() * (ch2 – ch1 + 1))

This is a simple but useful discovery. Let us create a class named RandomCharacter in List-
ing 5.10 with five overloaded methods to get a certain type of character randomly. You can
use these methods in your future projects.

LISTING 5.10 RandomCharacter.java
 1 public class RandomCharacter {
 2   /** Generate a random character between ch1 and ch2 */
 3   public static char getRandomCharacter(char ch1, char ch2) {                                  getRandomCharacter
 4     return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
 5   }
176 Chapter 5 Methods
                        6
                        7     /** Generate a random lowercase letter */
getRandomLowerCase      8     public static char getRandomLowerCaseLetter() {
  Letter()              9       return getRandomCharacter('a', 'z');
                       10     }
                       11
                       12     /** Generate a random uppercase letter */
getRandomUpperCase     13     public static char getRandomUpperCaseLetter() {
  Letter()             14       return getRandomCharacter('A', 'Z');
                       15     }
                       16
                       17     /** Generate a random digit character */
getRandomDigit         18     public static char getRandomDigitCharacter() {
  Character()          19       return getRandomCharacter('0', '9');
                       20     }
                       21
                       22     /** Generate a random character */
getRandomCharacter()   23     public static char getRandomCharacter() {
                       24       return getRandomCharacter('\u0000', '\uFFFF');
                       25     }
                       26 }

                       Listing 5.11 gives a test program that displays 175 random lowercase letters.

                       LISTING 5.11 TestRandomCharacter.java
                        1 public class TestRandomCharacter {
                        2   /** Main method */
                        3   public static void main(String[] args) {
constants               4     final int NUMBER_OF_CHARS = 175;
                        5     final int CHARS_PER_LINE = 25;
                        6
                        7     // Print random characters between 'a' and 'z', 25 chars per line
                        8     for (int i = 0; i < NUMBER_OF_CHARS; i++) {
lower-case letter       9       char ch = RandomCharacter.getRandomLowerCaseLetter() ;
                       10       if ((i + 1) % CHARS_PER_LINE == 0)
                       11         System.out.println(ch);
                       12       else
                       13         System.out.print(ch);
                       14     }
                       15   }
                       16 }


                           gmjsohezfkgtazqgmswfclrao
                           pnrunulnwmaztlfjedmpchcif
                           lalqdgivxkxpbzulrmqmbhikr
                           lbnrjlsopfxahssqhwuuljvbe
                           xbhdotzhpehbqmuwsfktwsoli
                           cbuwkzgxpmtzihgatdslvbwbz
                           bfesoklwbhnooygiigzdxuqni

                       Line 9 invokes getRandomLowerCaseLetter() defined in the RandomCharacter class.
                       Note that getRandomLowerCaseLetter() does not have any parameters, but you still have
parentheses required   to use the parentheses when defining and invoking the method.

                       5.12 Method Abstraction and Stepwise Refinement
                       The key to developing software is to apply the concept of abstraction. You will learn many lev-
method abstraction     els of abstraction from this book. Method abstraction is achieved by separating the use of a
                                                    5.12 Method Abstraction and Stepwise Refinement 177
method from its implementation. The client can use a method without knowing how it is imple-
mented. The details of the implementation are encapsulated in the method and hidden from the
client who invokes the method. This is known as information hiding or encapsulation. If you        information hiding
decide to change the implementation, the client program will not be affected, provided that you
do not change the method signature. The implementation of the method is hidden from the
client in a “black box,” as shown in Figure 5.8.

                       Optional arguments   Optional return
                            for input           value


                                  Method Header
                                                              Black box
                                   Method Body


FIGURE 5.8 The method body can be thought of as a black box that contains the detailed
implementation for the method.

  You have already used the System.out.print method to display a string, the
JOptionPane.showInputDialog method to read a string from a dialog box, and the max
method to find the maximum number. You know how to write the code to invoke these meth-
ods in your program, but as a user of these methods, you are not required to know how they
are implemented.
   The concept of method abstraction can be applied to the process of developing programs.
When writing a large program, you can use the divide-and-conquer strategy, also known as           divide and conquer
stepwise refinement, to decompose it into subproblems. The subproblems can be further              stepwise refinement
decomposed into smaller, more manageable problems.
   Suppose you write a program that displays the calendar for a given month of the year. The
program prompts the user to enter the year and the month, then displays the entire calendar for
the month, as shown in the following sample run:


    Enter full year (e.g., 2001): 2006
    Enter month in number between 1 and 12: 6
               June 2006
    —————————————————————————————————-
     Sun Mon Tue Wed Thu Fri Sat
                           1    2    3
       4    5    6    7    8    9   10
      11   12   13   14   15   16   17
      18   19   20   21   22   23   24
      25   26   27   28   29   30



Let us use this example to demonstrate the divide-and-conquer approach.

5.12.1 Top-Down Design
How would you get started on such a program? Would you immediately start coding? Begin-
ning programmers often start by trying to work out the solution to every detail. Although
details are important in the final program, concern for detail in the early stages may block the
problem-solving process. To make problem solving flow as smoothly as possible, this exam-
ple begins by using method abstraction to isolate details from design and only later imple-
ments the details.
178 Chapter 5 Methods
                              For this example, the problem is first broken into two subproblems: get input from the
                           user, and print the calendar for the month. At this stage, you should be concerned with what
                           the subproblems will achieve, not with how to get input and print the calendar for the month.
                           You can draw a structure chart to help visualize the decomposition of the problem (see
                           Figure 5.9(a)).


                          printCalendar
                              (main)                                             printMonth




              readInput                    printMonth          printMonthTitle                 printMonthBody

                                (a)                                                (b)

FIGURE 5.9 The structure chart shows that the printCalendar problem is divided into two subproblems, readInput and
printMonth, and that printMonth is divided into two smaller subproblems, printMonthTitle and printMonthBody.


                               The problem of printing the calendar for a given month can be broken into two subprob-
                           lems: print the month title, and print the month body, as shown in Figure 5.9(b). The month
                           title consists of three lines: month and year, a dash line, and the names of the seven days of the
                           week. You need to get the month name (e.g., January) from the numeric month (e.g., 1). This
                           is accomplished in getMonthName (see Figure 5.10(a)).


                                                                            printMonthBody
                                      printMonthTitle


                                         getMonthName         getStartDay             getNumberOfDaysInMonth

                                             (a)                                   (b)

                           FIGURE 5.10 (a) To printMonthTitle, you need getMonthName. (b) The printMonthBody
                           problem is refined into several smaller problems.


                               In order to print the month body, you need to know which day of the week is the first day of
                           the month (getStartDay) and how many days the month has (getNumberOfDaysInMonth),
                           as shown in Figure 5.10(b). For example, December 2005 has 31 days, and December 1, 2005,
                           is Thursday.
                               How would you get the start day for the first date in a month? There are several ways to do
                           so. For now, we’ll use the following approach. Assume you know that the start day
                           (startDay1800 = 3) for Jan 1, 1800, was Wednesday. You could compute the total number of


                                         getStartDay             getTotalNumberOfDays


                                                                                         getNumberOfDaysInMonth


                                  getTotalNumberOfDays                 isLeapYear

                                              (a)                                        (b)

                           FIGURE 5.11
                                     (a) To getStartDay, you need getTotalNumberOfDays. (b) The
                           getTotalNumberOfDays problem is refined into two smaller problems.
                                                      5.12 Method Abstraction and Stepwise Refinement 179
days (totalNumberOfDays) between Jan 1, 1800, and the first date of the calendar month. The
start day for the calendar month is (totalNumberOfDays + startDay1800) % 7, since every
week has seven days. So the getStartDay problem can be further refined as
getTotalNumberOfDays, as shown in Figure 5.11(a).
   To get the total number of days, you need to know whether the year is a leap year and the
number of days in each month. So getTotalNumberOfDays is further refined into two sub-
problems: isLeapYear and getNumberOfDaysInMonth, as shown in Figure 5.11(b). The
complete structure chart is shown in Figure 5.12.

                           printCalendar
                               (main)




              readInput                     printMonth




                         printMonthTitle                 printMonthBody


                           getMonthName            getStartDay


                                              getTotalNumberOfDays


                                                            getNumberOfDaysInMonth


                                              isLeapYear

FIGURE 5.12 The structure chart shows the hierarchical relationship of the subproblems in
the program.

5.12.2      Top-Down or Bottom-Up Implementation
Now we turn our attention to implementation. In general, a subproblem corresponds to a
method in the implementation, although some are so simple that this is unnecessary. You
would need to decide which modules to implement as methods and which to combine in other
methods. Decisions of this kind should be based on whether the overall program will be eas-
ier to read as a result of your choice. In this example, the subproblem readInput can be sim-
ply implemented in the main method.
    You can use either a “top-down” or a “bottom-up” approach. The top-down approach imple-           top-down approach
ments one method in the structure chart at a time from the top to the bottom. Stubs can be used for
the methods waiting to be implemented. A stub is a simple but incomplete version of a method.         stub
The use of stubs enables you to quickly build the framework of the program. Implement the main
method first, then use a stub for the printMonth method. For example, let printMonth display
the year and the month in the stub. Thus, your program may begin like this:

   public class PrintCalendar {
     /** Main method */
     public static void main(String[] args) {
       Scanner input = new Scanner(System.in);

        // Prompt the user to enter year
        System.out.print("Enter full year (e.g., 2001): ");
        int year = input.nextInt();
180 Chapter 5 Methods
                                // Prompt the user to enter month
                                System.out.print("Enter month as number between 1 and 12: ");
                                int month = input.nextInt();

                                // Print calendar for the month of the year
                                printMonth(year, month);
                            }

                            /** A stub for printMonth may look like this */
                            public static void printMonth(int year, int month) {
                              System.out.print(month + " " + year);
                            }

                            /** A stub for printMonthTitle may look like this */
                            public static void printMonthTitle(int year, int month) {
                            }

                            /** A stub for getMonthBody may look like this */
                            public static void printMonthBody(int year, int month)                {
                            }

                            /** A stub for getMonthName may look like this */
                            public static String getMonthName(int month) {
                              return "January"; // A dummy value
                            }

                            /** A stub for getMonthName may look like this */
                            public static int getStartDay(int year, int month) {
                              return 1; // A dummy value
                            }

                            /** A stub for getTotalNumberOfDays may look like this */
                            public static int getTotalNumberOfDays(int year, int month) {
                              return 10000; // A dummy value
                            }

                            /** A stub for getNumberOfDaysInMonth may look like this */
                            public static int getNumberOfDaysInMonth(int year, int month)                  {
                              return 31; // A dummy value
                            }

                            /** A stub for getTotalNumberOfDays may look like this */
                            public static boolean isLeapYear(int year) {
                              return true; // A dummy value
                            }
                        }

                     Compile and test the program, and fix any errors. You can now implement the printMonth
                     method. For methods invoked from the printMonth method, you can again use stubs.
bottom-up approach      The bottom-up approach implements one method in the structure chart at a time from the bot-
                     tom to the top. For each method implemented, write a test program to test it. The top-down and
                     bottom-up approaches are both fine. Both approaches implement methods incrementally, help to
                     isolate programming errors, and make debugging easy. Sometimes they can be used together.


                     5.12.3       Implementation Details
                     The isLeapYear(int year) method can be implemented using the following code:

                        return (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0));
                                                     5.12 Method Abstraction and Stepwise Refinement 181
Use the following facts to implement getTotalNumberOfDaysInMonth(int year, int
month):

      ■   January, March, May, July, August, October, and December have 31 days.
      ■   April, June, September, and November have 30 days.
      ■   February has 28 days during a regular year and 29 days during a leap year. A regular
          year, therefore, has 365 days, a leap year 366 days.
To implement getTotalNumberOfDays(int year, int month), you need to compute
the total number of days (totalNumberOfDays) between January 1, 1800, and the first day
of the calendar month. You could find the total number of days between the year 1800 and the
calendar year and then figure out the total number of days prior to the calendar month in the
calendar year. The sum of these two totals is totalNumberOfDays.
    To print a body, first pad some space before the start day and then print the lines for every
week.
    The complete program is given in Listing 5.12.

LISTING 5.12 PrintCalendar.java
  1 import java.util.Scanner;
  2
  3 public class PrintCalendar {
  4   /** Main method */
  5   public static void main(String[] args) {
  6     Scanner input = new Scanner(System.in);
  7
  8     // Prompt the user to enter year
  9     System.out.print("Enter full year (e.g., 2001): ");
 10     int year = input.nextInt();
 11
 12     // Prompt the user to enter month
 13     System.out.print("Enter month in number between 1 and 12: ");
 14     int month = input.nextInt();
 15
 16     // Print calendar for the month of the year
 17     printMonth(year, month);
 18   }
 19
 20   /** Print the calendar for a month in a year */
 21   public static void printMonth(int year, int month) {                                          printMonth
 22     // Print the headings of the calendar
 23     printMonthTitle(year, month);
 24
 25     // Print the body of the calendar
 26     printMonthBody(year, month);
 27   }
 28
 29   /** Print the month title, e.g., May, 1999 */
 30   public static void printMonthTitle(int year, int month) {                                     printMonthTitle
 31     System.out.println("         " + getMonthName(month)
 32       + " " + year);
 33     System.out.println("———————————————————————————————");
 34     System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
 35   }
 36
 37   /** Get the English name for the month */
 38   public static String getMonthName(int month) {                                                getMonthName
 39     String monthName = " ";
182 Chapter 5 Methods
                       40       switch   (month) {
                       41         case   1: monthName = "January"; break;
                       42         case   2: monthName = "February"; break;
                       43         case   3: monthName = "March"; break;
                       44         case   4: monthName = "April"; break;
                       45         case   5: monthName = "May"; break;
                       46         case   6: monthName = "June"; break;
                       47         case   7: monthName = "July"; break;
                       48         case   8: monthName = "August"; break;
                       49         case   9: monthName = "September"; break;
                       50         case   10: monthName = "October"; break;
                       51         case   11: monthName = "November"; break;
                       52         case   12: monthName = "December";
                       53       }
                       54
                       55       return monthName;
                       56   }
                       57
                       58   /** Print month body */
getMonthBody           59   public static void printMonthBody(int year, int month) {
                       60     // Get start day of the week for the first date in the month
                       61     int startDay = getStartDay(year, month) ;
                       62
                       63       // Get number of days in the month
                       64       int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month) ;
                       65
                       66        // Pad space before the first day of the month
                       67        int i = 0;
                       68        for (i = 0; i < startDay; i++)
                       69          System.out.print("    ");
                       70
                       71        for (i = 1; i <= numberOfDaysInMonth; i++) {
                       72          System.out.printf("%4d", i);
                       73
                       74           if ((i + startDay) % 7 == 0)
                       75             System.out.println();
                       76       }
                       77
                       78       System.out.println();
                       79   }
                       80
                       81   /** Get the start day of month/1/year */
getStartDay            82   public static int getStartDay(int year, int month) {
                       83     final int START_DAY_FOR_JAN_1_1800 = 3;
                       84     // Get total number of days from 1/1/1800 to month/1/year
                       85     int totalNumberOfDays = getTotalNumberOfDays(year, month);
                       86
                       87       // Return the start day for month/1/year
                       88       return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7;
                       89   }
                       90
                       91   /** Get the total number of days since January 1, 1800 */
getTotalNumberOfDays   92   public static int getTotalNumberOfDays(int year, int month) {
                       93     int total = 0;
                       94
                       95       // Get the total days from 1800 to 1/1/year
                       96       for (int i = 1800; i < year; i++)
                       97         if (isLeapYear(i))
                                                                                                                       Key Terms 183
 98             total = total + 366;
 99           else
100             total = total + 365;
101
102         // Add days from Jan to the month prior to the calendar month
103         for (int i = 1; i < month; i++)
104           total = total + getNumberOfDaysInMonth(year, i);
105
106         return total;
107     }
108
109     /** Get the number of days in a month */
110     public static int getNumberOfDaysInMonth(int year, int month) {                                           getNumberOfDaysInMonth
111       if (month == 1 || month == 3 || month == 5 || month == 7 ||
112        month == 8 || month == 10 || month == 12)
113        return 31;
114
115         if (month == 4 || month == 6 || month == 9 || month == 11)
116           return 30;
117
118         if (month == 2) return isLeapYear(year) ? 29 : 28;
119
120         return 0; // If month is incorrect
121     }
122
123     /** Determine if it is a leap year */
124     public static boolean isLeapYear(int year) {                                                              isLeapYear
125       return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
126     }
127 }

The program does not validate user input. For instance, if the user enters either a month not in
the range between 1 and 12 or a year before 1800, the program displays an erroneous calen-
dar. To avoid this error, add an if statement to check the input before printing the calendar.
    This program prints calendars for a month but could easily be modified to print calendars
for a whole year. Although it can print months only after January 1800, it could be modified
to trace the day of a month before 1800.

     Note
      Method abstraction modularizes programs in a neat, hierarchical manner. Programs written as
      collections of concise methods are easier to write, debug, maintain, and modify. This writing style
      also promotes method reusability.
                                                                                                                  incremental development and
     Tip                                                                                                             testing
      When implementing a large program, use the top-down or bottom-up approach. Do not write the
      entire program at once. Using these approaches seems to take more development time (because you
      repeatedly compile and run the program), but it actually saves time and makes debugging easier.


   KEY TERMS
   actual parameter 157                                     formal parameter (i.e., parameter)              157
   argument 157                                             information hiding 177
   ambiguous invocation 170                                 method 156
   divide and conquer 177                                   method abstraction 176
184 Chapter 5 Methods
                   method overloading 169                          return type 170
                   method signature 157                            return value 157
                   modifier 157                                    scope of variable 171
                   pass-by-value 163                               stepwise refinement 177
                   parameter 157                                   stub 179



                   CHAPTER SUMMARY
                    1. Making programs modular and reusable is one of the central goals in software engi-
                        neering. Java provides many powerful constructs that help to achieve this goal.
                        Methods are one such construct.

                    2. The method header specifies the modifiers, return value type, method name, and
                        parameters of the method. The static modifier is used for all the methods in this
                        chapter.

                    3. A method may return a value. The returnValueType is the data type of the value
                        the method returns. If the method does not return a value, the returnValueType is
                        the keyword void.

                    4. The parameter list refers to the type, order, and number of the parameters of a
                        method. The method name and the parameter list together constitute the method sig-
                        nature. Parameters are optional; that is, a method may contain no parameters.

                    5. A return statement can also be used in a void method for terminating the method
                        and returning to the method’s caller. This is useful occasionally for circumventing
                        the normal flow of control in a method.

                    6. The arguments that are passed to a method should have the same number, type, and
                        order as the parameters in the method signature.

                    7. When a program calls a method, program control is transferred to the called method.
                        A called method returns control to the caller when its return statement is executed or
                        when its method-ending closing brace is reached.

                    8. A value-returning method can also be invoked as a statement in Java. In this case, the
                        caller simply ignores the return value.

                    9. Each time a method is invoked, the system stores parameters and local variables
                        in a space known as a stack. When a method calls another method, the caller’s
                        stack space is kept intact, and new space is created to handle the new method call.
                        When a method finishes its work and returns to its caller, its associated space is
                        released.

                   10. A method can be overloaded. This means that two methods can have the same name,
                        as long as their method parameter lists differ.

                   11. A variable declared in a method is called a local variable. The scope of a local
                        variable starts from its declaration and continues to the end of the block that con-
                        tains the variable. A local variable must be declared and initialized before it is
                        used.
                                                                                       Review Questions   185

12. Method abstraction is achieved by separating the use of a method from its imple-
      mentation. The client can use a method without knowing how it is implemented. The
      details of the implementation are encapsulated in the method and hidden from the
      client who invokes the method. This is known as information hiding or
      encapsulation.

13. Method abstraction modularizes programs in a neat, hierarchical manner. Programs
      written as collections of concise methods are easier to write, debug, maintain, and
      modify than would otherwise be the case. This writing style also promotes method
      reusability.

14. When implementing a large program, use the top-down or bottom-up coding
      approach. Do not write the entire program at once. This approach seems to take more
      time for coding (because you are repeatedly compiling and running the program), but
      it actually saves time and makes debugging easier.



REVIEW QUESTIONS
Sections 5.2–5.4
5.1     What are the benefits of using a method? How do you define a method? How do
        you invoke a method?
5.2     What is the return type of a main method?
5.3     Can you simplify the max method in Listing 5.1 using the conditional operator?
5.4     True or false? A call to a method with a void return type is always a statement
        itself, but a call to a value-returning method is always a component of an
        expression.
5.5     What would be wrong with not writing a return statement in a value-returning
        method? Can you have a return statement in a void method? Does the return
        statement in the following method cause syntax errors?

        public static void xMethod(double x, double y) {
          System.out.println(x + y);
          return x + y;
        }


5.6     Define the terms parameter, argument, and method signature.
5.7     Write method headers for the following methods:

        ■   Computing a sales commission, given the sales amount and the commission
            rate.
        ■   Printing the calendar for a month, given the month and year.
        ■   Computing a square root.
        ■   Testing whether a number is even, and returning true if it is.
        ■   Printing a message a specified number of times.
        ■   Computing the monthly payment, given the loan amount, number of years, and
            annual interest rate.
        ■   Finding the corresponding uppercase letter, given a lowercase letter.
186 Chapter 5 Methods

                             5.8    Identify and correct the errors in the following program:

                                     1 public class Test {
                                     2   public static method1(int n, m) {
                                     3     n += m;
                                     4     method2(3.4);
                                     5   }
                                     6
                                     7   public static int method2(int n) {
                                     8     if (n > 0) return 1;
                                     9     else if (n == 0) return 0;
                                    10     else if (n < 0) return –1;
                                    11   }
                                    12 }

                             5.9    Reformat the following program according to the programming st yle and docu-
                                    mentation guidelines proposed in §2.16, “Programming Style and Documenta-
                                    tion.” Use the next-line brace style.

                                    public class Test {
                                      public static double method1(double i,double j)
                                      {
                                      while (i<j) {
                                        j--;
                                      }

                                        return j;
                                        }
                                    }

                             Sections 5.5–5.7
                             5.10 How is an argument passed to a method? Can the argument have the same name as
                                    its parameter?
                             5.11   What is pass-by-value? Show the result of the following programs:


   public class Test {                                        public class Test {
     public static void main(String[] args) {                   public static void main(String[] args) {
       int max = 0;                                               int i = 1;
       max(1, 2, max);                                            while (i <= 6) {
           System.out.println(max);                                 method1(i, 2);
       }                                                                  i++;
                                                                      }
       public static void max(                                    }
           int value1, int value2, int max) {
         if (value1 > value2)                                     public static void method1(
             max = value1;                                            int i, int num) {
           else
                                                                    for (int j = 1; j <= i; j++) {
             max = value2;
       }                                                              System.out.print(num + " ");
                                                                      num *= 2;
   }
                                                                      }

                                                                      System.out.println();
                                                                  }
                                                              }




                             (a)                                                        (b)
                                                                                                 Review Questions 187

public class Test {                                             public class Test {
  public static void main(String[] args) {                        public static void main(String[] args) {
    // Initialize times                                             int i = 0;
    int times = 3;                                                  while (i <= 4) {
    System.out.println("Before the call,"                                   method1(i);
      + " variable times is " + times);                                     i++;
                                                                        }
        // Invoke nPrintln and display times
        nPrintln("Welcome to Java!", times);                            System.out.println("i is " + i);
        System.out.println("After the call,"                        }
          + " variable times is " + times);
    }                                                               public static void method1(int i) {
                                                                      do {
    // Print the message n times                                        if (i % 3 != 0)
    public static void nPrintln(                                           System.out.print(i + " ");
        String message, int n) {                                            i--;
      while (n > 0) {                                                   }
        System.out.println("n = " + n);                                 while (i >= 1);
            System.out.println(message);
            n--;                                                        System.out.println();
        }                                                           }
    }                                                           }
}

                              (c)                                                          (d)


    5.12 For (a) in the preceding question, show the contents of the stack just before the
              method max is invoked, just as max is entered, just before max is returned, and
              right after max is returned.

    Section 5.8
    5.13 What is method overloading? Is it permissible to define two methods that have the
              same name but different parameter types? Is it permissible to define two methods
              in a class that have identical method names and parameter lists but different return
              value types or different modifiers?
    5.14      What is wrong in the following program?

              public class Test {
                public static void method(int x) {
                }

                  public static int method(int y) {
                    return y;
                  }
              }


    Section 5.9
    5.15 Identify and correct the errors in the following program:
               1 public class Test {
               2   public static void main(String[] args) {
               3     nPrintln("Welcome to Java!", 5);
               4   }
               5
               6   public static void nPrintln(String message, int n) {
               7     int n = 1;
188 Chapter 5 Methods
                            8     for (int i = 0; i < n; i++)
                            9       System.out.println(message);
                           10   }
                           11 }

                   Section 5.10
                   5.16 True or false? The argument for trigonometric methods represents an angle in radians.
                   5.17 Write an expression that returns a random integer between 34 and 55. Write an
                           expression that returns a random integer between 0 and 999. Write an expression
                           that returns a random number between 5.5 and 55.5. Write an expression that
                           returns a random lowercase letter.
                   5.18    Evaluate the following method calls:
                           (a) Math.sqrt(4)
                           (b) Math.sin(2 * Math.PI)
                           (c) Math.cos(2 * Math.PI)
                           (d) Math.pow(2, 2)
                           (e) Math.log(Math.E)
                           (f) Math.exp(1)
                           (g) Math.max(2, Math.min(3, 4))
                           (h) Math.rint1-2.52
                           (i) Math.ceil1-2.52
                           (j) Math.floor1-2.52
                           (k) Math.round1-2.5F2
                           (l) Math.round1-2.52
                           (m) Math.rint(2.5)
                           (n) Math.ceil(2.5)
                           (o) Math.floor(2.5)
                           (p) Math.round(2.5F)
                           (q) Math.round(2.5)
                           (r) Math.round(Math.abs1-2.52)

                   PROGRAMMING EXERCISES
                   Sections 5.2–5.9
                   5.1     (Math: pentagonal numbers) A pentagonal number is defined as n13n-12/2 for
                           n = 1, 2, Á , and so on. So, the first few numbers are 1, 5, 12, 22, Á . Write the
                           following method that returns a pentagonal number:
                           public static int getPentagonalNumber(int n)

                           Write a test program that displays the first 100 pentagonal numbers with 10 num-
                           bers on each line.
                   5.2*    (Summing the digits in an integer) Write a method that computes the sum of the
                           digits in an integer. Use the following method header:
                           public static int sumDigits(long n)

                           For example, sumDigits(234) returns 9 12 + 3 + 42.
                           (Hint: Use the % operator to extract digits, and the / operator to remove the
                           extracted digit. For instance, to extract 4 from 234, use 234 % 10 1= 42. To
                           remove 4 from 234, use 234 / 10 1= 232. Use a loop to repeatedly extract and
                           remove the digit until all the digits are extracted. Write a test program that prompts
                           the user to enter an integer and displays the sum of all its digits.)
                                                                                    Programming Exercises 189

5.3** (Palindrome integer) Write the following two methods
       // Return the reversal of an integer, i.e. reverse(456) returns 654
       public static int reverse(int number)

       // Return true if number is palindrome
       public static boolean isPalindrome(int number)

       Use the reverse method to implement isPalindrome. A number is a palin-
       drome if its reversal is the same as itself. Write a test program that prompts the
       user to enter an integer and reports whether the integer is a palindrome.
5.4*   (Displaying an integer reversed) Write the following method to display an integer
       in reverse order:
       public static void reverse(int number)

       For example, reverse(3456) displays 6543. Write a test program that prompts
       the user to enter an integer and displays its reversal.
5.5* (Sorting three numbers) Write the following method to display three numbers in
       increasing order:
       public static void displaySortedNumbers(
         double num1, double num2, double num3)

5.6* (Displaying patterns) Write a method to display a pattern as follows:
                        1
                      2 1
                    3 2 1
       ...
       n n-1 ... 3 2 1

       The method header is

       public static void displayPattern(int n)

5.7* (Financial application: computing the future investment value) Write a method that
       computes future investment value at a given interest rate for a specified number of
       years. The future investment is determined using the formula in Exercise 2.13.
       Use the following method header:

       public static double futureInvestmentValue(
         double investmentAmount, double monthlyInterestRate, int years)

       For example, futureInvestmentValue(10000, 0.05/12, 5) returns 12833.59.
          Write a test program that prompts the user to enter the investment amount (e.g.,
       1000) and the interest rate (e.g., 9%) and prints a table that displays future value
       for the years from 1 to 30, as shown below:

       The amount invested: 1000
       Annual interest rate: 9%
       Years       Future Value
       1              1093.80
       2              1196.41
       ...
       29            13467.25
       30            14730.57
190 Chapter 5 Methods

                   5.8    (Conversions between Celsius and Fahrenheit) Write a class that contains the fol-
                          lowing two methods:

                          /** Converts from Celsius to Fahrenheit */
                          public static double celsiusToFahrenheit(double celsius)

                          /** Converts from Fahrenheit to Celsius */
                          public static double fahrenheitToCelsius(double fahrenheit)

                          The formula for the conversion is:

                          fahrenheit = (9.0 / 5) * celsius + 32

                          Write a test program that invokes these methods to display the following tables:

                          Celsius        Fahrenheit            Fahrenheit        Celsius

                          40.0           104.0                 120.0             48.89
                          39.0           102.2                 110.0             43.33
                          ...
                          32.0           89.6                  40.0              4.44
                          31.0           87.8                  30.0              -1.11


                   5.9    (Conversions between feet and meters) Write a class that contains the following
                          two methods:

                          /** Converts from feet to meters */
                          public static double footToMeter(double foot)

                          /** Converts from meters to feet */
                          public static double meterToFoot(double meter)

                          The formula for the conversion is:

                          meter = 0.305 * foot

                          Write a test program that invokes these methods to display the following
                          tables:

                          Feet        Meters          Meters           Feet

                          1.0         0.305           20.0             65.574
                          2.0         0.61            25.0             81.967
                          ...
                          9.0         2.745           60.0             196.721
                          10.0        3.05            65.0             213.115


                   5.10 (Using the   isPrime Method) Listing 5.7, PrimeNumberMethod.java, provides
                          the isPrime(int number) method for testing whether a number is prime. Use
                          this method to find the number of prime numbers less than 10000.
                   5.11 (Financial application: computing commissions) Write a method that computes
                          the commission, using the scheme in Exercise 4.39. The header of the method is as
                          follows:

                          public static double computeCommission(double salesAmount)
                                                                                    Programming Exercises 191
        Write a test program that displays the following table:

        Sales Amount        Commission

        10000               900.0
        15000               1500.0
        ...
        95000               11100.0
        100000              11700.0

5.12 (Displaying characters) Write a method that prints characters using the following
        header:

        public static void printChars(char ch1, char ch2, int
          numberPerLine)

        This method prints the characters between ch1 and ch2 with the specified numbers
        per line. Write a test program that prints ten characters per line from '1' to 'Z'.
5.13*   (Summing series) Write a method to compute the following series:
                                           1   2         i
                                  m1i2 =     +   + Á +
                                           2   3       i + 1
        Write a test program that displays the following table:
        i                   m(i)
        1                   0.5000
        2                   1.1667
        ...
        19                  16.4023
        20                  17.3546

5.14* (Computing series) Write a method to compute the following series:
                                1  1 1 1   1          1        1
                m1i2 = 4a1 -      + - + -    + Á +        -        b
                                3  5 7 9  11       2i - 1   2i + 1                            Video Note
                                                                                              Compute p
        Write a test program that displays the following table:
        i               m(i)
        10              3.04184
        20              3.09162
        ...
        90              3.13048
        100             3.13159

5.15* (Financial application: printing a tax table) Listing 3.6 gives a program to com-
        pute tax. Write a method for computing tax using the following header:

        public static double computetax(int status, double taxableIncome)

        Use this method to write a program that prints a tax table for taxable income from
        $50,000 to $60,000 with intervals of $50 for all four statuses, as follows:
        Taxable          Single          Married        Married         Head of
        Income                           Joint          Separate        a House

        50000            8688            6665           8688            7353
        50050            8700            6673           8700            7365
        ...
        59950            11175           8158           11175           9840
        60000            11188           8165           11188           9853
192 Chapter 5 Methods

                   5.16* (Number of days in a year) Write a method that returns the number of days in a
                          year using the following header:

                          public static int numberOfDaysInAYear(int year)

                          Write a test program that displays the number of days in year from 2000 to 2010.

                   Sections 5.10–5.11
                   5.17* (Displaying matrix of 0s and 1s) Write a method that displays an n-by-n matrix
                          using the following header:

                          public static void printMatrix(int n)

                          Each element is 0 or 1, which is generated randomly. Write a test program that
                          prints a 3-by-3 matrix that may look like this:

                          010
                          000
                          111

                   5.18 (Using the Math.sqrt method) Write a program that prints the following table
                          using the sqrt method in the Math class.

                          Number          SquareRoot

                          0                     0.0000
                          2                     1.4142
                          ...
                          18                    4.2426
                          20                    4.4721

                   5.19* (The MyTriangle class) Create a class named MyTriangle that contains the fol-
                          lowing two methods:

                          /** Returns true if the sum of any two sides is
                           * greater than the third side. */
                          public static boolean isValid(
                            double side1, double side2, double side3)

                          /** Returns the area of the triangle. */
                          public static double area(
                            double side1, double side2, double side3)

                          Write a test program that reads three sides for a triangle and computes the area if
                          the input is valid. Otherwise, it displays that the input is invalid. The formula for
                          computing the area of a triangle is given in Exercise 2.21.
                   5.20   (Using trigonometric methods) Print the following table to display the sin value
                          and cos value of degrees from 0 to 360 with increments of 10 degrees. Round the
                          value to keep four digits after the decimal point.

                          Degree          Sin                Cos

                          0               0.0000             1.0000
                          10              0.1736             0.9848
                          ...
                          350             -0.1736            0.9848
                          360             0.0000             1.0000
                                                                                          Programming Exercises 193

5.21** (Statistics: computing mean and standard deviation) In business applications,
         you are often asked to compute the mean and standard deviation of data. The
         mean is simply the average of the numbers. The standard deviation is a statistic
         that tells you how tightly all the various data are clustered around the mean in a
         set of data. For example, what is the average age of the students in a class? How
         close are the ages? If all the students are the same age, the deviation is 0. Write a
         program that prompts the user to enter ten numbers, and displays the mean and
         standard deviations of these numbers using the following formula:

                                                                                         n        2

                    n                                                       n
                                                                                       ¢ a xi ≤
                                                                                        i=1
                                                                           a xi -
                                                                              2
                   a xi     x1 + x2 +         + xn                                           n
                  i=1                     Á                                i=1
        mean =            =                           deviation =
                     n              n                                e            n - 1

         Here is a sample run:


 Enter ten numbers: 1 2 3 4.5 5.6 6 7 8 9 10
 The mean is 5.61
 The standard deviation is 2.99794



5.22** (Math: approximating the square root) Implement the sqrt method. The square
         root of a number, num, can be approximated by repeatedly performing a calcula-
         tion using the following formula:

         nextGuess = (lastGuess + (num / lastGuess)) / 2

         When nextGuess and lastGuess are almost identical, nextGuess is the
         approximated square root.
             The initial guess can be any positive value (e.g., 1). This value will be the start-
         ing value for lastGuess. If the difference between nextGuess and lastGuess
         is less than a very small number, such as 0.0001, you can claim that nextGuess
         is the approximated square root of num. If not, nextGuess becomes lastGuess
         and the approximation process continues.

Sections 5.10–5.11
5.23* (Generating random characters) Use the methods in RandomCharacter in Listing
      5.10 to print 100 uppercase letters and then 100 single digits, printing ten per line.
5.24** (Displaying current date and time) Listing 2.9, ShowCurrentTime.java, displays
       the current time. Improve this example to display the current date and time. The
       calendar example in Listing 5.12, PrintCalendar.java, should give you some ideas
       on how to find year, month, and day.
5.25** (Converting milliseconds to hours, minutes, and seconds) Write a method that
       converts milliseconds to hours, minutes, and seconds using the following header:

         public static String convertMillis(long millis)

         The   method     returns   a   string   as   hours:minutes:seconds.     For    example,
         convertMillis(5500) returns a string 0:0:5, convertMillis(100000) returns
         a string 0:1:40, and convertMillis(555550000) returns a string 154:19:10.
194 Chapter 5 Methods
                   Comprehensive
                   5.26** (Palindromic prime) A palindromic prime is a prime number and also palin-
                            dromic. For example, 131 is a prime and also a palindromic prime. So are 313
                            and 757. Write a program that displays the first 100 palindromic prime num-
                            bers. Display 10 numbers per line and align the numbers properly, as follows:
                                    2     3     5       7     11      101    131    151     181    191
                                  313   353   373     383    727      757    787    797     919    929
                                  ...

                   5.27** (Emirp) An emirp (prime spelled backward) is a nonpalindromic prime number
                            whose reversal is also a prime. For example, 17 is a prime and 71 is a prime. So,
                            17 and 71 are emirps. Write a program that displays the first 100 emirps.
                            Display 10 numbers per line and align the numbers properly, as follows:
                                   13    17    31    37    71    73    79     97   107    113
                                  149   157   167   179   199   311   337    347   359    389
                                  ...

                   5.28** (Mersenne prime) A prime number is called a Mersenne prime if it can be writ-
                            ten in the form 2p - 1 for some positive integer p. Write a program that finds all
                            Mersenne primes with p … 31 and displays the output as follows:
                                    p          2^p - 1
                                    2             3
                                    3             7
                                    5            31
                            ...

                   5.29** (Game: craps) Craps is a popular dice game played in casinos. Write a program
                            to play a variation of the game, as follows:
                            Roll two dice. Each die has six faces representing values 1, 2, Á , and 6, respec-
                            tively. Check the sum of the two dice. If the sum is 2, 3, or 12 (called craps), you
                            lose; if the sum is 7 or 11 (called natural), you win; if the sum is another value (i.e.,
                            4, 5, 6, 8, 9, or 10), a point is established. Continue to roll the dice until either a 7
                            or the same point value is rolled. If 7 is rolled, you lose. Otherwise, you win.
                            Your program acts as a single player. Here are some sample runs.

                    You rolled 5 + 6 = 11
                    You win



                    You rolled 1 + 2 = 3
                    You lose



                    You rolled 4 + 4 = 8
                    point is 8
                    You rolled 6 + 2 = 8
                    You win



                    You rolled 3 + 2 = 5
                    point is 5
                    You rolled 2 + 5 = 7
                    You lose
                                                                                      Programming Exercises 195

5.30** (Twin primes) Twin primes are a pair of prime numbers that differ by 2. For
        example, 3 and 5 are twin primes, 5 and 7 are twin primes, and 11 and 13 are
        twin primes. Write a program to find all twin primes less than 1000. Display the
        output as follows:

        (3, 5)
        (5, 7)
        ...

5.31** (Financial: credit card number validation) Credit card numbers follow certain
        patterns. A credit card number must have between 13 and 16 digits. It must start
        with:
        ■     4 for Visa cards
        ■     5 for Master cards
        ■     37 for American Express cards
        ■     6 for Discover cards
        In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card
        numbers. The algorithm is useful to determine whether a card number is entered
        correctly or whether a credit card is scanned correctly by a scanner. All credit
        card numbers are generated following this validity check, commonly known as
        the Luhn check or the Mod 10 check, which can be described as follows (for illus-
        tration, consider the card number 4388576018402626):
        1. Double every second digit from right to left. If doubling of a digit results in a
           two-digit number, add up the two digits to get a single-digit number.
            2*2=4
            2*2=4
            4*2=8
            1*2=2
            6 * 2 = 12 (1 + 2 = 3)
            5 * 2 = 10 (1 + 0 = 1)
            8 * 2 = 16 (1 + 6 = 7)
            4*2=8
        2. Now add all single-digit numbers from Step 1.
           4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37
        3. Add all digits in the odd places from right to left in the card number.
           6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38
        4. Sum the results from Step 2 and Step 3.
           37 + 38 = 75
        5. If the result from Step 4 is divisible by 10, the card number is valid; otherwise,
           it is invalid. For example, the number 4388576018402626 is invalid, but the
           number 4388576018410707 is valid.
        Write a program that prompts the user to enter a credit card number as a long
        integer. Display whether the number is valid or invalid. Design your program to
        use the following methods:

            /** Return true if the card number is valid */
            public static boolean isValid(long number)

            /** Get the result from Step 2 */
            public static int sumOfDoubleEvenPlace(long number)
196 Chapter 5 Methods
                             /** Return this number if it is a single digit, otherwise, return
                              * the sum of the two digits */
                             public static int getDigit(int number)

                             /** Return sum of odd place digits in number */
                             public static int sumOfOddPlace(long number)

                             /** Return true if the digit d is a prefix for number */
                             public static boolean prefixMatched(long number, int d)

                             /** Return the number of digits in d */
                             public static int getSize(long d)

                             /** Return the first k number of digits from number. If the
                              * number of digits in number is less than k, return number. */
                             public static long getPrefix(long number, int k)

                   5.32** (Game: chance of winning at craps) Revise Exercise 5.29 to run it 10000 times
                           and display the number of winning games.
                   5.33*** (Current date and time) Invoking System.currentTimeMillis() returns
                           the elapse time in milliseconds since midnight of January 1, 1970. Write a pro-
                           gram that displays the date and time. Here is a sample run:


                    Current date and time is May 16, 2009 10:34:23



                   5.34** (Printing calendar) Exercise 3.21 uses Zeller’s congruence to calculate the day
                             of the week. Simplify Listing 5.12, PrintCalendar.java, using Zeller’s algorithm
                             to get the start day of the month.
                   5.35      (Geometry: area of a pentagon) The area of a pentagon can be computed using
                             the following formula:
                                                                      5 * s2
                                                           Area =
                                                                            p
                                                                  4 * tan a b
                                                                             5
                             Write a program that prompts the user to enter the side of a pentagon and dis-
                             plays its area.
                   5.36*     (Geometry: area of a regular polygon) A regular polygon is an n-sided polygon
                             in which all sides are of the same length and all angles have the same degree
                             (i.e., the polygon is both equilateral and equiangular). The formula for comput-
                             ing the area of a regular polygon is

                                                                     n * s2
                                                         Area =               .
                                                                           p
                                                                  4 * tan a b
                                                                           n
                             Write a method that returns the area of a regular polygon using the following
                             header:

                             public static double area(int n, double side)

                             Write a main method that prompts the user to enter the number of sides and the
                             side of a regular polygon and displays its area.
                                                           CHAPTER 6
SINGLE-DIMENSIONAL ARRAYS
Objectives
■   To describe why arrays are necessary in programming (§6.1).
■   To declare array reference variables and create arrays (§§6.2.1–6.2.2).
■   To initialize the values in an array (§6.2.3).
■   To access array elements using indexed variables (§6.2.4).
■   To declare, create, and initialize an array using an array
    initializer (§6.2.5).
■   To program common array operations (displaying arrays,
    summing all elements, finding min and max elements,
    random shuffling, shifting elements) (§6.2.6).
■   To simplify programming using the for-each loops (§6.2.7).
■   To apply arrays in the LottoNumbers and DeckOfCards
    problems (§§6.3–6.4).
■   To copy contents from one array to another (§6.5).
■   To develop and invoke methods with array arguments and return
    value (§6.6–6.7).
■   To define a method with variable-length argument list (§6.8).
■   To search elements using the linear (§6.9.1)
    or binary (§6.9.2) search algorithm.
■   To sort an array using the selection sort (§6.10.1)
■   To sort an array using the insertion sort (§6.10.2).
■   To use the methods in the Arrays class (§6.11).
198 Chapter 6 Single-Dimensional Arrays

                        6.1 Introduction
problem                 Often you will have to store a large number of values during the execution of a program. Sup-
                        pose, for instance, that you need to read 100 numbers, compute their average, and find out
                        how many numbers are above the average. Your program first reads the numbers and com-
                        putes their average, then compares each number with the average to determine whether it is
                        above the average. In order to accomplish this task, the numbers must all be stored in vari-
                        ables. You have to declare 100 variables and repeatedly write almost identical code 100 times.
why array?              Writing a program this way would be impractical. So, how do you solve this problem?
                           An efficient, organized approach is needed. Java and most other high-level languages pro-
what is array?          vide a data structure, the array, which stores a fixed-size sequential collection of elements of
                        the same type. In the present case, you can store all 100 numbers into an array and access
                        them through a single array variable. The solution may look like this:

                            1 public class AnalyzeNumbers {
                            2   public static void main(String[] args) {
                            3     final int NUMBER_OF_ELEMENTS = 100;
declare array               4     double[] numbers = new double[NUMBER_OF_ELEMENTS];
                            5     double sum = 0;
                            6
                            7     java.util.Scanner input = new java.util.Scanner(System.in);
                            8     for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
                            9       System.out.print("Enter a new number: ");
store number in array      10       numbers[i] = input.nextDouble();
                           11       sum += numbers[i];
                           12     }
                           13
get average                14     double average = sum / NUMBER_OF_ELEMENTS;
                           15
                           16     int count = 0; // The number of elements above average
                           17     for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
above average?             18       if (numbers[i] > average)
                           19         count++;
                           20
                           21     System.out.println("Average is " + average);
                           22     System.out.println("Number of elements above the average "
                           23       + count);
                           24   }
                           25 }

                        The program creates an array of 100 elements in line 4, stores numbers into the array in line
                        10, adds each number to sum in line 11, and obtains the average in line 14. It then compares
                        each number in the array with the average to count the number of values above the average
                        (lines 16–19).
                            This chapter introduces single-dimensional arrays. The next chapter will introduce two-
                        dimensional and multidimensional arrays.


                        6.2 Array Basics
                        An array is used to store a collection of data, but often we find it more useful to think of an
                        array as a collection of variables of the same type. Instead of declaring individual variables,
                        such as number0, number1, Á , and number99, you declare one array variable such as
                        numbers and use numbers[0], numbers[1], Á , and numbers[99] to represent individ-
                        ual variables. This section introduces how to declare array variables, create arrays, and
                        process arrays using indexed variables.
                                                                                                      6.2 Array Basics 199

6.2.1 Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array and specify
the array’s element type. Here is the syntax for declaring an array variable:                          element type

     elementType[] arrayRefVar;

The elementType can be any data type, and all elements in the array will have the same data
type. For example, the following code declares a variable myList that references an array of
double elements.

     double[] myList;


       Note
       You can also use elementType arrayRefVar[] to declare an array variable. This style comes       preferred syntax
       from the C language and was adopted in Java to accommodate C programmers. The style
       elementType[] arrayRefVar is preferred.


6.2.2      Creating Arrays
Unlike declarations for primitive data type variables, the declaration of an array variable does
not allocate any space in memory for the array. It creates only a storage location for the refer-
ence to an array. If a variable does not contain a reference to an array, the value of the variable
is null. You cannot assign elements to an array unless it has already been created. After an
array variable is declared, you can create an array by using the new operator with the follow-
ing syntax:

     arrayRefVar = new elementType[arraySize];                                                         new operator

This statement does two things: (1) it creates an array using new elementType[array-
Size]; (2) it assigns the reference of the newly created array to the variable arrayRefVar.
   Declaring an array variable, creating an array, and assigning the reference of the array to
the variable can be combined in one statement, as shown below:

     elementType arrayRefVar = new elementType[arraySize];

or

     elementType arrayRefVar[] = new elementType[arraySize];

Here is an example of such a statement:

     double[] myList = new double[10];

This statement declares an array variable, myList, creates an array of ten elements of
double type, and assigns its reference to myList. To assign values to the elements, use the
syntax:

     arrayRefVar[index] = value;

For example, the following code initializes the array.

     myList[0]   =   5.6;
     myList[1]   =   4.5;
     myList[2]   =   3.3;
     myList[3]   =   13.2;
200 Chapter 6 Single-Dimensional Arrays
                              myList[4]       =   4.0;
                              myList[5]       =   34.33;
                              myList[6]       =   34.0;
                              myList[7]       =   45.45;
                              myList[8]       =   99.993;
                              myList[9]       =   11123;

                           The array is pictured in Figure 6.1.

                                                                    double[] myList = new double[10];

                                          myList reference
                                                                           myList[0]             5.6
                                                                           myList[1]             4.5

                                     Array reference                       myList[2]             3.3
                                        variable                           myList[3]             13.2
                                                                           myList[4]             4.0
                                              Array element at             myList[5]            34.33                   Element value
                                                  index 5
                                                                           myList[6]             34.0
                                                                           myList[7]            45.45
                                                                           myList[8]           99.993
                                                                           myList[9]            11123

                           FIGURE 6.1 The array myList has ten elements of double type and int indices from 0 to 9.


                                 Note
array vs. array variable         An array variable that appears to hold an array actually contains a reference to that array. Strictly
                                 speaking, an array variable and an array are different, but most of the time the distinction can be
                                 ignored. Thus it is all right to say, for simplicity, that myList is an array, instead of stating, at greater
                                 length, that myList is a variable that contains a reference to an array of ten double elements.


                           6.2.3      Array Size and Default Values
                           When space for an array is allocated, the array size must be given, specifying the number of ele-
                           ments that can be stored in it. The size of an array cannot be changed after the array is created.
array length               Size can be obtained using arrayRefVar.length. For example, myList.length is 10.
                              When an array is created, its elements are assigned the default value of 0 for the numeric
default values             primitive data types, '\u0000' for char types, and false for boolean types.


                           6.2.4      Array Indexed Variables
0 based                    The array elements are accessed through the index. Array indices are 0 based; that is, they
                           range from 0 to arrayRefVar.length-1. In the example in Figure 6.1, myList holds ten
                           double values, and the indices are from 0 to 9.
indexed variables             Each element in the array is represented using the following syntax, known as an indexed
                           variable:
                              arrayRefVar[index];

                           For example, myList[9] represents the last element in the array myList.

                                 Caution
                                 Some languages use parentheses to reference an array element, as in myList(9). But Java uses
                                 brackets, as in myList[9].
                                                                                                                 6.2 Array Basics 201
After an array is created, an indexed variable can be used in the same way as a regular variable.
For example, the following code adds the values in myList[0] and myList[1] to myList[2].
   myList[2] = myList[0] + myList[1];

The following loop assigns 0 to myList[0], 1 to myList[1], Á , and 9 to myList[9]:
   for (int i = 0; i < myList.length; i++) {
     myList[i] = i;
   }


6.2.5      Array Initializers
Java has a shorthand notation, known as the array initializer, which combines in one state-
ment declaring an array, creating an array, and initializing, using the following syntax:
   elementType[] arrayRefVar = {value0, value1, ..., valuek};

For example,
   double[] myList = {1.9, 2.9, 3.4, 3.5};

This statement declares, creates, and initializes the array myList with four elements, which is
equivalent to the statements shown below:
   double[] myList = new double[4];
   myList[0] = 1.9;
   myList[1] = 2.9;
   myList[2] = 3.4;
   myList[3] = 3.5;


      Caution
      The new operator is not used in the array-initializer syntax. Using an array initializer, you have to
      declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error.
      Thus the next statement is wrong:

      double[] myList;
      myList = {1.9, 2.9, 3.4, 3.5};


6.2.6      Processing Arrays
When processing array elements, you will often use a for loop—for two reasons:
      ■   All of the elements in an array are of the same type. They are evenly processed in the
          same fashion repeatedly using a loop.
      ■   Since the size of the array is known, it is natural to use a for loop.
Assume the array is created as follows:
   double[] myList = new double[10];

Here are some examples of processing arrays:
   1. (Initializing arrays with input values) The following loop initializes the array myList
      with user input values.
          java.util.Scanner input = new java.util.Scanner(System.in);
          System.out.print("Enter " + myList.length + " values: ");
          for (int i = 0; i < myList.length; i++)
            myList[i] = input.nextDouble();
202 Chapter 6 Single-Dimensional Arrays
                        2. (Initializing arrays with random values) The following loop initializes the array
                           myList with random values between 0.0 and 100.0, but less than 100.0.
                              for (int i = 0; i < myList.length; i++) {
                                myList[i] = Math.random() * 100;
                              }

                        3. (Displaying arrays) To print an array, you have to print each element in the array using
                           a loop like the following:
                              for (int i = 0; i < myList.length; i++) {
                                System.out.print(myList[i] + " ");
                              }


                          Tip
print character array      For an array of the char[] type, it can be printed using one print statement. For example, the fol-
                           lowing code displays Dallas:
                           char[] city = {'D', 'a', 'l', 'l', 'a', 's'};
                           System.out.println(city);

                        4. (Summing all elements) Use a variable named total to store the sum. Initially total
                           is 0. Add each element in the array to total using a loop like this:
                              double total = 0;
                              for (int i = 0; i < myList.length; i++) {
                                total += myList[i];
                              }

                        5. (Finding the largest element) Use a variable named max to store the largest element. Ini-
                           tially max is myList[0]. To find the largest element in the array myList, compare
                           each element with max, and update max if the element is greater than max.
                              double max = myList[0];
                              for (int i = 1; i < myList.length; i++) {
                                if (myList[i] > max) max = myList[i];
                              }

                        6. (Finding the smallest index of the largest element) Often you need to locate the largest
                           element in an array. If an array has more than one largest element, find the smallest
                           index of such an element. Suppose the array myList is 51, 5, 3, 4, 5, 56. The largest
                           element is 5 and the smallest index for 5 is 1. Use a variable named max to store the
                           largest element and a variable named indexOfMax to denote the index of the largest
                           element. Initially max is myList[0], and indexOfMax is 0. Compare each element in
                           myList with max, and update max and indexOfMax if the element is greater than
                           max.
                              double max = myList[0];
                              int indexOfMax = 0;
                              for (int i = 1; i < myList.length; i++) {
                                if (myList[i] > max) {
                                  max = myList[i];
                                  indexOfMax = i;
                                }
                              }

                           What is the consequence if (myList[i] > max) is replaced by (myList[i] >= max)?
                        7. (Random shuffling) In many applications, you need to randomly reorder the elements in
Video Note                 an array. This is called a shuffling. To accomplish this, for each element myList[i],
Random shuffling           randomly generate an index j and swap myList[i] with myList[j], as follows:
                                                                                                             6.2 Array Basics 203
    for (int i = 0; i < myList.length; i++) {                                            myList
      // Generate an index j randomly                                          i         [0]
      int index = (int) (Math.random()                                                   [1]
        * mylist.length);
                                                                                               .
                                                                                                     swap
         // Swap myList[i] with myList[j]                                                      .
         double temp = myList[i];                                                              .
         myList[i] = myList[index]
                                                                                     [index]
         myList[index] = temp;
    }                                                                        A random index



   8. (Shifting elements) Sometimes you need to shift the elements left or right. Here is an
      example to shift the elements one position to the left and fill the last element with the
      first element:


double temp = myList[0]; // Retain the first element

// Shift elements left                                              myList
for (int i = 1; i < myList.length; i++) {
  myList[i - 1] = myList[i];
}

// Move the first element to fill in the last position
myList[myList.length - 1] = temp;




6.2.7        For-each Loops
Java supports a convenient for loop, known as a for-each loop or enhanced for loop, which
enables you to traverse the array sequentially without using an index variable. For example,
the following code displays all the elements in the array myList:

   for (double u: myList) {
     System.out.println(u);
   }

You can read the code as “for each element u in myList do the following.” Note that the vari-
able, u, must be declared the same type as the elements in myList.
   In general, the syntax for a for-each loop is

   for (elementType element: arrayRefVar) {
     // Process the element
   }

You still have to use an index variable if you wish to traverse the array in a different order or
change the elements in the array.

      Caution
        Accessing an array out of bounds is a common programming error that throws a runtime
        ArrayIndexOutOfBoundsException. To avoid it, make sure that you do not use an index                   ArrayIndexOutOfBounds-
        beyond arrayRefVar.length – 1.                                                                          Exception
           Programmers often mistakenly reference the first element in an array with index 1, but it
        should be 0. This is called the off-by-one error. It is a common error in a loop to use <= where <    off-by-one error
        should be used. For example, the following loop is wrong,

        for (int i = 0; i <= list.length; i++)
          System.out.print(list[i] + " ");

        The <= should be replaced by <.
204 Chapter 6 Single-Dimensional Arrays

                    6.3 Problem: Lotto Numbers
                    Each ticket for the Pick-10 lotto has 10 unique numbers ranging from 1 to 99. Suppose you
Video Note
Lotto numbers       buys a lot of tickets and like to have them cover all numbers from 1 to 99. Write a program that
                    reads the ticket numbers from a file and checks whether all numbers are covered. Assume the
                    last number in the file is 0. Suppose the file contains the numbers
                       80    3 87 62 30 90 10 21 46 27
                       12    40 83 9 39 88 95 59 20 37
                       80    40 87 67 31 90 11 24 56 77
                       11    48 51 42 8 74 1 41 36 53
                       52    82 16 72 19 70 44 56 29 33
                       54    64 99 14 23 22 94 79 55 2
                       60    86 34 4 31 63 84 89 7 78
                       43    93 97 45 25 38 28 26 85 49
                       47    65 57 67 73 69 32 71 24 66
                       92    98 96 77 6 75 17 61 58 13
                       35    81 18 15 5 68 91 50 76
                       0

                    Your program should display
                       The tickets cover all numbers

                    Suppose the file contains the numbers
                       11 48 51 42 8 74 1 41 36 53
                       52 82 16 72 19 70 44 56 29 33
                       0

                    Your program should display
                       The tickets don't cover all numbers

                    How do you mark a number as covered? You can create an array with 99 boolean elements.
                    Each element in the array can be used to mark whether a number is covered. Let the array be
                    isCovered. Initially, each element is false, as shown in Figure 6.2(a). Whenever a number
                    is read, its corresponding element is set to true. Suppose the numbers entered are 1, 2, 3, 99,
                    0. When number 1 is read, isCovered[0] is set to true (see Figure 6.2(b)). When number
                    2 is read, isCovered[2 - 1] is set to true (see Figure 6.2(c)). When number 3 is read,



                         isCovered          isCovered        isCovered         isCovered         isCovered

                             [0]   false      [0]   true       [0]   true       [0]   true        [0]   true
                             [1]   false      [1]   false      [1]   true       [1]   true        [1]   true
                             [2]   false      [2]   false      [2]   false      [2]   true        [2]   true
                             [3]   false      [3]   false      [3]   false      [3]   false       [3]   false
                                     .                .                .                .                  .
                                     .                .                .                .                  .
                                     .                .                .                .                  .
                            [97]   false     [97]   false     [97]   false     [97]   false      [97]   false
                            [98]   false     [98]   false     [98]   false     [98]   false      [98]   true

                                   (a)              (b)              (c)               (d)               (e)

                    FIGURE 6.2     If number i appears in a Lotto ticket, isCovered[i-1] is set to true.
                                                                               6.3 Problem: Lotto Numbers 205
isCovered[3 - 1] is set to true (see Figure 6.2(d)). When number 99 is read, set
isCovered[98] to true (see Figure 6.2(e)).
   The algorithm for the program can be described as follows:
   for each number k read from the file,
     mark number k as covered by setting isCovered[k – 1] true;

   if every isCovered[i] is true
     The tickets cover all numbers
   else
     The tickets don't cover all numbers

The complete program is given in Listing 6.1.

LISTING 6.1 LottoNumbers.java
 1 import java.util.Scanner;
 2
 3 public class LottoNumbers {
 4   public static void main(String args[]) {
 5     Scanner input = new Scanner(System.in);
 6     boolean[] isCovered = new boolean[99]; // Default is false                                create and initialize array
 7
 8     // Read each number and mark its corresponding element covered
 9     int number = input.nextInt();                                                             read number
10     while (number != 0) {
11       isCovered[number - 1] = true;                                                           mark number covered
12       number = input.nextInt();                                                               read number
13     }
14
15     // Check whether all covered
16     boolean allCovered = true; // Assume all covered initially
17     for (int i = 0; i < 99; i++)
18       if (!isCovered[i]) {
19          allCovered = false; // Find one number not covered
20          break;
21       }
22
23     // Display result
24     if (allCovered)                                                                           check allCovered?
25       System.out.println("The tickets cover all numbers");
26     else
27       System.out.println("The tickets don't cover all numbers");
28   }
29 }

Suppose you have created a text file named LottoNumbers.txt that contains the input data 2 5
6 5 4 3 23 43 2 0. You can run the program using the following command:

   java LottoNumbers < LottoNumbers.txt

The program can be traced as follows:
   The program creates an array of 99 boolean elements and initializes each element to
false (line 6). It reads the first number from the file (line 9). The program then repeats the
following operations in a loop:
      ■   If the number is not zero, set its corresponding value in array isCovered to true
          (line 11);
      ■   Read the next number (line 12).
206 Chapter 6 Single-Dimensional Arrays

                     line       Representative elements in array isCovered              number     allCovered
                                [1]     [2]     [3]     [4]     [5]     [22]    [42]
                      6         false   false   false   false   false   false   false
                      9                                                                  2
                     11         true
                     12                                                                  5
                     11                                 true
                     12                                                                  6
                     11                                         true
                     12                                                                  5
                     11                                 true
                     12                                                                  4
                     11                         true
                     12                                                                  3
                     11                 true
                     12                                                                 23
                     11                                                 true
                     12                                                                 43
                     11                                                         true
                     12                                                                  2
                     11         true
                     12                                                                  0
                     16                                                                            true
                     18(i=0)                                                                       false


                    When the input is 0, the input ends. The program checks whether all numbers are covered in
                    lines 16–21 and displays the result in lines 24–27.


                    6.4 Problem: Deck of Cards
                    The problem is to write a program that picks four cards randomly from a deck of 52 cards. All
                    the cards can be represented using an array named deck, filled with initial values 0 to 51, as
                    follows:
                       int[] deck = new int[52];

                       // Initialize cards
                       for (int i = 0; i < deck.length; i++)
                         deck[i] = i;

                    Card numbers 0 to 12, 13 to 25, 26 to 38, 39 to 51 represent 13 Spades, 13 Hearts, 13 Dia-
                    monds, and 13 Clubs, respectively, as shown in Figure 6.3. After shuffling the array deck,
                    pick the first four cards from deck. cardNumber / 13 determines the suit of the card and
                    cardNumber % 13 determines the rank of the card.
                       Listing 6.2 gives the solution to the problem.
                                                                             6.4 Problem: Deck of Cards 207

LISTING 6.2 DeckOfCards.java
 1 public class DeckOfCards {
 2   public static void main(String[] args) {
 3     int[] deck = new int[52];                                                           create array deck
 4     String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};                         array of strings
 5     String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9",                    array of strings
 6       "10", "Jack", "Queen", "King"};
 7
 8     // Initialize cards
 9     for (int i = 0; i < deck.length; i++)                                               initialize deck
10       deck[i] = i;
11
12     // Shuffle the cards
13     for (int i = 0; i < deck.length; i++) {                                             shuffle deck
14       // Generate an index randomly
15       int index = (int)(Math.random() * deck.length);
16       int temp = deck[i];
17       deck[i] = deck[index];
18       deck[index] = temp;
19     }
20
21     // Display the first four cards
22     for (int i = 0; i < 4; i++) {
23       String suit = suits[deck[i] / 13];                                                suit of a card
24       String rank = ranks[deck[i] % 13];                                                rank of a card
25       System.out.println("Card number " + deck[i] + ": "
26         + rank + " of " + suit);
27     }
28   }
29 }


       Card   number     6: 7 of Spades
       Card   number     48: 10 of Clubs
       Card   number     11: Queen of Spades
       Card   number     24: Queen of Hearts



                                   deck                        deck
  0                             [0] 0                       [0] 6      Card number 6 is
  .                              .    .                     [1] 48     7 of Spades
  .      13 Spades ( )           .    .                     [2] 11
  .                              .    .                     [3] 24
                               [12] 12                      [4] .      Card number 48 is
  12
  13                           [13] 13                      [5] .      10 of Clubs
   .                             .    .                      .     .
   .     13 Hearts ( )           .    .                      .     .
   .                                                                   Card number 11 is
                                 .    .                      .     .   Queen of Spades
  25                           [25] 25    Random shuffle   [25] .
  26                           [26] 26                     [26] .
   .                             .    .                      .     .
   .     13 Diamonds ( )         .    .                      .     .   Card number 24 is
   .                             .    .                      .     .   Queen of Hearts
  38                           [38] 38                     [38] .
  39                           [39] 39                     [39] .
   .                             .    .                      .     .
   .     13 Clubs ( )            .    .                      .     .
   .                             .    .                      .     .
  51                           [51] 51                     [51] .

FIGURE 6.3     52 cards are stored in an array named deck.
208 Chapter 6 Single-Dimensional Arrays
                     The program defines an array suits for four suits (line 4) and an array ranks for 13 cards in
                     a suits (lines 5–6). Each element in these arrays is a string.
                        The deck is initialized with values 0 to 51 in lines 9–10. A deck value 0 represents card
                     Ace of Spades, 1 represents card 2 of Spades, 13 represents card Ace of Hearts, 14 represents
                     card 2 of Hearts.
                        Lines 13–19 randomly shuffle the deck. After a deck is shuffled, deck[i] contains an
                     arbitrary value. deck[i] / 13 is 0, 1, 2, or 3, which determines a suit (line 23). deck[i] %
                     13 is a value between 0 and 12, which determines a rank (line 24).


                     6.5 Copying Arrays
                     Often, in a program, you need to duplicate an array or a part of an array. In such cases you
                     could attempt to use the assignment statement (=), as follows:

copy reference          list2 = list1;

                     This statement does not copy the contents of the array referenced by list1 to list2, but
                     merely copies the reference value from list1 to list2. After this statement, list1 and
                     list2 reference to the same array, as shown in Figure 6.4. The array previously referenced
garbage collection   by list2 is no longer referenced; it becomes garbage, which will be automatically collected
                     by the Java Virtual Machine.


                                 Before the assignment                   After the assignment
                                 list2 = list1;                          list2 = list1;
                                   list1                                   list1
                                                     Contents                                   Contents
                                                     of list1                                   of list1


                                   list2                                   list2
                                                    Contents                                    Contents
                                                    of list2                                    of list2




                     FIGURE 6.4 Before the assignment statement, list1 and list2 point to separate memory
                     locations. After the assignment, the reference of the list1 array is passed to list2.


                        In Java, you can use assignment statements to copy primitive data type variables, but not
                     arrays. Assigning one array variable to another array variable actually copies one reference to
                     another and makes both variables point to the same memory location.
                        There are three ways to copy arrays:
                           ■   Use a loop to copy individual elements one by one.
                           ■   Use the static arraycopy method in the System class.
                           ■   Use the clone method to copy arrays; this will be introduced in Chapter 14,
                               “Abstract Classes and Interfaces.”
                     You can write a loop to copy every element from the source array to the corresponding ele-
                     ment in the target array. The following code, for instance, copies sourceArray to
                     targetArray using a for loop.

                        int[] sourceArray = {2, 3, 1, 5, 10};
                        int[] targetArray = new int[sourceArray.length];
                                                                                           6.6 Passing Arrays to Methods 209
  for (int i = 0; i < sourceArray.length; i++) {
    targetArray[i] = sourceArray[i];
  }

Another approach is to use the arraycopy method in the java.lang.System class to copy
arrays instead of using a loop. The syntax for arraycopy is shown below:
  arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);                                         arraycopy method

The parameters src_pos and tar_pos indicate the starting positions in sourceArray and
targetArray, respectively. The number of elements copied from sourceArray to
targetArray is indicated by length. For example, you can rewrite the loop using the fol-
lowing statement:
  System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

The arraycopy method does not allocate memory space for the target array. The target array
must have already been created with its memory space allocated. After the copying takes
place, targetArray and sourceArray have the same content but independent memory
locations.

     Note
     The arraycopy method violates the Java naming convention. By convention, this method
     should be named arrayCopy (i.e., with an uppercase C).


6.6 Passing Arrays to Methods
Just as you can pass primitive type values to methods, you can also pass arrays to methods.
For example, the following method displays the elements in an int array:

  public static void printArray(int[] array) {
    for (int i = 0; i < array.length; i++) {
      System.out.print(array[i] + " ");
    }
  }

You can invoke it by passing an array. For example, the following statement invokes the
printArray method to display 3, 1, 2, 6, 4, and 2.
  printArray(new int[]{3, 1, 2, 6, 4, 2});


     Note
     The preceding statement creates an array using the following syntax:
     new elementType[]{value0, value1, ..., valuek};

     There is no explicit reference variable for the array. Such array is called an anonymous array.     anonymous arrays

   Java uses pass-by-value to pass arguments to a method. There are important differences                pass-by-value
between passing the values of variables of primitive data types and passing arrays.
     ■   For an argument of a primitive type, the argument’s value is passed.
     ■   For an argument of an array type, the value of the argument is a reference to an array;
         this reference value is passed to the method. Semantically, it can be best described as
         pass-by-sharing, i.e., the array in the method is the same as the array being passed.           pass-by-sharing
         So if you change the array in the method, you will see the change outside the
         method.
210 Chapter 6 Single-Dimensional Arrays
                    Take the following code, for example:
                       public class Test {
                         public static void main(String[] args) {
                           int x = 1; // x represents an int value
                           int[] y = new int[10]; // y represents an array of int values

                               m(x, y) ; // Invoke m with arguments x and y

                               System.out.println("x is " + x);
                               System.out.println("y[0] is " + y[0]);
                           }

                           public static void m(int number, int[] numbers) {
                             number = 1001; // Assign a new value to number
                             numbers[0] = 5555; // Assign a new value to numbers[0]
                           }
                       }


                           x is 1
                           y[0] is 5555



                    You will see that after m is invoked, x remains 1, but y[0] is 5555. This is because y and
                    numbers, although they are independent variables, reference to the same array, as illustrated
                    in Figure 6.5. When m(x, y) is invoked, the values of x and y are passed to number and
                    numbers. Since y contains the reference value to the array, numbers now contains the same
                    reference value to the same array.


                                Stack                                             Heap

                                Space required for
                                method m
                                int[] numbers:     reference
                                                                                                          Arrays are
                                int number: 1                                        An array of          stored in a
                                Space required for the                               ten int              heap.
                                main method                                          values is
                                    int[] y: reference                               stored here
                                    int x: 1

                    FIGURE 6.5 The primitive type value in x is passed to number, and the reference value in y
                    is passed to numbers.



                           Note
heap                        The JVM stores the array in an area of memory called the heap, which is used for dynamic mem-
                            ory allocation where blocks of memory are allocated and freed in an arbitrary order.


                    6.6.1 Passing Array Arguments
                    Listing 6.3 gives another program that shows the difference between passing a primitive data
                    type value and an array reference variable to a method.
                       The program contains two methods for swapping elements in an array. The first method, named
                    swap, fails to swap two int arguments. The second method, named swapFirstTwoInArray,
                    successfully swaps the first two elements in the array argument.
                                                                            6.6 Passing Arrays to Methods 211

LISTING 6.3 TestPassArray.java
 1 public class TestPassArray {
 2   /** Main method */
 3   public static void main(String[] args) {
 4     int[] a = {1, 2};
 5
 6     // Swap elements using the swap method
 7     System.out.println("Before invoking swap");
 8     System.out.println("array is {" + a[0] + ", " + a[1] + "}");
 9     swap(a[0], a[1]);                                                                        false swap
10     System.out.println("After invoking swap");
11     System.out.println("array is {" + a[0] + ", " + a[1] + "}");
12
13     // Swap elements using the swapFirstTwoInArray method
14     System.out.println("Before invoking swapFirstTwoInArray");
15     System.out.println("array is {" + a[0] + ", " + a[1] + "}");
16     swapFirstTwoInArray(a);                                                                  swap array elements
17     System.out.println("After invoking swapFirstTwoInArray");
18     System.out.println("array is {" + a[0] + ", " + a[1] + "}");
19   }
20
21   /** Swap two variables */
22   public static void swap(int n1, int n2) {
23     int temp = n1;
24     n1 = n2;
25     n2 = temp;
26   }
27
28   /** Swap the first two elements in the array */
29   public static void swapFirstTwoInArray(int[] array) {
30     int temp = array[0];
31     array[0] = array[1];
32     array[1] = temp;
33   }
34 }


    Before invoking swap
    array is {1, 2}
    After invoking swap
    array is {1, 2}
    Before invoking swapFirstTwoInArray
    array is {1, 2}
    After invoking swapFirstTwoInArray
    array is {2, 1}


As shown in Figure 6.6, the two elements are not swapped using the swap method. However,
they are swapped using the swapFirstTwoInArray method. Since the parameters in the swap
method are primitive type, the values of a[0] and a[1] are passed to n1 and n2 inside the
method when invoking swap(a[0], a[1]). The memory locations for n1 and n2 are indepen-
dent of the ones for a[0] and a[1]. The contents of the array are not affected by this call.
    The parameter in the swapFirstTwoInArray method is an array. As shown in Figure 6.6,
the reference of the array is passed to the method. Thus the variables a (outside the method)
and array (inside the method) both refer to the same array in the same memory location.
Therefore, swapping array[0] with array[1] inside the method swapFirstTwoInArray
is the same as swapping a[0] with a[1] outside of the method.
212 Chapter 6 Single-Dimensional Arrays

                          Stack                        Heap                Stack
                                                                           Space required for the
                                                                           swapFirstTwoInArray
                          Space required for the                           method
                          swap method                                      int[] array reference
                                          n2: 2
                                          n1: 1
                          Space required for the                           Space required for the
                          main method                                      main method
                          int[] a reference                                   int[] a reference
                                                         a[0]: 1
                                                         a[1]: 2

                     Invoke swap(int n1, int n2). The arrays are Invoke swapFirstTwoInArray(int[]
                     The primitive type values in    stored in a array). The reference value in a is passed
                     a[0] and a[1] are passed to the heap.       to the swapFirstTwoInArray method.
                     swap method.

                    FIGURE 6.6    When passing an array to a method, the reference of the array is passed to the
                    method.


                    6.7 Returning an Array from a Method
                    You can pass arrays when invoking a method. A method may also return an array. For exam-
                    ple, the method shown below returns an array that is the reversal of another array:


                     l public static int[] reverse(int[] list) {
create array         2   int[] result = new int[list.length];
                     3
                     4   for (int i = 0, j = result.length - 1;
                     5        i < list.length; i++, j--) {
                     6     result[j] = list[i];
                     7   }                                 list
                     8
return array         9   return result;                 result
                    10 }


                      Line 2 creates a new array result. Lines 4–7 copy elements from array list to array
                    result. Line 9 returns the array. For example, the following statement returns a new array
                    list2 with elements 6, 5, 4, 3, 2, 1.

                      int[] list1 = {1, 2, 3, 4, 5, 6};
                      int[] list2 = reverse(list1);


                    6.7.1 Case Study: Counting the Occurrences of Each Letter
                    Listing 6.4 presents a program to count the occurrences of each letter in an array of charac-
                    ters. The program does the following:
                       1. Generate 100 lowercase letters randomly and assign them to an array of characters, as
                          shown in Figure 6.7(a). You can obtain a random letter by using the getRandomLow-
                          erCaseLetter() method in the RandomCharacter class in Listing 5.10

                       2. Count the occurrences of each letter in the array. To do so, create an array, say counts,
                          of 26 int values, each of which counts the occurrences of a letter, as shown in Figure
                          6.7(b). That is, counts[0] counts the number of a’s, counts[1] counts the number
                          of b’s, and so on.
                                                               6.7 Returning an Array from a Method 213

                 chars[0]                       counts[0]
                 chars[1]                       counts[1]
                     …          …                   …           …
                     …          …                   …           …
                chars[98]                      counts[24]
                chars[99]                      counts[25]
                                (a)                             (b)

FIGURE 6.7 The chars array stores 100 characters, and the counts array stores 26 counts,
each of which counts the occurrences of a letter.



LISTING 6.4 CountLettersInArray.java
 1 public class CountLettersInArray {
 2   /** Main method */
 3   public static void main(String[] args) {
 4     // Declare and create an array
 5     char[] chars = createArray();                                                       create array
 6
 7     // Display the array
 8     System.out.println("The lowercase letters are:");
 9     displayArray(chars);                                                                pass array
10
11     // Count the occurrences of each letter
12     int[] counts = countLetters(chars) ;                                                return array
13
14     // Display counts
15     System.out.println();
16     System.out.println("The occurrences of each letter are:");
17     displayCounts(counts);                                                              pass array
18   }
19
20   /** Create an array of characters */
21   public static char[] createArray() {
22     // Declare an array of characters and create it
23     char[] chars = new char[100];
24
25     // Create lowercase letters randomly and assign
26     // them to the array
27     for (int i = 0; i < chars.length; i++)
28       chars[i] = RandomCharacter.getRandomLowerCaseLetter();
29
30     // Return the array
31     return chars;
32   }
33
34   /** Display the array of characters */
35   public static void displayArray(char[] chars) {
36     // Display the characters in the array 20 on each line
37     for (int i = 0; i < chars.length; i++) {
38       if ((i + 1) % 20 == 0)
39         System.out.println(chars[i]);
214 Chapter 6 Single-Dimensional Arrays
                    40             else
                    41               System.out.print(chars[i] + " ");
                    42         }
                    43     }
                    44
                    45     /** Count the occurrences of each letter */
                    46     public static int[] countLetters(char[] chars) {
                    47       // Declare and create an array of 26 int
                    48       int[] counts = new int[26];
                    49
                    50         // For each lowercase letter in the array, count it
                    51         for (int i = 0; i < chars.length; i++)
count               52           counts[chars[i] - 'a']++;
                    53
                    54         return counts;
                    55     }
                    56
                    57     /** Display counts */
                    58     public static void displayCounts(int[] counts) {
                    59       for (int i = 0; i < counts.length; i++) {
                    60         if ((i + 1) % 10 == 0)
                    61           System.out.println(counts[i] + " " + (char)(i + 'a'));
                    62         else
                    63           System.out.print(counts[i] + " " + (char)(i + 'a') + " ");
                    64       }
                    65     }
                    66 }



                        The    lowercase   letters   are:
                        e y    l s r i b   k j v j   h a b   z   n   w   b   t   v
                        s c    c k r d w   a m p w   v u n   q   a   m   p   l   o
                        a z    g d e g f   i n d x   m z o   u   l   o   z   j   v
                        h w    i w n t g   x w c d   o t x   h   y   v   z   y   z
                        q e    a m f w p   g u q t   r e n   n   w   f   c   r   f
                        The    occurrences   of each letter are:
                        5 a    3 b 4 c 4 d   4 e 4 f 4 g 3 h 3 i 3 j
                        2 k    3 l 4 m 6 n   4 o 3 p 3 q 4 r 2 s 4 t
                        3 u    5 v 8 w 3 x   3 y 6 z



                    The createArray method (lines 21–32) generates an array of 100 random lowercase letters.
                    Line 5 invokes the method and assigns the array to chars. What would be wrong if you
                    rewrote the code as follows?
                      char[] chars = new char[100];
                      chars = createArray();

                    You would be creating two arrays. The first line would create an array by using new
                    char[100]. The second line would create an array by invoking createArray() and assign
                    the reference of the array to chars. The array created in the first line would be garbage
                    because it is no longer referenced. Java automatically collects garbage behind the scenes.
                    Your program would compile and run correctly, but it would create an array unnecessarily.
                       Invoking getRandomLowerCaseLetter() (line 28) returns a random lowercase letter.
                    This method is defined in the RandomCharacter class in Listing 5.10.
                       The countLetters method (lines 46–55) returns an array of 26 int values, each of
                    which stores the number of occurrences of a letter. The method processes each letter in the
                                                                      6.8 Variable-Length Argument Lists 215
array and increases its count by one. A brute-force approach to count the occurrences of each
letter might be as follows:
   for (int i = 0; i < chars.length; i++)
     if (chars[i] == 'a')
       counts[0]++;
     else if (chars[i] == 'b')
       counts[1]++;
     ...

But a better solution is given in lines 51–52.
     for (int i = 0; i < chars.length; i++)
       counts[chars[i] - 'a']++;

If the letter (chars[i]) is 'a', the corresponding count is counts['a' - 'a'] (i.e.,
counts[0]). If the letter is 'b', the corresponding count is counts['b' - 'a'] (i.e.,
counts[1]), since the Unicode of 'b' is one more than that of 'a'. If the letter is 'z', the
corresponding count is counts['z' - 'a'] (i.e., counts[25]), since the Unicode of 'z' is
25 more than that of 'a'.
   Figure 6.8 shows the call stack and heap during and after executing createArray. See
Review Question 6.14 to show the call stack and heap for other methods in the program.


         Stack                      Heap                  Stack                     Heap

  Space required for the        Array of 100                                   Array of 100
  createArray method            characters                                     characters
        char[] chars: ref
  Space required for the                           Space required for the
  main method                                      main method
        char[] chars: ref                               char[] chars: ref

                (a) Executing                                  (b) After exiting
            createArray in line 5                           createArray in line 5

FIGURE 6.8 (a) An array of 100 characters is created when executing createArray.
(b) This array is returned and assigned to the variable chars in the main method.


6.8 Variable-Length Argument Lists
You can pass a variable number of arguments of the same type to a method. The parameter in
the method is declared as follows:
   typeName... parameterName

In the method declaration, you specify the type followed by an ellipsis 1 Á 2. Only one vari-
able-length parameter may be specified in a method, and this parameter must be the last para-
meter. Any regular parameters must precede it.
   Java treats a variable-length parameter as an array. You can pass an array or a variable
number of arguments to a variable-length parameter. When invoking a method with a variable
number of arguments, Java creates an array and passes the arguments to it. Listing 6.5 con-
tains a method that prints the maximum value in a list of an unspecified number of values.

LISTING 6.5 VarArgsDemo.java
 1 public class VarArgsDemo {
 2   public static void main(String[] args) {
 3     printMax(34, 3, 3, 2, 56.5);                                                             pass variable-length arg list
216 Chapter 6 Single-Dimensional Arrays
pass an array arg        4     printMax(new double[]{1, 2, 3});
                         5   }
                         6
a variable-length arg    7   public static void printMax(double... numbers ) {
   parameter             8     if (numbers.length == 0) {
                         9       System.out.println("No argument passed");
                        10       return;
                        11     }
                        12
                        13     double result = numbers[0];
                        14
                        15     for (int i = 1; i < numbers.length; i++)
                        16       if (numbers[i] > result)
                        17         result = numbers[i];
                        18
                        19     System.out.println("The max value is " + result);
                        20   }
                        21 }

                        Line 3 invokes the printMax method with a variable-length argument list passed to the array
                        numbers. If no arguments are passed, the length of the array is 0 (line 8).
                           Line 4 invokes the printMax method with an array.


                        6.9 Searching Arrays
                        Searching is the process of looking for a specific element in an array—for example, discover-
                        ing whether a certain score is included in a list of scores. Searching is a common task in com-
linear search           puter programming. Many algorithms and data structures are devoted to searching. This
binary search           section discusses two commonly used approaches, linear search and binary search.

                        6.9.1 The Linear Search Approach
                        The linear search approach compares the key element key sequentially with each element in
                        the array. It continues to do so until the key matches an element in the array or the array is
                        exhausted without a match being found. If a match is made, the linear search returns the index
                        of the element in the array that matches the key. If no match is found, the search returns -1.
                        The linearSearch method in Listing 6.6 gives the solution:

                        LISTING 6.6 LinearSearch.java
                         1 public class LinearSearch {
                         2   /** The method for finding a key in the list */
                         3   public static int linearSearch(int[] list, int key) {
                         4     for (int i = 0; i < list.length; i++) {
                         5       if (key == list[i])
                         6         return i;                              [0] [1] [2] …
                         7     }                                     list
                         8     return -1;
                         9   }                                       key Compare key with list[i] for i = 0, 1, …
                        10 }

                        To better understand this method, trace it with the following statements:
                           int[]   list = {1, 4, 4, 2, 5, -3, 6, 2};
                           int i   = linearSearch(list, 4); // Returns 1
                           int j   = linearSearch(list, -4); // Returns -1
                           int k   = linearSearch(list, -3); // Returns 5

                        The linear search method compares the key with each element in the array. The elements can
                        be in any order. On average, the algorithm will have to compare half of the elements in an
                                                                                              6.9 Searching Arrays 217
array before finding the key, if it exists. Since the execution time of a linear search increases
linearly as the number of array elements increases, linear search is inefficient for a large array.


6.9.2      The Binary Search Approach
Binary search is the other common search approach for a list of values. For binary search to
work, the elements in the array must already be ordered. Assume that the array is in ascend-
ing order. The binary search first compares the key with the element in the middle of the array.
Consider the following three cases:
      ■   If the key is less than the middle element, you need to continue to search for the key
          only in the first half of the array.
      ■   If the key is equal to the middle element, the search ends with a match.
      ■   If the key is greater than the middle element, you need to continue to search for the
          key only in the second half of the array.
Clearly, the binary search method eliminates half of the array after each comparison. Some-
times you eliminate half of the elements, and sometimes you eliminate half plus one. Suppose
that the array has n elements. For convenience, let n be a power of 2. After the first compari-
son, n/2 elements are left for further search; after the second comparison, (n/2)/2 elements
are left. After the kth comparison, n/2k elements are left for further search. When k = log2n,
only one element is left in the array, and you need only one more comparison. Therefore, in
the worst case when using the binary search approach, you need log2n+1 comparisons to find
an element in the sorted array. In the worst case for a list of 1024 12102 elements, binary
search requires only 11 comparisons, whereas a linear search requires 1023 comparisons in
the worst case.
   The portion of the array being searched shrinks by half after each comparison. Let low and
high denote, respectively, the first index and last index of the array that is currently being
searched. Initially, low is 0 and high is list.length–1. Let mid denote the index of the
middle element. So mid is (low + high)/2. Figure 6.9 shows how to find key 11 in the list
52, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 796 using binary search.
   You now know how the binary search works. The next task is to implement it in Java. Don’t
rush to give a complete implementation. Implement it incrementally, one step at a time. You
may start with the first iteration of the search, as shown in Figure 6.10(a). It compares the key
with the middle element in the list whose low index is 0 and high index is list.length - 1.



             key is 11             low                           mid                high

             key   50              [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
                            list    2    4    7    10 11 45 50 59 60 66 69 70 79
                                   low       mid          high

                                   [0] [1] [2] [3] [4] [5]
             key   7        list    2    4    7    10 11 45
                                                  low mid high

                                                   [3] [4] [5]
             key       11   list                   10 11 45

FIGURE 6.9 Binary search eliminates half of the list from further consideration after each
comparison.
218 Chapter 6 Single-Dimensional Arrays
                    If key < list[mid], set the high index to mid - 1; if key == list[mid], a match is found
                    and return mid; if key > list[mid], set the low index to mid + 1.


                     public static int binarySearch(                     public static int binarySearch(
                         int[] list, int key) {                              int[] list, int key) {
                       int low = 0;                                        int low = 0;
                       int high = list.length - 1;                         int high = list.length - 1;

                                                                             while (high >= low) {
                          int mid = (low + high) / 2;                          int mid = (low + high) / 2;
                          if (key < list[mid])                                 if (key < list[mid])
                            high = mid - 1;                                      high = mid - 1;
                          else if (key == list[mid])                           else if (key == list[mid])
                            return mid;                                          return mid;
                          else                                                 else
                            low = mid + 1;                                       low = mid + 1;
                                                                             }

                                                                             return -1; // Not found
                     }                                                   }


                                   (a) Version 1                                       (b) Version 2
                    FIGURE 6.10   Binary search is implemented incrementally.


                       Next consider implementing the method to perform search repeatedly by adding a loop, as
                    shown in Figure 6.10(b). The search ends if the key is found, or if the key is not found when
                    low > high.
why not -1?            When the key is not found, low is the insertion point where a key would be inserted to
                    maintain the order of the list. It is more useful to return the insertion point than -1. The
                    method must return a negative value to indicate that the key is not in the list. Can it simply
                    return –low? No. If key is less than list[0], low would be 0. -0 is 0. This would indicate
                    that key matches list[0]. A good choice is to let the method return –low – 1 if the key is
                    not in the list. Returning –low – 1 indicates not only that the key is not in the list, but also
                    where the key would be inserted.
                       The complete program is given in Listing 6.7.

                    LISTING 6.7 BinarySearch.java
                     1 public class BinarySearch {
                     2   /** Use binary search to find the key in the list */
                     3   public static int binarySearch(int[] list, int key) {
                     4     int low = 0;
                     5     int high = list.length - 1;
                     6
                     7     while (high >= low) {
                     8       int mid = (low + high) / 2;
                     9       if (key < list[mid])
first half          10         high = mid - 1;
                    11       else if (key == list[mid])
                    12         return mid;
                    13       else
second half         14         low = mid + 1;
                    15     }
                    16
                    17     return –low - 1; // Now high < low, key not found
                    18   }
                    19 }
                                                                                                                6.10 Sorting Arrays 219
The binary search returns the index of the search key if it is contained in the list (line 12). Oth-
erwise, it returns –low – 1 (line 17).
   What would happens if we replaced (high >= low) in line 7 with (high > low)? The
search would miss a possible matching element. Consider a list with just one element. The
search would miss the element.
   Does the method still work if there are duplicate elements in the list? Yes, as long as the
elements are sorted in increasing order. The method returns the index of one of the matching
elements if the element is in the list.
   To better understand this method, trace it with the following statements and identify low
and high when the method returns.

   int[]   list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
   int i   = BinarySearch.binarySearch(list, 2); // Returns 0
   int j   = BinarySearch.binarySearch(list, 11); // Returns 4
   int k   = BinarySearch.binarySearch(list, 12); // Returns –6
   int l   = BinarySearch.binarySearch(list, 1); // Returns –1
   int m   = BinarySearch.binarySearch(list, 3); // Returns –2

Here is the table that lists the low and high values when the method exits and the value
returned from invoking the method.


                              Method               Low      High       Value Returned
                    binarySearch(list, 2)              0         1               0
                    binarySearch(list, 11)             3         5               4
                    binarySearch(list, 12)             5         4             -6
                    binarySearch(list, 1)              0       -1              -1
                    binarySearch(list, 3)              1         0             -2



      Note
      Linear search is useful for finding an element in a small array or an unsorted array, but it is ineffi-
      cient for large arrays. Binary search is more efficient, but it requires that the array be presorted.         binary search benefits


6.10 Sorting Arrays
Sorting, like searching, is a common task in computer programming. Many different algo-
rithms have been developed for sorting. This section introduces two simple, intuitive sorting
algorithms: selection sort and insertion sort.

6.10.1 Selection Sort
Suppose that you want to sort a list in ascending order. Selection sort finds the smallest num-
ber in the list and places it first. It then finds the smallest number remaining and places it next
                                                                                                                    Video Note
to first, and so on, until only a single number remains. Figure 6.11 shows how to sort a list                       Selection sort
52, 9, 5, 4, 8, 1, 66 using selection sort.
   You know how the selection-sort approach works. The task now is to implement it in Java.
Beginners find it difficult to develop a complete solution on the first attempt. Start by writing
the code for the first iteration to find the largest element in the list and swap it with the last
element, and then observe what would be different for the second iteration, the third, and so
on. The insight this gives will enable you to write a loop that generalizes all the iterations.
220 Chapter 6 Single-Dimensional Arrays
                       The solution can be described as follows:
                       for (int i = 0; i < list.length - 1; i++) {
                         select the smallest element in list[i..list.length-1];
                         swap the smallest with list[i], if necessary;
                           // list[i] is in its correct position.
                           // The next iteration apply on list[i+1..list.length-1]
                       }

                    Listing 6.8 implements the solution.

                    LISTING 6.8 SelectionSort.java
                     1 public class SelectionSort {
                     2   /** The method for sorting the numbers */
                     3   public static void selectionSort(double[] list) {
                     4     for (int i = 0; i < list.length - 1; i++) {
                     5       // Find the minimum in the list[i..list.length-1]
                     6       double currentMin = list[i];
                     7       int currentMinIndex = i;
                     8
select               9       for (int j = i + 1; j < list.length; j++) {
                    10         if (currentMin > list[j]) {
                    11           currentMin = list[j];
                    12           currentMinIndex = j;
                    13         }
                    14       }
                    15
                    16       // Swap list[i] with list[currentMinIndex] if necessary;
swap                17       if (currentMinIndex != i) {
                    18         list[currentMinIndex] = list[i];
                    19         list[i] = currentMin;
                    20       }
                    21     }
                    22   }
                    23 }

                    The selectionSort(double[] list) method sorts any array of double elements. The
                    method is implemented with a nested for loop. The outer loop (with the loop control variable
                    i) (line 4) is iterated in order to find the smallest element in the list, which ranges from
                    list[i] to list[list.length-1], and exchange it with list[i].
                       The variable i is initially 0. After each iteration of the outer loop, list[i] is in the right
                    place. Eventually, all the elements are put in the right place; therefore, the whole list is sorted.
                       To understand this method better, trace it with the following statements:
                       double[] list = {1, 9, 4.5, 6.6, 5.7, -4.5};
                       SelectionSort.selectionSort(list);


                    6.10.2      Insertion Sort
                    Suppose that you want to sort a list in ascending order. The insertion-sort algorithm sorts a list
                    of values by repeatedly inserting a new element into a sorted sublist until the whole list is
                    sorted. Figure 6.12 shows how to sort the list 52, 9, 5, 4, 8, 1, 66 using insertion sort.
                       The algorithm can be described as follows:
                       for (int i = 1; i < list.length; i++) {
                         insert list[i] into a sorted sublist list[0..i-1] so that
                         list[0..i] is sorted.
                       }
                                                                                                                   6.10 Sorting Arrays 221

                                                                        swap

              Step 1: (the smallest) and swap it        2       9   5      4      8    1     6
              with 2 (the first) in the list
                                                                               swap
              The number 1 is now in the                                                             Select 2 (the smallest) and swap it
              correct position and thus no              1       9   5      4      8    2     6       with 9 (the first) in the remaining
              longer needs to be considered.                                                         list
                                                                        swap
              The number 2 is now in the                                                             Select 4 (the smallest) and swap it
              correct position and thus no              1       2   5      4      8    9     6       with 5 (the first) in the remaining
              longer needs to be considered.                                                         list


              The number 4 is now in the
                                                                                                     5 is the smallest and in the right
              correct position and thus no              1       2   4      5      8    9     6
                                                                                                     position. No swap is necessary
              longer needs to be considered.
                                                                                      swap
              The number 5 is now in the                                                             Select 6 (the smallest) and swap it
              correct position and thus no              1       2   4      5      8    9     6       with 8 (the first) in the remaining
              longer needs to be considered.                                                         list
                                                                                          swap
              The number 6 is now in the                                                             Select 8 (the smallest) and swap it
              correct position and thus no              1       2   4      5      6    9     8       with 9 (the first) in the remaining
              longer needs to be considered.                                                         list


              The number 8 is now in the                                                             Since there is only one element
              correct position and thus no              1       2   4      5      6    8     9       remaining in the list, sort is
              longer needs to be considered.                                                         completed

FIGURE 6.11    Selection sort repeatedly selects the smallest number and swaps it with the first number in the list.




         Step 1: Initially, the sorted sublist contains the         2     9      5    4      8   1      6
         first element in the list. Insert 9 to the sublist.


         Step 2: The sorted sublist is {2, 9}. Insert 5 to          2     9      5    4      8   1      6
         the sublist.


         Step 3: The sorted sublist is {2, 5, 9}. Insert 4 to       2     5      9    4      8   1      6
         the sublist.


         Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8       2     4      5    9      8   1      6
         to the sublist.


         Step 5: The sorted sublist is {2, 4, 5, 8, 9}. Insert      2     4      5    8      9   1      6
         1 to the sublist.


         Step 6: The sorted sublist is {1, 2, 4, 5, 8, 9}.          1     2      4    5      8   9      6
         Insert 6 to the sublist.


         Step 7: The entire list is now sorted                      1     2      4    5      6   8      9

FIGURE 6.12    Insertion sort repeatedly inserts a new element into a sorted sublist.
222 Chapter 6 Single-Dimensional Arrays
                    To insert list[i] into list[0..i-1], save list[i] into a temporary variable, say
                    currentElement. Move list[i-1] to list[i] if list[i-1] > currentElement,
                    move list[i-2] to list[i-1] if list[i-2] > currentElement, and so on, until
                    list[i-k] <= currentElement or k > i (we pass the first element of the sorted list).
                    Assign currentElement to list[i-k+1]. For example, to insert 4 into 52, 5, 96 in Step 3
                    in Figure 6.13, move list[2] (9) to list[3] since 9 > 4, move list[1] (5) to list[2]
                    since 5 > 4. Finally, move currentElement (4) to list[1].
                       The algorithm can be expanded and implemented as in Listing 6.9.

                    LISTING 6.9 InsertionSort.java
                     1 public class InsertionSort {
                     2   /** The method for sorting the numbers */
                     3   public static void insertionSort(double[] list) {
                     4     for (int i = 1; i < list.length; i++) {
                     5       /** insert list[i] into a sorted sublist list[0..i-1] so that
                     6            list[0..i] is sorted. */
                     7       double currentElement = list[i];
                     8       int k;
shift                9       for (k = i - 1; k >= 0 && list[k] > currentElement; k--) {
                    10         list[k + 1] = list[k];
                    11       }
                    12
                    13       // Insert the current element into list[k + 1]
insert              14       list[k + 1] = currentElement;
                    15     }
                    16   }
                    17 }



                               [0][1][2][3][4][5][6]
                       list       2     5   9   4               Step 1: Save 4 to a temporary variable currentElement

                               [0][1][2][3][4][5][6]
                       list       2     5       9               Step 2: Move list[2] to list[3]

                               [0][1][2][3][4][5][6]
                       list       2         5   9               Step 3: Move list[1] to list[2]

                               [0][1][2][3][4][5][6]
                       list       2     4   5   9               Step 4: Assign currentElement to list[1]

                    FIGURE 6.13       A new element is inserted into a sorted sublist.


                    The insertionSort(double[] list) method sorts any array of double elements. The
                    method is implemented with a nested for loop. The outer loop (with the loop control variable
                    i) (line 4) is iterated in order to obtain a sorted sublist, which ranges from list[0] to
                    list[i]. The inner loop (with the loop control variable k) inserts list[i] into the sublist
                    from list[0] to list[i-1].
                       To better understand this method, trace it with the following statements:

                      double[] list = {1, 9, 4.5, 6.6, 5.7, -4.5};
                      InsertionSort.insertionSort(list);
                                                                                       6.11 The Arrays Class 223

6.11 The Arrays Class
The java.util.Arrays class contains various static methods for sorting and searching
arrays, comparing arrays, and filling array elements. These methods are overloaded for all
primitive types.
   You can use the sort method to sort a whole array or a partial array. For example, the fol-     sort
lowing code sorts an array of numbers and an array of characters.

   double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};
   java.util.Arrays.sort(numbers); // Sort the whole array

   char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};
   java.util.Arrays.sort(chars, 1, 3); // Sort part of the array

Invoking sort(numbers) sorts the whole array numbers. Invoking sort(chars, 1, 3)
sorts a partial array from chars[1] to chars[3-1].
   You can use the binarySearch method to search for a key in an array. The array must be          binarySearch
presorted in increasing order. If the key is not in the array, the method returns –(insertion
index + 1). For example, the following code searches the keys in an array of integers and an
array of characters.
   int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
   System.out.println("(1) Index is " +
     java.util.Arrays.binarySearch(list, 11));
   System.out.println("(2) Index is " +
     java.util.Arrays.binarySearch(list, 12));

   char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'};
   System.out.println("(3) Index is " +
     java.util.Arrays.binarySearch(chars, 'a'));
   System.out.println("(4) Index is " +
     java.util.Arrays.binarySearch(chars, 't'));

The output of the preceding code is
   (1) Index is 4
   (2) Index is -6
   (3) Index is 0
   (4) Index is -4
You can use the equals method to check whether two arrays are equal. Two arrays are equal          equals
if they have the same contents. In the following code, list1 and list2 are equal, but list2
and list3 are not.

   int[] list1 = {2, 4, 7, 10};
   int[] list2 = {2, 4, 7, 10};
   int[] list3 = {4, 2, 7, 10};
   System.out.println(java.util.Arrays.equals(list1, list2)); // true
   System.out.println(java.util.Arrays.equals(list2, list3)); // false

You can use the fill method to fill in all or part of the array. For example, the following code   fill
fills list1 with 5 and fills 8 into elements list2[1] and list2[3-1].

   int[] list1 = {2, 4, 7, 10};
   int[] list2 = {2, 4, 7, 10};
   java.util.Arrays.fill(list1, 5) ; // Fill 5 to the whole array
   java.util.Arrays.fill(list2, 1, 3, 8); // Fill 8 to a partial array
224 Chapter 6 Single-Dimensional Arrays

                      KEY TERMS
                      anonymous array 209                                  index 198
                      array 198                                            indexed variable 200
                      array initializer 201                                insertion sort 219
                      binary search 216                                    linear search 216
                      garbage collection 208                               selection sort 219


                      CHAPTER SUMMARY
                      1. A variable is declared as an array type using the syntax elementType[] arrayRef-
                            Var or elementType arrayRefVar[]. The style elementType[] arrayRefVar
                            is preferred, although elementType arrayRefVar[] is legal.

                      2. Unlike declarations for primitive data type variables, the declaration of an array vari-
                            able does not allocate any space in memory for the array. An array variable is not a
                            primitive data type variable. An array variable contains a reference to an array.

                      3. You cannot assign elements to an array unless it has already been created. You can
                            create an array by using the new operator with the following syntax: new element-
                            Type[arraySize].

                      4. Each element in the array is represented using the syntax arrayRefVar[index]. An
                            index must be an integer or an integer expression.

                      5. After an array is created, its size becomes permanent and can be obtained using
                            arrayRefVar.length. Since the index of an array always begins with 0, the last
                            index is always arrayRefVar.length - 1. An out-of-bounds error will occur if you
                            attempt to reference elements beyond the bounds of an array.

                      6. Programmers often mistakenly reference the first element in an array with index 1, but
                            it should be 0. This is called the index off-by-one error.

                      7. When an array is created, its elements are assigned the default value of     0 for the
                            numeric primitive data types, '\u0000' for char types, and false for boolean types.

                      8. Java has a shorthand notation, known as the array initializer, which combines in one
                            statement declaring an array, creating an array, and initializing, using the syntax:
                            elementType[] arrayRefVar = {value0, value1, ..., valuek}.

                      9. When you pass an array argument to a method, you are actually passing the reference of
                            the array; that is, the called method can modify the elements in the caller’s original array.

                      REVIEW QUESTIONS
                      Section 6.2
                      6.1       How do you declare and create an array?
                      6.2       How do you access elements of an array?
                                                                                        Review Questions 225

6.3    Is memory allocated for an array when it is declared? When is the memory allo-
       cated for an array? What is the printout of the following code?

       int x = 30;
       int[] numbers = new int[x];
       x = 60;
       System.out.println("x is " + x);
       System.out.println("The size of numbers is " + numbers.length);

6.4    Indicate true or false for the following statements:
       ■   Every element in an array has the same type.
       ■   The array size is fixed after it is declared.
       ■   The array size is fixed after it is created.
       ■   The elements in an array must be of primitive data type.
6.5    Which of the following statements are valid array declarations?

       int i = new int(30);
       double d[] = new double[30];
       char[] r = new char(1..30);
       int i[] = (3, 4, 3, 2);
       float f[] = {2.3, 4.5, 6.6};
       char[] c = new char();

6.6    What is the array index type? What is the lowest index? What is the representation
       of the third element in an array named a?
6.7    Write statements to do the following:
       a. Create an array to hold 10 double values.
       b. Assign value 5.5 to the last element in the array.
       c. Display the sum of the first two elements.
       d. Write a loop that computes the sum of all elements in the array.
       e. Write a loop that finds the minimum element in the array.
       f. Randomly generate an index and display the element of this index in the array.
       g. Use an array initializer to create another array with initial values 3.5, 5.5,
          4.52, and 5.6.
6.8    What happens when your program attempts to access an array element with an
       invalid index?
6.9    Identify and fix the errors in the following code:

       1 public class Test {
       2   public static void main(String[] args) {
       3     double[100] r;
       4
       5     for (int i = 0; i < r.length(); i++);
       6       r(i) = Math.random * 100;
       7   }
       8 }

Section 6.3
6.10 Use the arraycopy() method to copy the following array to a target array t:
       int[] source = {3, 4, 5};
226 Chapter 6 Single-Dimensional Arrays

                               6.11 Once an array is created, its size cannot be changed. Does the following code
                                      resize the array?

                                      int[] myList;
                                      myList = new int[10];
                                      // Some time later you want to assign a new array to myList
                                      myList = new int[20];

                               Sections 6.4–6.7
                               6.12 When an array is passed to a method, a new array is created and passed to the
                                      method. Is this true?
                               6.13   Show the output of the following two programs:


 public class Test {                                         public class Test {
   public static void main(String[] args) {                    public static void main(String[] args) {
     int number = 0;                                             int[] list = {1, 2, 3, 4, 5};
     int[] numbers = new int[1];                                     reverse(list);
                                                                     for (int i = 0; i < list.length; i++)
         m(number, numbers);                                           System.out.print(list[i] + " ");
                                                                 }
         System.out.println("number is " + number
           + " and numbers[0] is " + numbers[0]);                public static void reverse(int[] list) {
     }                                                             int[] newList = new int[list.length];

     public static void m(int x, int[] y) {                          for (int i = 0; i < list.length; i++)
       x = 3;                                                          newList[i] = list[list.length - 1 - i];
       y[0] = 3;
     }                                                               list = newList;
 }                                                               }
                                                             }

                          a                                                              b


                               6.14 Where are the arrays stored during execution? Show the contents of the stack and
                                      heap during and after executing createArray, displayArray, countLetters,
                                      displayCounts in Listing 6.4.

                               Section 6.8
                               6.15 What is wrong in the following method declaration?
                                      public static void print(String... strings, double... numbers)
                                      public static void print(double... numbers, String name)
                                      public static double... print(double d1, double d2)

                               6.16 Can you invoke the printMax method in Listing 6.5 using the following state-
                                      ments?
                                      printMax(1, 2, 2, 1, 4);
                                      printMax(new double[]{1, 2, 3});
                                      printMax(new int[]{1, 2, 3});

                               Sections 6.9–6.10
                               6.17 Use Figure 6.9 as an example to show how to apply the binary search approach to
                                      a search for key 10 and key 12 in list 52, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70,
                                      796.
                                                                                     Programming Exercises 227

6.18 Use Figure 6.11 as an example to show how to apply the selection-sort approach to
        sort 53.4, 5, 3, 3.5, 2.2, 1.9, 26.
6.19    Use Figure 6.12 as an example to show how to apply the insertion-sort approach to
        sort 53.4, 5, 3, 3.5, 2.2, 1.9, 26.
6.20    How do you modify the selectionSort method in Listing 6.8 to sort numbers in
        decreasing order?
6.21    How do you modify the insertionSort method in Listing 6.9 to sort numbers in
        decreasing order?

Section 6.11
6.22 What types of array can be sorted using the java.util.Arrays.sort method?
        Does this sort method create a new array?
6.23 To apply java.util.Arrays.binarySearch(array,                    key), should the array
        be sorted in increasing order, in decreasing order, or neither?
6.24    Show the contents of the array after the execution of each line.

        int[] list = {2, 4, 7, 10};
        java.util.Arrays.fill(list, 7);
        java.util.Arrays.fill(list, 1, 3, 8);
        System.out.print(java.util.Arrays.equals(list, list));



PROGRAMMING EXERCISES
Section 6.2
6.1* (Assigning grades) Write a program that reads student scores, gets the best score,
        and then assigns grades based on the following scheme:

                         Grade is A if score is 7 = best    -   10;
                         Grade is B if score is 7 = best    -   20;
                         Grade is C if score is 7 = best    -   30;
                         Grade is D if score is 7 = best    -   40;
                         Grade is F otherwise.
        The program prompts the user to enter the total number of students, then prompts
        the user to enter all of the scores, and concludes by displaying the grades. Here is
        a sample run:


         Enter the number of students: 4
         Enter 4 scores: 40 55 70 58
         Student 0 score is 40 and grade           is   C
         Student 1 score is 55 and grade           is   B
         Student 2 score is 70 and grade           is   A
         Student 3 score is 58 and grade           is   B



6.2     (Reversing the numbers entered) Write a program that reads ten integers and dis-
        plays them in the reverse of the order in which they were read.
6.3**   (Counting occurrence of numbers) Write a program that reads the integers
        between 1 and 100 and counts the occurrences of each. Assume the input ends
        with 0. Here is a sample run of the program:
228 Chapter 6 Single-Dimensional Arrays

                               Enter the integers between 1 and 100: 2 5 6 5 4 3 23
                                 43 2 0
                               2 occurs 2 times
                               3 occurs 1 time
                               4 occurs 1 time
                               5 occurs 2 times
                               6 occurs 1 time
                               23 occurs 1 time
                               43 occurs 1 time



                              Note that if a number occurs more than one time, the plural word “times” is used
                              in the output.
                      6.4     (Analyzing scores) Write a program that reads an unspecified number of scores
                              and determines how many scores are above or equal to the average and how many
                              scores are below the average. Enter a negative number to signify the end of the
                              input. Assume that the maximum number of scores is 10.
                      6.5**   (Printing distinct numbers) Write a program that reads in ten numbers and dis-
                              plays distinct numbers (i.e., if a number appears multiple times, it is displayed
                              only once). Hint: Read a number and store it to an array if it is new. If the number
                              is already in the array, ignore it. After the input, the array contains the distinct
                              numbers. Here is the sample run of the program:


                               Enter ten numbers: 1 2 3 2 1 6 3 4 5 2
                               The distinct numbers are: 1 2 3 6 4 5



                      6.6* (Revising Listing 4.14, PrimeNumber.java) Listing 4.14 determines whether a
                              number n is prime by checking whether 2, 3, 4, 5, 6, Á , n/2 is a divisor. If a
                              divisor is found, n is not prime. A more efficient approach is to check whether any
                              of the prime numbers less than or equal to 1n can divide n evenly. If not, n is
                              prime. Rewrite Listing 4.11 to display the first 50 prime numbers using this
                              approach. You need to use an array to store the prime numbers and later use them
                              to check whether they are possible divisors for n.
                      6.7*    (Counting single digits) Write a program that generates 100 random integers between
                              0 and 9 and displays the count for each number. (Hint: Use (int)(Math.random()
                              * 10) to generate a random integer between 0 and 9. Use an array of ten integers, say
                              counts, to store the counts for the number of 0s, 1s, Á , 9s.)

                      Sections 6.4–6.7
                      6.8     (Averaging an array) Write two overloaded methods that return the average of an
                              array with the following headers:
                              public static int average(int[] array)
                              public static double average(double[] array)

                              Write a test program that prompts the user to enter ten double values, invokes this
                              method, and displays the average value.
                      6.9     (Finding the smallest element) Write a method that finds the smallest element in
                              an array of integers using the following header:
                              public static double min(double[] array)
                                                                                      Programming Exercises 229
        Write a test program that prompts the user to enter ten numbers, invokes this
        method to return the minimum value, and displays the minimum value. Here is a
        sample run of the program:


         Enter ten numbers: 1.9 2.5 3.7 2 1.5 6 3 4 5 2
         The minimum number is: 1.5



6.10 (Finding the index of the smallest element) Write a method that returns the index
        of the smallest element in an array of integers. If the number of such elements is
        greater than 1, return the smallest index. Use the following header:

        public static int indexOfSmallestElement(double[] array)

        Write a test program that prompts the user to enter ten numbers, invokes this
        method to return the index of the smallest element, and displays the index.
6.11*   (Statistics: computing deviation) Exercise 5.21 computes the standard deviation of
        numbers. This exercise uses a different but equivalent formula to compute the
        standard deviation of n numbers.
                  n                                                      n
                                                                        a 1xi - mean2
                                                                                     2
                  a xi     x1 + x2 + Á + xn
                 i=1                                                    i=1
        mean =           =                            deviation =
                   n                n                               Q         n - 1

        To compute deviation with this formula, you have to store the individual numbers
        using an array, so that they can be used after the mean is obtained.
           Your program should contain the following methods:

        /** Compute the deviation of double values*/
        public static double deviation(double[] x)

        /** Compute the mean of an array of double values*/
        public static double mean(double[] x)

        Write a test program that prompts the user to enter ten numbers and displays the
        mean and deviation, as shown in the following sample run:


         Enter ten numbers: 1.9 2.5 3.7 2 1 6 3 4 5 2
         The mean is 3.11
         The standard deviation is 1.55738


6.12* (Reversing an array) The reverse method in §6.7 reverses an array by copying it
        to a new array. Rewrite the method that reverses the array passed in the argument
        and returns this array. Write a test program that prompts the user to enter ten num-
        bers, invokes the method to reverse the numbers, and displays the numbers.

Section 6.8
6.13* (Random number chooser) Write a method that returns a random number between
        1 and 54, excluding the numbers passed in the argument. The method header is
        specified as follows:
        public static int getRandom(int... numbers)
230 Chapter 6 Single-Dimensional Arrays

                      6.14      (Computing gcd) Write a method that returns the gcd of an unspecified number
                                of integers. The method header is specified as follows:
                                public static int gcd(int... numbers)

                                Write a test program that prompts the user to enter five numbers, invokes the
                                method to find the gcd of these numbers, and displays the gcd.
                      Sections 6.9–6.10
                      6.15      (Eliminating duplicates) Write a method to eliminate the duplicate values in the
                                array using following method header:

                                public static int[] eliminateDuplicates(int[] numbers)

                                Write a test program that reads in ten integers, invokes the method, and displays
                                the result. Here is the sample run of the program:


                                 Enter ten numbers: 1 2 3 2 1 6 3 4 5 2
                                 The distinct numbers are: 1 2 3 6 4 5


                      6.16      (Execution time) Write a program that randomly generates an array of 100000
                                integers and a key. Estimate the execution time of invoking the linearSearch
                                method in Listing 6.6. Sort the array and estimate the execution time of invoking
                                the binarySearch method in Listing 6.7. You can use the following code tem-
                                plate to obtain the execution time:

                                long startTime = System.currentTimeMillis();
                                perform the task;
                                long endTime = System.currentTimeMillis();
                                long executionTime = endTime - startTime;

                      6.17*   (Revising selection sort) In §6.10.1, you used selection sort to sort an array.
                              The selection-sort method repeatedly finds the smallest number in the cur-
                              rent array and swaps it with the first number in the array. Rewrite this pro-
                              gram by finding the largest number and swapping it with the last number in
                              the array. Write a test program that reads in ten double numbers, invokes the
                              method, and displays the sorted numbers.
                      6.18** (Bubble sort) Write a sort method that uses the bubble-sort algorithm. The bub-
                              ble-sort algorithm makes several passes through the array. On each pass, succes-
                              sive neighboring pairs are compared. If a pair is in decreasing order, its values
                              are swapped; otherwise, the values remain unchanged. The technique is called a
                              bubble sort or sinking sort because the smaller values gradually “bubble” their
                              way to the top and the larger values “sink” to the bottom. Use 56.0, 4.4, 1.9,
                              2.9, 3.4, 2.9, 3.56 to test the method. Write a test program that reads in ten
                              double numbers, invokes the method, and displays the sorted numbers.
                      6.19** (Sorting students) Write a program that prompts the user to enter the number of
                              students, the students’ names, and their scores, and prints student names in
                              decreasing order of their scores.
                      6.20*** (Game: Eight Queens) The classic Eight Queens puzzle is to place eight queens
                              on a chessboard such that no two queens can attack each other (i.e., no two
                              queens are on the same row, same column, or same diagonal). There are many
                              possible solutions. Write a program that displays one such solution. A sample
                                                                                            Programming Exercises 231
              output is shown below:

              |Q| | | | | | | |
              | | | | |Q| | | |
              | | | | | | | |Q|
              | | | | | |Q| | |
              | | |Q| | | | | |
              | | | | | | |Q| |
              | |Q| | | | | | |
              | | | |Q| | | | |

  6.21*** (Game: bean machine) The bean machine, also known as a quincunx or the Gal-
              ton box, is a device for statistic experiments named after English scientist Sir
              Francis Galton. It consists of an upright board with evenly spaced nails (or pegs)
              in a triangular form, as shown in Figure 6.14.




                     (a)                       (b)                        (c)

FIGURE 6.14   Each ball takes a random path and falls into a slot.

              Balls are dropped from the opening of the board. Every time a ball hits a nail, it
              has a 50% chance of falling to the left or to the right. The piles of balls are accu-
              mulated in the slots at the bottom of the board.
                 Write a program that simulates the bean machine. Your program should
              prompt the user to enter the number of the balls and the number of the slots in
              the machine. Simulate the falling of each ball by printing its path. For example,
              the path for the ball in Figure 6.14(b) is LLRRLLR and the path for the ball in
              Figure 6.14(c) is RLRRLRR. Display the final buildup of the balls in the slots in
              a histogram. Here is a sample run of the program:


               Enter the number of balls to drop: 5
               Enter the number of slots in the bean machine: 7
               LRLRLRR
               RRLLLRR
               LLRLLRR
               RRLLLLL
               LRLRRLR
                 O
                 O
               OOO


              (Hint: Create an array named slots. Each element in slots stores the number
              of balls in a slot. Each ball falls into a slot via a path. The number of R’s in a
              path is the position of the slot where the ball falls. For example, for the path
232 Chapter 6 Single-Dimensional Arrays
                                  LRLRLRR, the ball falls into slots[4], and for the path is RRLLLLL, the ball
                                  falls into slots[2].)
                          6.22*** (Game: multiple Eight Queens solutions) Exercise 6.20 finds one solution for
                                  the Eight Queens problem. Write a program to count all possible solutions for
                                  the eight queens problem and display all solutions.
                          6.23** (Game: locker puzzle) A school has 100 lockers and 100 students. All lockers
                                  are closed on the first day of school. As the students enter, the first student,
                                  denoted S1, opens every locker. Then the second student, S2, begins with the
                                  second locker, denoted L2, and closes every other locker. Student S3 begins
                                  with the third locker and changes every third locker (closes it if it was open, and
                                  opens it if it was closed). Student S4 begins with locker L4 and changes every
                                  fourth locker. Student S5 starts with L5 and changes every fifth locker, and so
                                  on, until student S100 changes L100.
                                      After all the students have passed through the building and changed the lock-
                                  ers, which lockers are open? Write a program to find your answer.
                                      (Hint: Use an array of 100 boolean elements, each of which indicates whether
                                  a locker is open (true) or closed (false). Initially, all lockers are closed.)
                          6.24** (Simulation: coupon collector’s problem) Coupon collector is a classic statistic
                                  problem with many practical applications. The problem is to pick objects from a
                                  set of objects repeatedly and find out how many picks are needed for all the
     Video Note                   objects to be picked at least once. A variation of the problem is to pick cards from
     Coupon collector’s           a shuffled deck of 52 cards repeatedly and find out how many picks are needed
     problem
                                  before you see one of each suit. Assume a picked card is placed back in the deck
                                  before picking another. Write a program to simulate the number of picks needed
                                  to get four cards from each suit and display the four cards picked (it is possible a
                                  card may be picked twice). Here is a sample run of the program:

                                    Queen of Spades
                                    5 of Clubs
                                    Queen of Hearts
                                    4 of Diamonds
                                    Number of picks: 12


                          6.25 (Algebra: solving quadratic equations) Write a method for solving a quadratic
                                  equation using the following header:

                                  public static int solveQuadratic(double[] eqn, double[] roots)

                                  The coefficients of a quadratic equation ax2 + bx + c = 0 are passed to the array
                                  eqn and the noncomplex roots are stored in roots. The method returns the number
                                  of roots. See Programming Exercise 3.1 on how to solve a quadratic equation.
                                     Write a program that prompts the user to enter values for a, b, and c and dis-
                                  plays the number of roots and all noncomplex roots.
                          6.26    (Strictly identical arrays) Two arrays list1 and list2 are strictly identical if
                                  they have the same length and list1[i] is equal to list2[i] for each i. Write
                                  a method that returns true if list1 and list2 are strictly identical, using the
                                  following header:

                                  public static boolean equal(int[] list1, int[] list2)

                                  Write a test program that prompts the user to enter two lists of integers and dis-
                                  plays whether the two are strictly identical. Here are the sample runs. Note that the
                                  first number in the input indicates the number of the elements in the list.
                                                                                     Programming Exercises 233

         Enter list1: 5 2 5 6 1 6
         Enter list2: 5 2 5 6 1 6
         Two lists are strictly identical



         Enter list1: 5 2 5 6 6 1
         Enter list2: 5 2 5 6 1 6
         Two lists are not strictly identical



6.27 (Identical arrays) Two arrays     list1 and list2 are identical if they have the
       same contents. Write a method that returns true if list1 and list2 are identi-
       cal, using the following header:

       public static boolean equal(int[] list1, int[] list2)

       Write a test program that prompts the user to enter two lists of integers and dis-
       plays whether the two are identical. Here are the sample runs. Note that the first
       number in the input indicates the number of the elements in the list.


         Enter list1: 5 2 5 6 6 1
         Enter list2: 5 5 2 6 1 6
         Two lists are identical



         Enter list1: 5 5 5 6 6 1
         Enter list2: 5 2 5 6 1 6
         Two lists are not identical



6.28 (Math: combinations) Write a program that prompts the user to enter 10 integers
       and displays all combinations of picking two numbers from the 10.
6.29   (Game: picking four cards) Write a program that picks four cards from a deck of
       52 cards and computes their sum. An Ace, King, Queen, and Jack represent 1, 13,
       12, and 11, respectively. Your program should display the number of picks that
       yields the sum of 24.
6.30   (Pattern recognition: consecutive four equal numbers) Write the following
       method that tests whether the array has four consecutive numbers with the same
       value.

       public static boolean isConsecutiveFour(int[] values)

       Write a test program that prompts the user to enter a series of integers and displays
       true if the series contains four consecutive numbers with the same value. Other-
       wise, display false. Your program should first prompt the user to enter the input
       size—i.e., the number of values in the series.
This page intentionally left blank
                                                        CHAPTER 7
MULTIDIMENSIONAL ARRAYS
Objectives
■   To give examples of representing data using two-dimensional arrays (§7.1).
■   To declare variables for two-dimensional arrays, create arrays, and access array elements
    in a two-dimensional array using row and column indexes (§7.2).
■   To program common operations for two-dimensional arrays
    (displaying arrays, summing all elements, finding min and
    max elements, and random shuffling) (§7.3).
■   To pass two-dimensional arrays to methods (§7.4).
■   To write a program for grading multiple-choice
    questions using two-dimensional arrays (§7.5).
■   To solve the closest-pair problem using
    two-dimensional arrays (§7.6).
■   To check a Sudoku solution using two-dimensional
    arrays (§7.7).
■   To use multidimensional arrays (§7.8).
236 Chapter 7 Multidimensional Arrays

                    7.1 Introduction
problem             The preceding chapter introduced how to use one-dimensional arrays to store linear collec-
                    tions of elements. You can use a two-dimensional array to store a matrix or a table. For exam-
                    ple, the following table that describes the distances between the cities can be stored using a
                    two-dimensional array.

                                                         Distance Table (in miles)
                                    Chicago     Boston     New York       Atlanta    Miami    Dallas    Houston
                    Chicago              0        983          787          714       1375      967       1087
                    Boston             983           0         214         1102       1763     1723       1842
                    New York           787        214             0         888       1549     1548       1627
                    Atlanta            714       1102          888              0      661      781         810
                    Miami             1375       1763         1549          661           0    1426       1187
                    Dallas             967       1723         1548          781       1426         0        239
                    Houston           1087       1842         1627          810       1187      239           0

                    7.2 Two-Dimensional Array Basics
                    How do you declare a variable for two-dimensional arrays? How do you create a two-
                    dimensional array? How do you access elements in a two-dimensional array? This section
                    addresses these issues.

                    7.2.1 Declaring Variables of Two-Dimensional Arrays and Creating
                          Two-Dimensional Arrays
                    Here is the syntax for declaring a two-dimensional array:
                         elementType[][] arrayRefVar;

                    or
                         elementType arrayRefVar[][]; // Allowed, but not preferred

                    As an example, here is how you would declare a two-dimensional array variable matrix of
                    int values:

                         int[][] matrix;

                    or
                         int matrix[][]; // This style is allowed, but not preferred

                    You can create a two-dimensional array of 5-by-5 int values and assign it to matrix using
                    this syntax:
                         matrix = new int[5][5];

                    Two subscripts are used in a two-dimensional array, one for the row and the other for the col-
                    umn. As in a one-dimensional array, the index for each subscript is of the int type and starts
                    from 0, as shown in Figure 7.1(a).
                       To assign the value 7 to a specific element at row 2 and column 1, as shown in Figure 7.1(b),
                    you can use the following:
                         matrix[2][1] = 7;
                                                                              7.2 Two-Dimensional Array Basics     237
           [0][1][2][3][4]                   [0][1][2][3][4]                   [0][1][2]

     [0]                               [0]                                [0] 1     2    3

     [1]                               [1]                                [1] 4     5    6

     [2]                               [2]       7                        [2] 7     8    9

     [3]                               [3]                                [3] 10 11 12

     [4]                               [4]                                 int[][] array = {
                                                                              {1, 2, 3},
   matrix = new int[5][5];               matrix[2][1] = 7;                    {4, 5, 6},
                                                                              {7, 8, 9},
                                                                              {10, 11, 12}
                                                                           };
                 (a)                                 (b)                           (c)

FIGURE 7.1 The index of each subscript of a two-dimensional array is an int value, starting
from 0.


      Caution
      It is a common mistake to use matrix[2, 1] to access the element at row 2 and column 1. In
      Java, each subscript must be enclosed in a pair of square brackets.

   You can also use an array initializer to declare, create, and initialize a two-dimensional
array. For example, the following code in (a) creates an array with the specified initial values,
as shown in Figure 7.1(c). This is equivalent to the code in (b).


int[][] array = {                                    int[][] array     = new int[4][3];
   {1, 2, 3},                  Equivalent            array[0][0] =     1; array[0][1] = 2; array[0][2] =   3;
   {4, 5, 6},                                        array[1][0] =     4; array[1][1] = 5; array[1][2] =   6;
   {7, 8, 9},                                        array[2][0] =     7; array[2][1] = 8; array[2][2] =   9;
   {10, 11, 12}                                      array[3][0] =     10; array[3][1] = 11; array[3][2]   = 12;
};

           (a)                                                                           (b)


7.2.2      Obtaining the Lengths of Two-Dimensional Arrays
A two-dimensional array is actually an array in which each element is a one-dimensional
array. The length of an array x is the number of elements in the array, which can be obtained
using x.length. x[0], x[1], Á , and x[x.length-1] are arrays. Their lengths can be
obtained using x[0].length, x[1].length, Á , and x[x.length-1].length.
   For example, suppose x = new int[3][4], x[0], x[1], and x[2] are one-dimensional
arrays and each contains four elements, as shown in Figure 7.2. x.length is 3, and
x[0].length, x[1].length, and x[2].length are 4.


     x
                                 x[0][0] x[0][1] x[0][2] x[0][3]              x[0].length is 4
         x[0]

         x[1]                    x[1][0] x[1][1] x[1][2] x[1][3]              x[1].length is 4

         x[2]
                                 x[2][0] x[2][1] x[2][2] x[2][3]              x[2].length is 4
     x.length is 3

FIGURE 7.2 A two-dimensional array is a one-dimensional array in which each element is
another one-dimensional array.
238 Chapter 7 Multidimensional Arrays

                    7.2.3     Ragged Arrays
                    Each row in a two-dimensional array is itself an array. Thus the rows can have different lengths.
                    An array of this kind is known as a ragged array. Here is an example of creating a ragged array:
                                    int[][] triangleArray = {                                    1 2 3 4 5
                                      {1, 2, 3, 4, 5},
                                      {2, 3, 4, 5},
                                                                                                 2 3 4 5
                                      {3, 4, 5},
                                      {4, 5},
                                      {5}                                                        3 4 5
                                    };
                                                                                                 4 5

                                                                                                 5

                    As can be seen, triangleArray[0].length is 5, triangleArray[1].length is
                    4, triangleArray[2].length is 3, triangleArray[3].length is 2, and
                    triangleArray[4].length is 1.
                       If you don’t know the values in a ragged array in advance, but know the sizes, say the same
                    as before, you can create a ragged array using the syntax that follows:
                       int[][] triangleArray = new int[5][] ;
                       triangleArray[0] = new int[5];
                       triangleArray[1] = new int[4];
                       triangleArray[2] = new int[3];
                       triangleArray[3] = new int[2];
                       triangleArray[4] = new int[1];

                    You can now assign values to the array. For example,
                       triangleArray[0][3] = 50;
                       triangleArray[4][0] = 45;

                          Note
                          The syntax new int[5][] for creating an array requires the first index to be specified. The syn-
                          tax new int[][] would be wrong.


                    7.3 Processing Two-Dimensional Arrays
                    Suppose an array matrix is created as follows:
                       int[][] matrix = new int[10][10];

                    Here are some examples of processing two-dimensional arrays:
                       1. (Initializing arrays with input values) The following loop initializes the array with user
                          input values:
                             java.util.Scanner input = new Scanner(System.in);
                             System.out.println("Enter " + matrix.length + " rows and " +
                               matrix[0].length + " columns: ");
                             for (int row = 0; row < matrix.length ; row++) {
                               for (int column = 0; column < matrix[row].length ; column++) {
                                 matrix[row][column] = input.nextInt();
                               }
                             }

                       2. (Initializing arrays with random values) The following loop initializes the array with
                          random values between 0 and 99:
                             for (int row = 0; row < matrix.length ; row++) {
                               for (int column = 0; column < matrix[row].length ; column++) {
                                                            7.3 Processing Two-Dimensional Arrays                  239
             matrix[row][column] = (int)(Math.random() * 100);
         }
     }

3. (Printing arrays) To print a two-dimensional array, you have to print each element in
   the array using a loop like the following:

     for (int row = 0; row < matrix.length ; row++) {
       for (int column = 0; column < matrix[row].length ; column++) {
         System.out.print(matrix[row][column] + " ");
       }

         System.out.println();
     }

4. (Summing all elements) Use a variable named total to store the sum. Initially total
   is 0. Add each element in the array to total using a loop like this:

     int total = 0;
     for (int row = 0; row < matrix.length; row++) {
       for (int column = 0; column < matrix[row].length; column++) {
         total += matrix[row][column];
       }
     }

5. (Summing elements by column) For each column, use a variable named total to store
   its sum. Add each element in the column to total using a loop like this:

     for (int column = 0; column < matrix[0].length; column++) {
       int total = 0;
       for (int row = 0; row < matrix.length; row++)
         total += matrix[row][column];
       System.out.println("Sum for column " + column + " is " +
         total);
     }

6. (Which row has the largest sum?) Use variables maxRow and indexOfMaxRow to track
   the largest sum and index of the row. For each row, compute its sum and update maxRow
   and indexOfMaxRow if the new sum is greater.
                                                                                           Video Note
     int maxRow = 0;                                                                       find the row with the
     int indexOfMaxRow = 0;                                                                largest sum

     // Get sum of the first row in maxRow
     for (int column = 0; column < matrix[0].length; column++) {
       maxRow += matrix[0][column];
     }

     for (int row = 1; row < matrix.length; row++) {
       int totalOfThisRow = 0;
       for (int column = 0; column < matrix[row].length; column++)
         totalOfThisRow += matrix[row][column];

         if (totalOfThisRow > maxRow) {
           maxRow = totalOfThisRow;
           indexOfMaxRow = row;
         }
     }

     System.out.println("Row " + indexOfMaxRow
       + " has the maximum sum of " + maxRow);
240 Chapter 7 Multidimensional Arrays
                      7. (Random shuffling) Shuffling the elements in a one-dimensional array was introduced in
                         §6.2.6. How do you shuffle all the elements in a two-dimensional array? To accomplish
                         this, for each element matrix[i][j], randomly generate indices i1 and j1 and swap
                         matrix[i][j] with matrix[i1][j1], as follows:

                            for (int i    =   0; i < matrix.length; i++) {
                              for (int    j   = 0; j < matrix[i].length; j++) {
                                int i1    =   (int)(Math.random() * matrix.length);
                                int j1    =   (int)(Math.random() * matrix[i].length);

                                    // Swap matrix[i][j] with matrix[i1][j1]
                                    int temp = matrix[i][j];
                                    matrix[i][j] = matrix[i1][j1];
                                    matrix[i1][j1] = temp;
                                }
                            }


                    7.4 Passing Two-Dimensional Arrays to Methods
                    You can pass a two-dimensional array to a method just as you pass a one-dimensional array.
                    Listing 7.1 gives an example with a method that returns the sum of all the elements in a
                    matrix.


                    LISTING 7.1 PassTwoDimensionalArray.java
                     1 import java.util.Scanner;
                     2
                     3 public class PassTwoDimensionalArray {
                     4   public static void main(String[] args) {
                     5     // Create a Scanner
                     6     Scanner input = new Scanner(System.in);
                     7
                     8     // Enter array values
                     9     int[][] m = new int[3][4];
                    10     System.out.println("Enter " + m.length + " rows and "
                    11       + m[0].length + " columns: ");
                    12     for (int i = 0; i < m.length; i++)
                    13       for (int j = 0; j < m[i].length; j++)
                    14         m[i][j] = input.nextInt();
                    15
                    16     // Display result
pass array          17     System.out.println("\nSum of all elements is " + sum(m) );
                    18   }
                    19
                    20   public static int sum(int[][] m) {
                    21     int total = 0;
                    22     for (int row = 0; row < m.length; row++) {
                    23       for (int column = 0; column < m[row].length; column++) {
                    24         total += m[row][column];
                    25       }
                    26     }
                    27
                    28     return total;
                    29   }
                    30 }
                                                                         7.5 Problem: Grading a Multiple-Choice Test 241

    Enter 3 rows and 4 columns:
    1 2 3 4
    5 6 7 8
    9 10 11 12
    Sum of all elements is 78


The method sum (line 20) has a two-dimensional array argument. You can obtain the number
of rows using m.length (line 22) and the number of columns in a specified row using
m[row].column (line 23).


7.5 Problem: Grading a Multiple-Choice Test
The problem is to write a program that grades multiple-choice tests. Suppose there are eight
students and ten questions, and the answers are stored in a two-dimensional array. Each row
                                                                                                    Video Note
records a student’s answers to the questions, as shown in the following array.
                                                                                                    Grade multiple-choice test

                                     Students’ Answers to the Questions:
                                     0 1 2 3 4 5 6 7 8 9
                   Student   0       A   B   A   C   C   D   E   E   A   D
                   Student   1       D   B   A   B   C   A   E   E   A   D
                   Student   2       E   D   D   A   C   B   E   E   A   D
                   Student   3       C   B   A   E   D   C   E   E   A   D
                   Student   4       A   B   D   C   C   D   E   E   A   D
                   Student   5       B   B   E   C   C   D   E   E   A   D
                   Student   6       B   B   A   C   C   D   E   E   A   D
                   Student   7       E   B   E   C   C   D   E   E   A   D


The key is stored in a one-dimensional array:

                          Key to the Questions:
                          0 1 2 3 4 5 6 7 8 9
                Key       D B D C C D A E A D



Your program grades the test and displays the result. It compares each student’s answers with
the key, counts the number of correct answers, and displays it. Listing 7.2 gives the program.

LISTING 7.2 GradeExam.java
 1 public class GradeExam {
 2   /** Main method */
 3   public static void main(String[] args) {
 4     // Students’ answers to the questions
 5     char[][] answers = {                                                                         2-D array
 6       {'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
 7       {'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'},
 8       {'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'},
 9       {'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'},
10       {'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
11       {'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
12       {'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
13       {'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}};
242 Chapter 7 Multidimensional Arrays
                    14
                    15       // Key to the questions
1-D array           16       char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};
                    17
                    18       // Grade all answers
                    19       for (int i = 0; i < answers.length ; i++) {
                    20         // Grade one student
                    21         int correctCount = 0;
                    22         for (int j = 0; j < answers[i].length ; j++) {
compare with key    23           if (answers[i][j] == keys[j] )
                    24             correctCount++;
                    25         }
                    26
                    27           System.out.println("Student " + i + "’s correct count is " +
                    28             correctCount);
                    29       }
                    30   }
                    31 }


                        Student    0's   correct   count   is   7
                        Student    1's   correct   count   is   6
                        Student    2's   correct   count   is   5
                        Student    3's   correct   count   is   4
                        Student    4's   correct   count   is   8
                        Student    5's   correct   count   is   7
                        Student    6's   correct   count   is   7
                        Student    7's   correct   count   is   7


                    The statement in lines 5–13 declares, creates, and initializes a two-dimensional array of char-
                    acters and assigns the reference to answers of the char[][] type.
                       The statement in line 16 declares, creates, and initializes an array of char values and
                    assigns the reference to keys of the char[] type.
                       Each row in the array answers stores a student’s answer, which is graded by comparing it with
                    the key in the array keys. The result is displayed immediately after a student’s answer is graded.


                    7.6 Problem: Finding a Closest Pair
                    The GPS navigation system is becoming increasingly popular. The system uses the graph and
                    geometric algorithms to calculate distances and map a route. This section presents a geomet-
                    ric problem for finding a closest pair of points.



                                   (–1, 3)                       (3, 3)

                                                                       (4, 2)                   x      y
                                                  (1, 1)
                                                                                            0 –1      3
                                                            (2, 0.5)                        1 –1     –1
                                                                                            2 1       1
                                                                                            3 2       0.5
                                                                       (4, –0.5)
                                                                                            4 2      –1
                                  (–1, –1)                 (2, –1)                          5 3       3
                                                                                            6 4       2
                                                                                            7 4      –0.5

                    FIGURE 7.3   Points can be represented in a two-dimensional array.
                                                                            7.6 Problem: Finding a Closest Pair                243
   Given a set of points, the closest-pair problem is to find the two points that are nearest to each
other. In Figure 7.3, for example, points (1, 1) and (2, 0.5) are closest to each other. There are
several ways to solve this problem. An intuitive approach is to compute the distances between all
pairs of points and find the one with the minimum distance, as implemented in Listing 7.3.

LISTING 7.3 FindNearestPoints.java
 1 import java.util.Scanner;
 2
 3 public class FindNearestPoints {
 4   public static void main(String[] args) {
 5     Scanner input = new Scanner(System.in);
 6     System.out.print("Enter the number of points: ");
 7     int numberOfPoints = input.nextInt();                                                            number of points
 8
 9     // Create an array to store points
10     double[][] points = new double[numberOfPoints][2];                                               2-D array
11     System.out.print("Enter " + numberOfPoints + " points: ");
12     for (int i = 0; i < points.length; i++) {                                                        read points
13       points[i][0] = input.nextDouble();
14       points[i][1] = input.nextDouble();
15     }
16
17     // p1 and p2 are the indices in the points array
18     int p1 = 0, p2 = 1; // Initial two points                                                        track two points
19     double shortestDistance = distance(points[p1][0], points[p1][1],                                 track shortestDistance
20       points[p2][0], points[p2][1]); // Initialize shortestDistance
21
22     // Compute distance for every two points
23     for (int i = 0; i < points.length; i++) {                                                        for each point i
24       for (int j = i + 1; j < points.length; j++) {                                                  for each point j
25         double distance = distance(points[i][0], points[i][1],                                       distance between i and j
26           points[j][0], points[j][1]); // Find distance                                              distance between two points
27
28         if (shortestDistance > distance) {
29           p1 = i; // Update p1
30           p2 = j; // Update p2
31           shortestDistance = distance; // Update shortestDistance                                    update shortestDistance
32         }
33       }
34     }
35
36     // Display result
37     System.out.println("The closest two points are " +
38       "(" + points[p1][0] + ", " + points[p1][1] + ") and (" +
39       points[p2][0] + ", " + points[p2][1] + ")");
40   }
41
42   /** Compute the distance between two points (x1, y1) and (x2, y2)*/
43   public static double distance(
44       double x1, double y1, double x2, double y2) {
45     return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
46   }
47 }


     Enter the number of points: 8
     Enter 8 points: -1 3 -1 -1 1 1 2 0.5 2 -1 3 3                           4 2 4 -0.5
     The closest two points are (1, 1) and (2, 0.5)
244 Chapter 7 Multidimensional Arrays
                         The program prompts the user to enter the number of points (lines 6–7). The points are read
                         from the console and stored in a two-dimensional array named points (lines 12–15). The
                         program uses variable shortestDistance (line 19) to store the distance between two near-
                         est points, and the indices of these two points in the points array are stored in p1 and p2
                         (line 18).
                             For each point at index i, the program computes the distance between points[i] and
                         points[j] for all j > i (lines 23–34). Whenever a shorter distance is found, the variable
                         shortestDistance and p1 and p2 are updated (lines 28–32).
                             The distance between two points (x1, y1) and (x2, y2) can be computed using the
                         formula 21x2 - x122 + 1y2 - y122 (lines 43–46).
                             The program assumes that the plane has at least two points. You can easily modify the pro-
                         gram to handle the case if the plane has zero or one point.
multiple closest pairs       Note that there might be more than one closest pair of points with the same minimum dis-
                         tance. The program finds one such pair. You may modify the program to find all closest pairs
                         in Programming Exercise 7.8.

                              Tip
input file                     It is cumbersome to enter all points from the keyboard. You may store the input in a file, say
                               FindNearestPoints.txt, and compile and run the program using the following command:

                               java FindNearestPoints < FindNearestPoints.txt


                         7.7 Problem: Sudoku
                         This book teaches how to program using a wide variety of problems with various levels of dif-
                         ficulty. We use simple, short, and stimulating examples to introduce programming and
Video Note
Sudoku                   problem-solving techniques and use interesting and challenging examples to motivate stu-
                         dents. This section presents an interesting problem of a sort that appears in the newspaper
                         every day. It is a number-placement puzzle, commonly known as Sudoku. This is a very chal-
                         lenging problem. To make it accessible to the novice, this section presents a solution to a sim-
                         plified version of the Sudoku problem, which is to verify whether a solution is correct. The
                         complete solution for solving the Sudoku problem is presented in Supplement VII.A.
                            Sudoku is a 9 * 9 grid divided into smaller 3 * 3 boxes (also called regions or blocks), as
fixed cells              shown in Figure 7.4(a). Some cells, called fixed cells, are populated with numbers from 1 to
free cells               9. The objective is to fill the empty cells, also called free cells, with numbers 1 to 9 so that
                         every row, every column, and every 3 * 3 box contains the numbers 1 to 9, as shown in
                         Figure 7.4(b).



                                    5   3           7                                   5   3   4    6   7   8     9   1   2
                                    6           1   9   5                               6   7   2    1   9   5     3   4   8
                                        9   8                 6                         1   9   8    3   4   2     5   6   7
                                    8               6             3                     8   5   9    7   6   1     4   2   3
                                                                        Solution
                                    4           8       3         1                     4   2   6    8   5   3     7   9   1
                                    7               2             6                     7   1   3    9   2   4     8   5   6
                                        6                                               9   6   1    5   3   7     2   8   4
                                                4   1   9         5                     2   8   7    4   1   9     6   3   5
                                                    8         7   9                     3   4   5    2   8   6     1   7   9

                                                (a) Puzzle                                          (b) Solution

                         FIGURE 7.4     The Sudoku puzzle in (a) is solved in (b).
                                                                                                 7.7 Problem: Sudoku 245
   For convenience, we use value 0 to indicate a free cell, as shown in Figure 7.5(a). The grid       representing a grid
can be naturally represented using a two-dimensional array, as shown in Figure 7.5(a).


             5   3   0   0   7     0   0   0   0   int[][] grid =
             6   0   0   1   9     5   0   0   0    {{5, 3, 0, 0,      7,   0,   0,   0,   0},
                                                      {6, 0, 0, 1,     9,   5,   0,   0,   0},
             0   9   8   0   0     0   0   6   0
                                                      {0, 9, 8, 0,     0,   0,   0,   6,   0},
             8   0   0   0   6     0   0   0   3      {8, 0, 0, 0,     6,   0,   0,   0,   3},
             4   0   0   8   0     3   0   0   1      {4, 0, 0, 8,     0,   3,   0,   0,   1},
             7   0   0   0   2     0   0   0   6      {7, 0, 0, 0,     2,   0,   0,   0,   6},
                                                      {0, 6, 0, 0,     0,   0,   2,   8,   0},
             0   6   0   0   0     0   0   0   0      {0, 0, 0, 4,     1,   9,   0,   0,   5},
             0   0   0   4   1     9   0   0   5      {0, 0, 0, 0,     8,   0,   0,   7,   9}
             0   0   0   0   8     0   0   7   9     };

                             (a)                                      (b)

FIGURE 7.5   A grid can be represented using a two-dimensional array.


   To find a solution for the puzzle we must replace each 0 in the grid with an appropriate num-
ber from 1 to 9. For the solution in Figure 7.4(b), the grid should be as shown in Figure 7.6.


                                   A solution grid is
                                     {{5, 3, 4, 6, 7, 8,   9,   1,   2},
                                      {6, 7, 2, 1, 9, 5,   3,   4,   8},
                                      {1, 9, 8, 3, 4, 2,   5,   6,   7},
                                      {8, 5, 9, 7, 6, 1,   4,   2,   3},
                                      {4, 2, 6, 8, 5, 3,   7,   9,   1},
                                      {7, 1, 3, 9, 2, 4,   8,   5,   6},
                                      {9, 6, 1, 5, 3, 7,   2,   8,   4},
                                      {2, 8, 7, 4, 1, 9,   6,   3,   5},
                                      {3, 4, 5, 2, 8, 6,   1,   7,   9}
                                     };

FIGURE 7.6   A solution is stored in grid.

   A simplified version of the Sudoku problem is to check the validity of a solution. The pro-
gram in Listing 7.4 prompts the user to enter a solution and reports whether it is valid.

LISTING 7.4 CheckSudokuSolution.java
 1 import java.util.Scanner;
 2
 3 public class CheckSudokuSolution {
 4   public static void main(String[] args) {
 5     // Read a Sudoku solution
 6     int[][] grid = readASolution();                                                                read input
 7
 8     System.out.println(isValid(grid) ? "Valid solution" :                                          solution valid?
 9       "Invalid solution");
10   }
11
12   /** Read a Sudoku solution from the console */
13   public static int[][] readASolution() {                                                          read solution
14     // Create a Scanner
15     Scanner input = new Scanner(System.in);
246 Chapter 7 Multidimensional Arrays
                    16
                    17       System.out.println("Enter a Sudoku puzzle solution:");
                    18       int[][] grid = new int[9][9];
                    19       for (int i = 0; i < 9; i++)
                    20         for (int j = 0; j < 9; j++)
                    21           grid[i][j] = input.nextInt();
                    22
                    23       return grid;
                    24   }
                    25
                    26   /** Check whether a solution is valid */
check solution      27   public static boolean isValid(int[][] grid) {
                    28     // Check whether each row has numbers 1 to 9
check rows          29     for (int i = 0; i < 9; i++)
                    30       if (!is1To9(grid[i]) ) // If grid[i] does not contain 1 to 9
                    31         return false;
                    32
                    33       // Check whether each column has numbers 1 to 9
check columns       34       for (int j = 0; j < 9; j++) {
                    35         // Obtain a column in the one-dimensional array
                    36         int[] column = new int[9];
                    37         for (int i = 0; i < 9; i++) {
                    38           column[i] = grid[i][j];
                    39         }
                    40
                    41           if (!is1To9(column) ) // If column does not contain 1 to 9
                    42             return false;
                    43       }
                    44
                    45       // Check whether each 3-by-3 box has numbers 1 to 9
check small boxes   46       for (int i = 0; i < 3; i++) {
                    47         for (int j = 0; j < 3; j++) {
                    48           // The starting element in a small 3-by-3 box
                    49           int k = 0;
                    50           int[] list = new int[9]; // Get all numbers in the box to list
                    51           for (int row = i * 3; row < i * 3 + 3; row ++)
                    52             for (int column = j * 3; column < j * 3 + 3; column++)
                    53               list[k++] = grid[row][column];
                    54
                    55               if (!is1To9(list) ) // If list does not contain 1 to 9
                    56                 return false;
                    57           }
                    58       }
                    59
all valid           60       return true; // The fixed cells are valid
                    61   }
                    62
                    63   /** Check whether the one-dimensional array contains 1 to 9 */
contains 1 to 9 ?   64   public static boolean is1To9(int[] list) {
                    65     // Make a copy of the array
                    66     int[] temp = new int[list.length];
copy of array       67     System.arraycopy(list, 0, temp, 0, list.length);
                    68
                    69       // Sort the array
sort array          70       java.util.Arrays.sort(temp);
                    71
                    72       // Check whether the list contains 1, 2, 3, ..., 9
check 1 to 9        73       for (int i = 0; i < 9; i++)
                                                                                          7.7 Problem: Sudoku 247
74       if (temp[i] != i + 1)
75         return false;
76
77     return true; // The list contains exactly 1 to 9
78   }
79 }



    Enter a Sudoku         puzzle solution:
     9 6 3 1 7 4 2         5 8
     1 7 8 3 2 5 6         4 9
     2 5 4 6 8 9 7         3 1
     8 2 1 4 3 7 5         9 6
     4 9 6 8 5 2 3         1 7
     7 3 5 9 6 1 8         2 4
     5 8 9 7 1 3 4         6 2
     3 1 7 2 4 6 9         8 5
     6 4 2 5 9 8 1         7 3
    Valid solution



The program invokes the readASolution() method (line 6) to read a Sudoku solution and
return a two-dimensional array representing a Sudoku grid.
   The isValid(grid) method (lines 27–61) checks whether every row contains numbers 1              isValid method
to 9 (lines 29–31). grid is a two-dimensional array. grid[i] is a one-dimensional array for        check rows
the ith row. Invoking is1To9(grid[i]) returns true if the row grid[i] contains exactly
numbers from 1 to 9 (line 30).
   To check whether each column in grid has numbers 1 to 9, get a column into a one-               check columns
dimensional array (lines 36–39) and invoke the is1To9 method to check whether it has 1 to
9 (line 41).
   To check whether each small 3 * 3 box in grid has numbers 1 to 9, get a box into a one-         check small boxes
dimensional array (lines 49–53) and invoke the is1To9 method to check whether it has 1 to
9 (line 55).
   How do you locate all the cells in the same box? First, locate the starting cells of the
3 * 3 boxes. They are at (3i, 3j) for i = 0, 1, 2 and j = 0, 1, 2, as illustrated in
Figure 7.7.


                                     grid[0][0]                              grid[0][6]




                                       grid[6][3]

            The location of the starting cell for
            each grid is at (3*i, 3*j) for i = 0, 1,
            2 and j = 0, 1, 2. For example,
            grid[6][3]).


FIGURE 7.7 The location of the first cell in a 3 * 3 box determines the locations of other cells
in the box.
248 Chapter 7 Multidimensional Arrays
                       With this observation, you can easily identify all the cells in the box. Suppose
                    grid[r][c] is the starting cell of a 3 * 3 box. The cells in the box can be traversed in a
                    nested loop as follows:
                       // Get all cells in a 3-by-3 box starting at grid[r][c]
                       for (int row = r; row < r + 3; row++)
                         for (int column = c; column < c + 3; column++)
                           // grid[row][column] is in the box

                    All the numbers in a small box are collected into a one-dimensional array list (line 53), and
                    invoking is1To9(list) checks whether list contains numbers 1 to 9 (line 55).
is1To9 method          The is1To9(list) method (lines 64–78) checks whether array list contains exactly
                    numbers 1 to 9. It first copies list to a new array temp, then sorts temp. Note that if you sort
                    list, the contents of grid will be changed. After temp is sorted, the numbers in temp
                    should be 1, 2, Á , 9, if temp contains exactly 1 to 9. The loop in lines 73–75 checks
                    whether this is the case.
                       It is cumbersome to enter 81 numbers from the console. When you test the program, you
input file          may store the input in a file, say CheckSudokuSolution.txt, and run the program using the fol-
                    lowing command:
                       java CheckSudokuSoluton < CheckSudokuSoluton.txt


                    7.8 Multidimensional Arrays
                    In the preceding section, you used a two-dimensional array to represent a matrix or a table.
                    Occasionally, you will need to represent n-dimensional data structures. In Java, you can cre-
                    ate n-dimensional arrays for any integer n.
                       The way to declare two-dimensional array variables and create two-dimensional arrays can
                    be generalized to declare n-dimensional array variables and create n-dimensional arrays for
                    n 7 = 3. For example, the following syntax declares a three-dimensional array variable
                    scores, creates an array, and assigns its reference to scores.

                       double[][][] data = new double[10][24][2];

                    A multidimensional array is actually an array in which each element is another array. A three-
                    dimensional array consists of an array of two-dimensional arrays, each of which is an array of
                    one-dimensional arrays. For example, suppose x = new int[2][2][5], x[0] and x[1]
                    are two-dimensional arrays. X[0][0], x[0][1], x[1][0], and x[1][1] are one-
                    dimensional arrays and each contains five elements. x.length is 2, x[0].length and
                    x[1].length are 2, and X[0][0].length, x[0][1].length, x[1][0].length, and
                    x[1][1].length are 5.


                    7.8.1 Problem: Daily Temperature and Humidity
                    Suppose a meteorology station records the temperature and humidity at each hour of every
                    day and stores the data for the past ten days in a text file named weather.txt. Each line of the
                    file consists of four numbers that indicate the day, hour, temperature, and humidity. The con-
                    tents of the file may look like the one in (a):

                     1 1 76.4 0.92                                    10 24 98.7 0.74
                     1 2 77.7 0.93                                    1 2 77.7 0.93
                     ...                                              ...
                     10 23 97.7 0.71                                  10 23 97.7 0.71
                     10 24 98.7 0.74                                  1 1 76.4 0.92

                                         (a)                                                (b)
                                                                                   7.8 Multidimensional Arrays 249
   Note that the lines in the file are not necessary in order. For example, the file may appear
as shown in (b).
   Your task is to write a program that calculates the average daily temperature and humidity
for the 10 days. You can use the input redirection to read the file and store the data in a three-
dimensional array, named data. The first index of data ranges from 0 to 9 and represents 10
days, the second index ranges from 0 to 23 and represents 24 hours, and the third index
ranges from 0 to 1 and represents temperature and humidity, respectively. Note that the days
are numbered from 1 to 10 and hours from 1 to 24 in the file. Since the array index starts from
0, data[0][0][0] stores the temperature in day 1 at hour 1 and data[9][23][1] stores
the humidity in day 10 at hour 24.
   The program is given in Listing 7.5.

LISTING 7.5 Weather.java
 1 import java.util.Scanner;
 2
 3 public class Weather {
 4   public static void main(String[] args) {
 5     final int NUMBER_OF_DAYS = 10;
 6     final int NUMBER_OF_HOURS = 24;
 7     double[][][] data
 8       = new double[NUMBER_OF_DAYS][NUMBER_OF_HOURS][2];                                           three-dimensional array
 9
10     Scanner input = new Scanner(System.in);
11     // Read input using input redirection from a file
12     for (int k = 0; k < NUMBER_OF_DAYS * NUMBER_OF_HOURS; k++) {
13       int day = input.nextInt();
14       int hour = input.nextInt();
15       double temperature = input.nextDouble();
16       double humidity = input.nextDouble();
17       data[day - 1][hour - 1][0] = temperature;
18       data[day - 1][hour - 1][1] = humidity;
19     }
20
21     // Find the average daily temperature and humidity
22     for (int i = 0; i < NUMBER_OF_DAYS; i++) {
23       double dailyTemperatureTotal = 0, dailyHumidityTotal = 0;
24       for (int j = 0; j < NUMBER_OF_HOURS; j++) {
25         dailyTemperatureTotal += data[i][j][0];
26         dailyHumidityTotal += data[i][j][1];
27       }
28
29       // Display result
30       System.out.println("Day " + i + "'s average temperature is "
31         + dailyTemperatureTotal / NUMBER_OF_HOURS);
32       System.out.println("Day " + i + "'s average humidity is "
33         + dailyHumidityTotal / NUMBER_OF_HOURS);
34     }
35   }
35 }

    Day    0's   average   temperature     is 77.7708
    Day    0's   average   humidity is     0.929583
    Day    1's   average   temperature     is 77.3125
    Day    1's   average   humidity is     0.929583
    ...
    Day    9's average temperature is 79.3542
    Day    9's average humidity is 0.9125
250 Chapter 7 Multidimensional Arrays
                          You can use the following command to run the program:

                             java Weather < Weather.txt

                          A three-dimensional array for storing temperature and humidity is created in line 8. The loop
                          in lines 12–19 reads the input to the array. You can enter the input from the keyboard, but doing
                          so will be awkward. For convenience, we store the data in a file and use the input redirection to
                          read the data from the file. The loop in lines 24–27 adds all temperatures for each hour in a day
                          to dailyTemperatureTotal and all humidity for each hour to dailyHumidityTotal. The
                          average daily temperature and humidity are displayed in lines 30–33.

                          7.8.2     Problem: Guessing Birthdays
                          Listing 3.3, GuessBirthday.java, gives a program that guesses a birthday. The program can be
                          simplified by storing the numbers in five sets in a three-dimensional array, and it prompts the
                          user for the answers using a loop, as shown in Listing 7.6. The sample run of the program can
                          be the same as shown in Listing 3.3.

                          LISTING 7.6 GuessBirthdayUsingArray.java
                           1 import java.util.Scanner;
                           2
                           3 public class GuessBirthdayUsingArray {
                           4   public static void main(String[] args) {
                           5     int day = 0; // Day to be determined
                           6     int answer;
                           7
three-dimensional array    8     int[][][] dates = {
                           9       {{ 1, 3, 5, 7},
                          10        { 9, 11, 13, 15},
                          11        {17, 19, 21, 23},
                          12        {25, 27, 29, 31}},
                          13       {{ 2, 3, 6, 7},
                          14        {10, 11, 14, 15},
                          15        {18, 19, 22, 23},
                          16        {26, 27, 30, 31}},
                          17       {{ 4, 5, 6, 7},
                          18        {12, 13, 14, 15},
                          19        {20, 21, 22, 23},
                          20        {28, 29, 30, 31}},
                          21       {{ 8, 9, 10, 11},
                          22        {12, 13, 14, 15},
                          23        {24, 25, 26, 27},
                          24        {28, 29, 30, 31}},
                          25       {{16, 17, 18, 19},
                          26        {20, 21, 22, 23},
                          27        {24, 25, 26, 27},
                          28        {28, 29, 30, 31}}};
                          29
                          30     // Create a Scanner
                          31     Scanner input = new Scanner(System.in);
                          32
                          33     for (int i = 0; i < 5; i++) {
Set i                     34       System.out.println("Is your birthday in Set" + (i + 1) + "?");
                          35       for (int j = 0; j < 4; j++) {
                          36         for (int k = 0; k < 4; k++)
                          37           System.out.printf("%4d", dates[i][j][k] );
                          38         System.out.println();
                          39       }
                                                                                                  Review Questions 251
40
41       System.out.print("\nEnter 0 for No and 1 for Yes: ");
42       answer = input.nextInt();
43
44       if (answer == 1)
45         day += dates[i][0][0] ;                                                                    add to Set i
46     }
47
48     System.out.println("Your birth day is " + day);
49   }
50 }

A three-dimensional array dates is created in Lines 8–28. This array stores five sets of num-
bers. Each set is a 4-by-4 two-dimensional array.
   The loop starting from line 33 displays the numbers in each set and prompts the user to
answer whether the birthday is in the set (lines 41–42). If the day is in the set, the first number
(dates[i][0][0]) in the set is added to variable day (line 45).


   CHAPTER SUMMARY
   1. A two-dimensional array can be used to store a table.
   2. A variable for two-dimensional arrays can be declared using the syntax:
         elementType[][] arrayVar.

   3. A two-dimensional array can be created using the syntax:              new elementType-
         [ROW_SIZE][COLUMN_SIZE].

   4. Each element in a two-dimensional array is represented using the syntax:
         arrayVar[rowIndex][columnIndex].

   5. You can create and initialize a two-dimensional array using an array initializer with the
         syntax: elementType[][] arrayVar = {{row values}, ..., {row values}}.
   6. You can use arrays of arrays to form multidimensional arrays. For example, a vari-
         able for three-dimensional arrays can be declared as elementType[][][]
         arrayVar and a three-dimensional array can be created using new element-
         Type[size1][size2][size3].


   REVIEW QUESTIONS
   7.1      Declare and create a 4-by-5 int matrix.
   7.2      Can the rows in a two-dimensional array have different lengths?
   7.3      What is the output of the following code?
            int[][] array = new int[5][6];
            int[] x = {1, 2};
            array[0] = x;
            System.out.println("array[0][1] is " + array[0][1]);

   7.4      Which of the following statements are valid array declarations?
            int[][] r = new int[2];
            int[] x = new int[];
            int[][] y = new int[3][];
252 Chapter 7 Multidimensional Arrays

                      7.5    Why does the is1To9 method need to copy list to temp? What happens if you
                             replace the code in lines 66–70 in Listing 7.4 with the following code:

                             java.util.Arrays.sort(list);

                      7.6    Declare and create a 4 × 6 × 5 int array.


                      PROGRAMMING EXERCISES
                      7.1*   (Summing all the numbers in a matrix) Write a method that sums all the integers in
                             a matrix of integers using the following header:

                             public static double sumMatrix(int[][] m)

                             Write a test program that reads a 4-by-4 matrix and displays the sum of all its ele-
                             ments. Here is a sample run:



                             Enter a 4-by-4 matrix row by row:
                              1 2 3 4
                              5 6 7 8
                              9 10 11 12
                             13 14 15 16
                             Sum of the matrix is 136




                      7.2* (Summing the major diagonal in a matrix) Write a method that sums all the inte-
                             gers in the major diagonal in an n * n matrix of integers using the following
                             header:

                             public static int sumMajorDiagonal(int[][] m)

                             Write a test program that reads a 4-by-4 matrix and displays the sum of all its ele-
                             ments on the major diagonal. Here is a sample run:



                             Enter a 4-by-4 matrix row by row:
                             1 2 3 4
                             5 6 7 8
                              9 10 11 12
                             13 14 15 16
                             Sum of the elements in the major diagonal is 34




                      7.3* (Sorting students on grades) Rewrite Listing 7.2, GradeExam.java, to display the
                             students in increasing order of the number of correct answers.
                      7.4** (Computing the weekly hours for each employee) Suppose the weekly hours for all
                             employees are stored in a two-dimensional array. Each row records an employee’s
                             seven-day work hours with seven columns. For example, the array shown below
                             stores the work hours for eight employees. Write a program that displays employ-
                             ees and their total hours in decreasing order of the total hours.
                                                                                    Programming Exercises 253
                                         Su M    T W H       F Sa
                            Employee 0   2   4   3   4   5   8   8
                            Employee 1   7   3   4   3   3   4   4
                            Employee 2   3   3   4   3   3   2   2
                            Employee 3   9   3   4   7   3   4   1
                            Employee 4   3   5   4   3   6   3   8
                            Employee 5   3   4   4   6   3   4   4
                            Employee 6   3   7   4   8   3   8   4
                            Employee 7   6   3   5   9   2   7   9


7.5    (Algebra: adding two matrices) Write a method to add two matrices. The header
       of the method is as follows:

       public static double[][] addMatrix(double[][] a, double[][] b)

       In order to be added, the two matrices must have the same dimensions and the
       same or compatible types of elements. Let c be the resulting matrix. Each element
       cij is aij + bij . For example, for two 3 * 3 matrices a and b, c is

           a11 a12 a13       b11 b12 b13       a11 + b11     a12 + b12     a13 + b13
         £ a21 a22 a23 ≥ + £ b21 b22 b23 ≥ = £ a21 + b21     a22 + b22     a23 + b23 ≥
           a31 a32 a33       b31 b32 b33       a31 + b31     a32 + b32     a33 + b33

       Write a test program that prompts the user to enter two 3 * 3 matrices and dis-
       plays their sum. Here is a sample run:


        Enter matrix1: 1 2 3 4 5 6 7 8 9
        Enter matrix2: 0 2 4 1 4.5 2.2 1.1 4.3 5.2
        The matrices are added as follows
         1.0 2.0 3.0      0.0 2.0 4.0     1.0 4.0 7.0
         4.0 5.0 6.0 +    1.0 4.5 2.2 =    5.0 9.5 8.2
         7.0 8.0 9.0      1.1 4.3 5.2     8.1 12.3 14.2


7.6** (Algebra: multiplying two matrices) Write a method to multiply two matrices. The
       header of the method is as follows:

       public static double[][] multiplyMatrix(double[][] a, double[][] b)                   Video Note
                                                                                             Multiply two matrices
       To multiply matrix a by matrix b, the number of columns in a must be the same as
       the number of rows in b, and the two matrices must have elements of the same or
       compatible types. Let c be the result of the multiplication. Assume the column size
       of matrix a is n. Each element cij is ai1 * b1j + ai2 * b2j + Á + ain * bnj .
       For example, for two 3 * 3 matrices a and b, c is

                       a11 a12 a13       b11 b12 b13       c11 c12 c13
                     £ a21 a22 a23 ≥ * £ b21 b22 b23 ≥ = £ c21 c22 c23 ≥
                       a31 a32 a33       b31 b32 b33       c31 c32 c33

       where cij = ai1 * b1j + ai2 * b2j + ai3 * b3j .
       Write a test program that prompts the user to enter two 3 * 3 matrices and displays
       their product. Here is a sample run:
254 Chapter 7 Multidimensional Arrays

                               Enter matrix1: 1 2 3 4 5 6 7 8 9
                               Enter matrix2: 0 2 4 1 4.5 2.2 1.1 4.3 5.2
                               The matrices are multiplied as follows:
                                1 2 3      0 2.0 4.0      5.3 23.9 24
                                4 5 6   * 1 4.5 2.2 =     11.6 56.3 58.2
                                7 8 9      1.1 4.3 5.2    17.9 88.7 92.4


                      7.7*     (Points nearest to each other) Listing 7.3 gives a program that finds two points in
                               a two-dimensional space nearest to each other. Revise the program so that it finds
                               two points in a three-dimensional space nearest to each other. Use a two-dimen-
                               sional array to represent the points. Test the program using the following points:
                               double[][] points = {{-1, 0, 3}, {-1, -1, -1}, {4, 1, 1},
                                 {2, 0.5, 9}, {3.5, 2, -1}, {3, 1.5, 3}, {-1.5, 4, 2},
                                 {5.5, 4, -0.5}};

                               The formula for computing the distance between two points (x1, y1, z1) and
                               (x2, y2, z2) is 21x2 - x122 + 1y2 - y122 + 1z2 - z122 .
                      7.8**    (All closest pairs of points) Revise Listing 7.3, FindNearestPoints.java, to find
                               all closest pairs of points with same minimum distance.
                      7.9***   (Game: playing a TicTacToe game) In a game of TicTacToe, two players take
                               turns marking an available cell in a 3 * 3 grid with their respective tokens (either
                               X or O). When one player has placed three tokens in a horizontal, vertical, or
                               diagonal row on the grid, the game is over and that player has won. A draw (no
                               winner) occurs when all the cells on the grid have been filled with tokens and nei-
                               ther player has achieved a win. Create a program for playing TicTacToe.
                               The program prompts two players to enter X token and O token alternately. When-
                               ever a token is entered, the program redisplays the board on the console and deter-
                               mines the status of the game (win, draw, or continue). Here is a sample run:

                               ——————-——————
                               |   |   |   |
                               ————————————-
                               |   |   |   |
                               ————————————-
                               |   |   |   |
                               ————————————-
                               Enter a row (1, 2, or 3) for player X: 1
                               Enter a column (1, 2, or 3) for player X: 1
                               ————————————-
                               |   |   |   |
                               ————————————-
                               |   | X |   |
                               ————————————-
                               |   |   |   |
                               ————————————-
                               Enter a row (1, 2, or 3) for player O: 1
                               Enter a column (1, 2, or 3) for player O: 2
                               ————————————-
                               |   |   |   |
                               ————————————-
                               |   | X | O |
                               ————————————-
                               |   |   |   |
                               ————————————-
                                                                                       Programming Exercises 255

        Enter a row (1, 2, or 3) for player X:
        ...
        ————————————-
        | X |   |   |
        ————————————-
        | O | X | O |
        ————————————-
        |   |   | X |
        ————————————-
        X player won



7.10* (Game: TicTacToe board) Write a program that randomly fills in 0s and 1s into a
        TicTacToe board, prints the board, and finds the rows, columns, or diagonals with
        all 0s or 1s. Use a two-dimensional array to represent a TicTacToe board. Here is a
        sample run of the program:

        001
        001
        111
        All 1s on row 2
        All 1s on column 2

7.11** (Game: nine heads and tails) Nine coins are placed in a 3-by-3 matrix with some
        face up and some face down. You can represent the state of the coins using a 3-by-3
        matrix with values 0 (head) and 1 (tail). Here are some examples:

        0 0 0       1 0 1       1 1 0       1 0 1       1 0 0
        0 1 0       0 0 1       1 0 0       1 1 0       1 1 1
        0 0 0       1 0 0       0 0 1       1 0 0       1 1 0

        Each state can also be represented using a binary number. For example, the pre-
        ceding matrices correspond to the numbers

        000010000 101001100 110100001 101110100 100111110

        There are a total of 512 possibilities. So, you can use decimal numbers 0, 1, 2, 3,
         Á , and 511 to represent all states of the matrix. Write a program that prompts the
        user to enter a number between 0 and 511 and displays the corresponding matrix
        with characters H and T. Here is a sample run:



        Enter a number between 0 and 511: 7
        H H H
        H H H
        T T T




      The user entered 7, which corresponds to 000000111. Since 0 stands for H and 1
      for T, the output is correct.
7.12**(Financial application: computing tax) Rewrite Listing 3.6, ComputeTax.java,
      using arrays. For each filing status, there are six tax rates. Each rate is applied to a
      certain amount of taxable income. For example, from the taxable income of
      $400,000 for a single filer, $8,350 is taxed at 10%, (33,950 – 8,350) at 15%,
      (82,250 – 33,950) at 25%, (171,550 – 82,550) at 28%, (372,550 – 82,250) at 33%,
256 Chapter 7 Multidimensional Arrays
                              and (400,000 – 372,950) at 36%. The six rates are the same for all filing statuses,
                              which can be represented in the following array:
                              double[] rates = {0.10, 0.15, 0.25, 0.28, 0.33, 0.35};

                              The brackets for each rate for all the filing statuses can be represented in a two-
                              dimensional array as follows:
                              int[][] brackets = {
                                 {8350, 33950, 82250, 171550, 372950},   // Single filer
                                 {16700, 67900, 137050, 20885, 372950}, // Married jointly
                                 {8350, 33950, 68525, 104425, 186475}, // Married separately
                                 {11950, 45500, 117450, 190200, 372950} // Head of household
                              };

                              Suppose the taxable income is $400,000 for single filers. The tax can be computed
                              as follows:
                              tax = brackets[0][0] * rates[0] +
                                (brackets[0][1] – brackets[0][0]) * rates[1]                    +
                                (brackets[0][2] – brackets[0][1]) * rates[2]                    +
                                (brackets[0][3] – brackets[0][2]) * rates[3]                    +
                                (brackets[0][4] – brackets[0][3]) * rates[4]                    +
                                (400000 – brackets[0][4]) * rates[5]

                      7.13* (Locating the largest element) Write the following method that returns the location
                              of the largest element in a two-dimensional array.
                              public static int[] locateLargest(double[][] a)

                              The return value is a one-dimensional array that contains two elements. These two
                              elements indicate the row and column indices of the largest element in the two-
                              dimensional array. Write a test program that prompts the user to enter a two-dimen-
                              sional array and displays the location of the largest element in the array. Here is a
                              sample run:

                              Enter the number of rows and columns of the array: 3 4
                              Enter the array:
                              23.5 35 2 10
                              4.5 3 45 3.5
                              35 44 5.5 9.6
                              The location of the largest element is at (1, 2)

                      7.14** (Exploring matrix) Write a program that prompts the user to enter the length of a square
                              matrix, randomly fills in 0s and 1s into the matrix, prints the matrix, and finds the rows,
                              columns, and diagonals with all 0s or 1s. Here is a sample run of the program:

                              Enter the size for         the matrix: 4
                              0111
                              0000
                              0100
                              1111
                              All 0s on row 1
                              All 1s on row 3
                              No same numbers on         a column
                              No same numbers on         the major diagonal
                              No same numbers on         the sub-diagonal
                                                                                           Programming Exercises 257

  7.15*      (Geometry: same line?) Suppose a set of points are given. Write a program to
             check whether all the points are on the same line. Use the following sets to test
             your program:
             double[][] set1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}};
             double[][] set2 = {{0, 1}, {1, 2}, {4, 5}, {5, 6}};
             double[][] set3 = {{0, 1}, {1, 2}, {4, 5}, {4.5, 4}};

  7.16*      (Sorting two-dimensional array) Write a method to sort a two-dimensional
             array using following header:

             public static void sort(int m[][])

          The method performs a primary sort on rows and a secondary sort on columns.
          For example, the array 554, 26, 51, 76, 54, 56, 51, 26, 51, 16, 54, 166 will be
          sorted to 551, 16, 51, 26, 51, 76, 54, 16, 54, 26, 54, 566.
  7.17*** (Financial tsunami) Banks lend money to each other. In tough economic times,
          if a bank goes bankrupt, it may not be able to pay back the loan. A bank’s total
          assets are its current balance plus its loans to other banks. Figure 7.8 is a dia-
          gram that shows five banks. The banks’ current balances are 25, 125, 175, 75,
          and 181 million dollars, respectively. The directed edge from node 1 to node 2
          indicates that bank 1 lends 40 million dollars to bank 2.

                                                      125
                                                  1
                                 100.5                           85
                   25
                                                                                     75
                        0
                                          125                                    3

                                                            40
                        320.5                   125
                                                                            75

                                           125                   2    175
                                181   4

FIGURE 7.8   Banks lend money to each other.

             If a bank’s total assets are under a certain limit, the bank is unsafe. The money it
             borrowed cannot be returned to the lender, and the lender cannot count the loan in
             its total assets. Consequently, the lender may also be unsafe, if its total assets are
             under the limit. Write a program to find all unsafe banks. Your program reads the
             input as follows. It first reads two integers n and limit, where n indicates the
             number of banks and limit is the minimum total assets for keeping a bank safe. It
             then reads n lines that describe the information for n banks with id from 0 to n-1.
             The first number in the line is the bank’s balance, the second number indicates the
             number of banks that borrowed money from the bank, and the rest are pairs of two
             numbers. Each pair describes a borrower. The first number in the pair is the bor-
             rower’s id and the second is the amount borrowed. For example, the input for the
             five banks in Figure 7.8 is as follows (note that the limit is 201):

             5 201
             25 2 1 100.5 4 320.5
             125 2 2 40 3 85
             175 2 0 125 3 75
             75 1 0 125
             181 1 2 125
258 Chapter 7 Multidimensional Arrays
                               The total assets of bank 3 are (75 + 125), which is under 201. So bank 3 is
                               unsafe. After bank 3 becomes unsafe, the total assets of bank 1 fall below (125 +
                               40). So, bank 1 is also unsafe. The output of the program should be
                               Unsafe banks are 3 1
                               (Hint: Use a two-dimensional array borrowers to represent loans.
                               borrowers[i][j] indicates the loan that bank i loans to bank j. Once bank j
                               becomes unsafe, borrowers[i][j] should be set to 0.)
                      7.18*    (Shuffling rows) Write a method that shuffles the rows in a two-dimensional int
                               array using the following header:

                               public static void shuffle(int[][] m)

                               Write a test program that shuffles the following matrix:

                               int[][] m = {{1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10}};

                      7.19** (Pattern recognition: consecutive four equal numbers) Write the following
                               method that tests whether a two-dimensional array has four consecutive num-
                               bers of the same value, either horizontally, vertically, or diagonally.

                               public static boolean isConsecutiveFour(int[][] values)

                               Write a test program that prompts the user to enter the number of rows and
                               columns of a two-dimensional array and then the values in the array and dis-
                               plays true if the array contains four consecutive numbers with the same value.
                               Otherwise, display false. Here are some examples of the true cases:


                       0 1 0 3 1 6 1        0 1 0 3 1 6 1          0 1 0 3 1 6 1          0 1 0 3 1 6 1
                       0 1 6 8 6 0 1        0 1 6 8 6 0 1          0 1 6 8 6 0 1          0 1 6 8 6 0 1
                       5 6 2 1 8 2 9        5 5 2 1 8 2 9          5 6 2 1 6 2 9          9 6 2 1 8 2 9
                       6 5 6 1 1 9 1        6 5 6 1 1 9 1          6 5 6 6 1 9 1          6 9 6 1 1 9 1
                       1 3 6 1 4 0 7        1 5 6 1 4 0 7          1 3 6 1 4 0 7          1 3 9 1 4 0 7
                       3 3 3 3 4 0 7        3 5 3 3 4 0 7          3 6 3 3 4 0 7          3 3 3 9 4 0 7



                      7.20*** (Game: connect four) Connect four is a two-player board game in which the
                               players alternately drop colored disks into a seven-column, six-row vertically-
                               suspended grid, as shown below.
                                                                                  Programming Exercises 259
         The objective of the game is to connect four same-colored disks in a row, a col-
         umn, or a diagonal before your opponent can do likewise. The program prompts
         two players to drop a RED or YELLOW disk alternately. Whenever a disk is
         dropped, the program redisplays the board on the console and determines the
         status of the game (win, draw, or continue). Here is a sample run:


         | | | | | | | |
         | | | | | | | |
         | | | | | | | |
         | | | | | | | |
         | | | | | | | |
         | | | | | | | |
         ——————————————————————
         Drop a red disk at column (0–6): 0
         | | | | | | | |
         | | | | | | | |
         | | | | | | | |
         | | | | | | | |
         | | | | | | | |
         |R| | | | | | |
         ——————————————————————
         Drop a yellow disk at column (0–6): 3
         | | | | | | |     |
         | | | | | | |     |
         | | | | | | |     |
         | | | | | | |     |
         | | | | | | |     |
         |R| | |Y| | |     |
         ...
         ...
         ...
         Drop a yellow     disk at column (0–6): 6
         | | | | | | | |
         | | | | | | | |
         | | | |R| | | |
         | | | |Y|R|Y| |
         | | |R|Y|Y|Y|Y|
         |R|Y|R|Y|R|R|R|
         ——————————————————————
         The yellow player won



7.21*** (Game: multiple Sudoku solutions) The complete solution for the Sudoku prob-
         lem is given in Supplement VII.A. A Sudoku problem may have multiple solu-
         tions. Modify Sudoku.java in Supplement VII.A to display the total number of
         the solutions. Display two solutions if multiple solutions exist.
7.22*    (Algebra: 2 * 2 matrix inverse) The inverse of a square matrix A is denoted A-1,
         such that A×A-1 = I, where I is the identity matrix with all 1’s on the diagonal
                                                                               1 2
         and 0 on all other cells. For example, the inverse of matrix B              R is
                                                                               3 4
            -0.5 1
         B           R , i.e.,
            1.5    0
                                     1 2          -0.5 1            1 0
                                   B       R * B             R = B         R
                                     3 4           1.5     0       0 1
260 Chapter 7 Multidimensional Arrays
                             The inverse of a 2 * 2 matrix A can be obtained using the following formula:

                                                      a   b                 1     d        -b
                                              A = B         R    A-1 =          B             R
                                                      c   d              ad - bc -c        a

                             Implement the following method to obtain an inverse of the matrix:

                             public static double[][] inverse(double[][] A)

                             The method returns null if ad – bc is 0.
                             Write a test program that prompts the user to enter a, b, c, d for a matrix and dis-
                             plays its inverse matrix. Here is a sample run:



                              Enter a, b, c, d: 1 2 3 4
                              -2.0 1.0
                              1.5 -0.5




                              Enter a, b, c, d: 0.5 2 1.5 4.5
                              -6.0 2.6666666666666665
                              2.0 -0.6666666666666666



                      7.23* (Algebra: 3 * 3 matrix inverse) The inverse of a square matrix A is denoted A-1,
                             such that A×A-1 = I, where I is the identity matrix with all 1’s on the diagonal
                                                                               1 2 1
                             and 0 on all other cells. The inverse of matrix C 2 3 1 S, for example, is
                                                                               4 5 3


                                                            -2    0.5       0.5
                                                           C 1    0.5       -0.5 S
                                                             1    -1.5      0.5
                             —that is,


                                          1    2   1     -2       0.5       0.5        1    0     0
                                         C2    3   1S * C 1       0.5       -0.5 S = C 0    1     0S
                                          4    5   3      1       -1.5      0.5        0    0     1


                             The inverse of a 3 * 3 matrix


                                                                a11   a12     a13
                                                          A = C a21   a22     a23 S
                                                                a31   a32     a33
                                                                                Programming Exercises 261

can be obtained using the following formula if ƒ A ƒ Z 0:

                   a22a33 - a23a32     a13a32 - a12a33     a12a23 - a13a22
              1
    A-1 =        C a23a31 - a21a33     a11a33 - a13a31     a13a21 - a11a23 S
             ƒAƒ
                   a21a32 - a22a31     a12a31 - a11a32     a11a22 - a12a21
               a11   a12   a13
     ƒ A ƒ = 3 a21   a22   a23 3 = a11a22a33 + a31a12a23 + a13a21a32
               a31   a32   a33
          - a13a22a31 - a11a23a32 - a33a21a12 .


Implement the following function to obtain an inverse of the matrix:

public static double[][] inverse(double[][] A)

The method returns null if |A| is 0.
Write a test program that prompts the user to enter a11 , a12 , a13 , a21 , a22 , a23 ,
a31 , a32 , a33 for a matrix and displays its inverse matrix. Here is a sample run:


Enter a11, a12, a13, a21, a22, a23, a31, a32, a33:
  1 2 1 2 3 1 4 5 3
-2 0.5 0.5
1 0.5 -0.5
1 -1.5 0.5



Enter a11, a12, a13, a21, a22, a23, a31, a32, a33:
  1 4 2 2 5 8 2 1 8
2.0 -1.875 1.375
0.0 0.25 -0.25
-0.5 0.4375 -0.1875
This page intentionally left blank
                                                           CHAPTER 8
OBJECTS AND CLASSES
Objectives
■   To describe objects and classes, and use classes to model objects (§8.2).
■   To use UML graphical notations to describe classes and objects (§8.2).
■   To demonstrate defining classes and creating objects (§8.3).
■   To create objects using constructors (§8.4).
■   To access objects via object reference variables (§8.5).
■   To define a reference variable using a reference type (§8.5.1).
■   To access an object’s data and methods using the
    object member access operator (.) (§8.5.2).
■   To define data fields of reference types and assign
    default values for an object’s data fields (§8.5.3).
■   To distinguish between object reference variables
    and primitive data type variables (§8.5.4).
■   To use classes Date, Random, and JFrame in
    the Java library (§8.6).
■   To distinguish between instance and static variables
    and methods (§8.7).
■   To define private data fields with appropriate get
    and set methods (§8.8).
■   To encapsulate data fields to make classes easy
    to maintain (§8.9).
■   To develop methods with object arguments and
    differentiate between primitive-type arguments
    and object-type arguments (§8.10).
■   To store and process objects in arrays (§8.11).
264 Chapter 8 Objects and Classes

                   8.1 Introduction
                   Having learned the material in earlier chapters, you are able to solve many programming prob-
                   lems using selections, loops, methods, and arrays. However, these Java features are not suffi-
                   cient for developing graphical user interfaces and large-scale software systems. Suppose you
                   want to develop a GUI (graphical user interface, pronounced goo-ee) as shown in Figure 8.1.
why OOP?           How do you program it?

                    Button                  Label    Text Field     Check Box      Radio Button       Combo Box




                   FIGURE 8.1 The GUI objects are created from classes.

                     This chapter begins the introduction of object-oriented programming, which will enable
                   you to develop GUI and large-scale software systems effectively.

                   8.2 Defining Classes for Objects
object             Object-oriented programming (OOP) involves programming using objects. An object repre-
                   sents an entity in the real world that can be distinctly identified. For example, a student, a
                   desk, a circle, a button, and even a loan can all be viewed as objects. An object has a unique
                   identity, state, and behavior.
state                    ■   The state of an object (also known as its properties or attributes) is represented by
                             data fields with their current values. A circle object, for example, has a data field
                             radius, which is the property that characterizes a circle. A rectangle object has data
                             fields width and height, which are the properties that characterize a rectangle.
behavior                 ■   The behavior of an object (also known as its actions) is defined by methods. To
                             invoke a method on an object is to ask the object to perform an action. For example,
                             you may define a method named getArea() for circle objects. A circle object may
                             invoke getArea() to return its area.
                   Objects of the same type are defined using a common class. A class is a template, blueprint,
contract           or contract that defines what an object’s data fields and methods will be. An object is an
                   instance of a class. You can create many instances of a class. Creating an instance is referred
instantiation      to as instantiation. The terms object and instance are often interchangeable. The relationship
object             between classes and objects is analogous to that between an apple-pie recipe and apple pies.
instance           You can make as many apple pies as you want from a single recipe. Figure 8.2 shows a class
                   named Circle and its three objects.

                                               Class Name: Circle               A class template

                                               Data Fields:
                                                radius is _____
                                               Methods:
                                                getArea



                          Circle Object 1       Circle Object 2        Circle Object 3             Three objects of
                                                                                                   the Circle class
                          Data Fields:          Data Fields:           Data Fields:
                           radius is 10          radius is 25           radius is 125

                   FIGURE 8.2    A class is a template for creating objects.
                                                                                    8.2 Defining Classes for Objects 265
   A Java class uses variables to define data fields and methods to define actions. Addition-            class
ally, a class provides methods of a special type, known as constructors, which are invoked to            data field
create a new object. A constructor can perform any action, but constructors are designed to              method
perform initializing actions, such as initializing the data fields of objects. Figure 8.3 shows an       constructor
example of defining the class for circle objects.

                class Circle {
                  /** The radius of this circle */
                  double radius = 1.0;                                       Data field

                    /** Construct a circle object */
                    Circle() {
                    }
                                                                             Constructors
                    /** Construct a circle object */
                    Circle(double newRadius) {
                      radius = newRadius;
                    }

                    /** Return the area of this circle */
                    double getArea() {                                       Method
                      return radius * radius * Math.PI;
                    }
                }

FIGURE 8.3   A class is a construct that defines objects of the same type.

   The Circle class is different from all of the other classes you have seen thus far. It does
not have a main method and therefore cannot be run; it is merely a definition for circle
objects. The class that contains the main method will be referred to in this book, for conve-
nience, as the main class.                                                                               main class
   The illustration of class templates and objects in Figure 8.2 can be standardized using UML
(Unified Modeling Language) notations. This notation, as shown in Figure 8.4, is called a UML
class diagram, or simply a class diagram. In the class diagram, the data field is denoted as             class diagram

   dataFieldName: dataFieldType


 UML Class Diagram                           Circle                             Class name

                               radius: double                                   Data fields

                               Circle()                                         Constructors and
                                                                                methods
                               Circle(newRadius: double)
                               getArea(): double


             circle1: Circle             circle2: Circle   circle3: Circle                UML notation
                                                                                          for objects
               radius = 10                radius = 25      radius = 125

FIGURE 8.4   Classes and objects can be represented using UML notations.

The constructor is denoted as
   ClassName(parameterName: parameterType)

The method is denoted as
   methodName(parameterName: parameterType): returnType
266 Chapter 8 Objects and Classes

                     8.3 Example: Defining Classes and Creating Objects
                     This section gives two examples of defining classes and uses the classes to create objects.
                     Listing 8.1 is a program that defines the Circle class and uses it to create objects. To avoid a
                     naming conflict with several improved versions of the Circle class introduced later in this
                     book, the Circle class in this example is named Circle1.
                        The program constructs three circle objects with radius 1.0, 25, and 125 and displays the
                     radius and area of each of the three circles. Change the radius of the second object to 100 and
                     display its new radius and area.


                     LISTING 8.1 TestCircle1.java
main class            1   public class TestCircle1 {
                      2     /** Main method */
main method           3     public static void main(String[] args) {
                      4       // Create a circle with radius 1.0
create object         5       Circle1 circle1 = new Circle1();
                      6       System.out.println("The area of the circle of radius "
                      7         + circle1.radius + " is " + circle1.getArea() );
                      8
                      9           // Create a circle with radius 25
create object        10           Circle1 circle2 = new Circle1(25);
                     11           System.out.println("The area of the circle of radius "
                     12             + circle2.radius + " is " + circle2.getArea());
                     13
                     14           // Create a circle with radius 125
create object        15           Circle1 circle3 = new Circle1(125);
                     16           System.out.println("The area of the circle of radius "
                     17             + circle3.radius + " is " + circle3.getArea());
                     18
                     19           // Modify circle radius
                     20           circle2.radius = 100;
                     21           System.out.println("The area of the circle of radius "
                     22             + circle2.radius + " is " + circle2.getArea() );
                     23       }
                     24   }
                     25
                     26   // Define the circle class with two constructors
class Circle1        27   class Circle1 {
data field           28     double radius ;
                     29
                     30       /** Construct a circle with radius 1 */
no-arg constructor   31       Circle1() {
                     32         radius = 1.0;
                     33       }
                     34
                     35       /** Construct a circle with a specified radius */
second constructor   36       Circle1(double newRadius) {
                     37         radius = newRadius;
                     38       }
                     39
                     40       /** Return the area of this circle */
method               41       double getArea() {
                     42         return radius * radius * Math.PI;
                     43       }
                     44   }
                                                    8.3 Example: Defining Classes and Creating Objects 267

 The   area   of   the   circle   of   radius   1.0 is 3.141592653589793
 The   area   of   the   circle   of   radius   25.0 is 1963.4954084936207
 The   area   of   the   circle   of   radius   125.0 is 49087.385212340516
 The   area   of   the   circle   of   radius   100.0 is 31415.926535897932



The program contains two classes. The first of these, TestCircle1, is the main class. Its sole
purpose is to test the second class, Circle1. Such a program that uses the class is often
referred to as a client of the class. When you run the program, the Java runtime system                client
invokes the main method in the main class.
    You can put the two classes into one file, but only one class in the file can be a public class.   public class
Furthermore, the public class must have the same name as the file name. Therefore, the file
name is TestCircle1.java, since TestCircle1 is public.
    The main class contains the main method (line 3) that creates three objects. As in creating
an array, the new operator is used to create an object from the constructor. new Circle1()
creates an object with radius 1.0 (line 5), new Circle1(25) creates an object with radius 25
(line 10), and new Circle1(125) creates an object with radius 125 (line 15).
    These three objects (referenced by circle1, circle2, and circle3) have different data but
the same methods. Therefore, you can compute their respective areas by using the getArea()
method. The data fields can be accessed via the reference of the object using circle1.radius,
circle2.radius, and circle3.radius, respectively. The object can invoke its method via
the reference of the object using circle1.getArea(), circle2.getArea(), and
circle3.getArea(), respectively.
    These three objects are independent. The radius of circle2 is changed to 100 in line 20.
The object’s new radius and area is displayed in lines 21–22.
    There are many ways to write Java programs. For instance, you can combine the two
classes in the example into one, as shown in Listing 8.2.

LISTING 8.2 Circle1.java
 1 public class Circle1 {
 2   /** Main method */
 3   public static void main(String[] args) {                                                          main method
 4     // Create a circle with radius 1.0
 5     Circle1 circle1 = new Circle1();
 6     System.out.println("The area of the circle of radius                       "
 7       + circle1.radius + " is " + circle1.getArea() );
 8
 9     // Create a circle with radius 25
10     Circle1 circle2 = new Circle1(25);
11     System.out.println("The area of the circle of radius                       "
12       + circle2.radius + " is " + circle2.getArea());
13
14     // Create a circle with radius 125
15     Circle1 circle3 = new Circle1(125);
16     System.out.println("The area of the circle of radius                       "
17       + circle3.radius + " is " + circle3.getArea());
18
19     // Modify circle radius
20     circle2.radius = 100;
21     System.out.println("The area of the circle of radius                       "
22       + circle2.radius + " is " + circle2.getArea());
23   }
24
268 Chapter 8 Objects and Classes
data field           25     double radius;
                     26
                     27     /** Construct a circle with radius 1 */
no-arg constructor   28     Circle1() {
                     29       radius = 1.0;
                     30     }
                     31
                     32     /** Construct a circle with a specified radius */
second constructor   33     Circle1(double newRadius) {
                     34       radius = newRadius;
                     35     }
                     36
                     37     /** Return the area of this circle */
method               38     double getArea() {
                     39       return radius * radius * Math.PI;
                     40     }
                     41 }

                     Since the combined class has a main method, it can be executed by the Java interpreter. The
                     main method is the same as in Listing 1.1. This demonstrates that you can test a class by sim-
                     ply adding a main method in the same class.
                        As another example, consider TV sets. Each TV is an object with states (current channel,
                     current volume level, power on or off) and behaviors (change channels, adjust volume, turn
                     on/off). You can use a class to model TV sets. The UML diagram for the class is shown in
                     Figure 8.5.
                        Listing 8.3 gives a program that defines the TV class.


                                            TV

                       channel: int                                      The current channel (1 to 120) of this TV.
                       volumeLevel: int                                  The current volume level (1 to 7) of this TV.
                       on: boolean                                       Indicates whether this TV is on/off.

                       +TV()                                             Constructs a default TV object.
                       +turnOn(): void                                   Turns on this TV.
                       +turnOff(): void                                  Turns off this TV.
                       +setChannel(newChannel: int): void                Sets a new channel for this TV.
                       +setVolume(newVolumeLevel: int): void             Sets a new volume level for this TV.
                       +channelUp(): void                                Increases the channel number by 1.
                       +channelDown(): void                              Decreases the channel number by 1.
                       +volumeUp(): void                                 Increases the volume level by 1.
                       +volumeDown(): void                               Decreases the volume level by 1.


                     FIGURE 8.5   The TV class models TV sets.


                     LISTING 8.3 TV.java
                      1 public class TV {
data fields           2   int channel = 1; // Default channel is 1
                      3   int volumeLevel = 1; // Default volume level is 1
                      4   boolean on = false; // By default TV is off
                      5
constructor           6   public TV() {
                      7   }
                      8
                                                  8.3 Example: Defining Classes and Creating Objects 269
 9     public void turnOn() {                                                                   turn on TV
10       on = true;
11     }
12
13     public void turnOff() {                                                                  turn off TV
14       on = false;
15     }
16
17     public void setChannel(int newChannel) {                                                 set a new channel
18       if (on && newChannel >= 1 && newChannel <= 120)
19         channel = newChannel;
20     }
21
22     public void setVolume(int newVolumeLevel) {                                              set a new volume
23       if (on && newVolumeLevel >= 1 && newVolumeLevel <= 7)
24         volumeLevel = newVolumeLevel;
25     }
26
27     public void channelUp() {                                                                increase channel
28       if (on && channel < 120)
29         channel++;
30     }
31
32     public void channelDown() {                                                              decrease channel
33       if (on && channel > 1)
34         channel--;
35     }
36
37     public void volumeUp() {                                                                 increase volume
38       if (on && volumeLevel < 7)
39         volumeLevel++;
40     }
41
42     public void volumeDown() {                                                               decrease volume
43       if (on && volumeLevel > 1)
44         volumeLevel--;
45     }
46 }

Note that the channel and volume level are not changed if the TV is not on. Before either of
these is changed, its current value is checked to ensure that it is within the correct range.
   Listing 8.4 gives a program that uses the TV class to create two objects.

LISTING 8.4 TestTV.java
 1 public class TestTV {
 2   public static void main(String[] args) {                                                   main method
 3     TV tv1 = new TV();                                                                       create a TV
 4     tv1.turnOn();                                                                            turn on
 5     tv1.setChannel(30);                                                                      set a new channel
 6     tv1.setVolume(3);                                                                        set a new volume
 7
 8     TV tv2 = new TV();                                                                       create a TV
 9     tv2.turnOn();                                                                            turn on
10     tv2.channelUp();                                                                         increase channel
11     tv2.channelUp();
12     tv2.volumeUp();                                                                          increase volume
13
14     System.out.println("tv1's channel is " + tv1.channel                                     display state
15       + " and volume level is " + tv1.volumeLevel );
270 Chapter 8 Objects and Classes
                          16     System.out.println("tv2's channel is " + tv2.channel
                          17       + " and volume level is " + tv2.volumeLevel);
                          18   }
                          19 }



                           tv1's channel is 30 and volume level is 3
                           tv2's channel is 3 and volume level is 2



                          The program creates two objects in lines 3 and 8 and invokes the methods on the objects to
                          perform actions for setting channels and volume levels and for increasing channels and vol-
                          umes. The program displays the state of the objects in lines 14–17. The methods are invoked
                          using a syntax such as tv1.turnOn() (line 4). The data fields are accessed using a syntax
                          such as tv1.channel (line 14).
                             These examples have given you a glimpse of classes and objects. You may have many
                          questions regarding constructors, objects, reference variables, and accessing data fields, and
                          invoking object’s methods. The sections that follow discuss these issues in detail.


                          8.4 Constructing Objects Using Constructors
                          Constructors are a special kind of method. They have three peculiarities:
constructor’s name              ■   A constructor must have the same name as the class itself.
no return type                  ■   Constructors do not have a return type—not even void.
new operator                    ■   Constructors are invoked using the new operator when an object is created. Con-
                                    structors play the role of initializing objects.
overloaded constructors   The constructor has exactly the same name as the defining class. Like regular methods, con-
                          structors can be overloaded (i.e., multiple constructors can have the same name but different
                          signatures), making it easy to construct objects with different initial data values.
no void                      It is a common mistake to put the void keyword in front of a constructor. For example,
                             public void Circle() {
                             }

                          In this case, Circle() is a method, not a constructor.
constructing objects         Constructors are used to construct objects. To construct an object from a class, invoke a
                          constructor of the class using the new operator, as follows:
                             new ClassName(arguments);

                          For example, new Circle() creates an object of the Circle class using the first construc-
                          tor defined in the Circle class, and new Circle(25) creates an object using the second
                          constructor defined in the Circle class.
                             A class normally provides a constructor without arguments (e.g., Circle()). Such a con-
no-arg constructor        structor is referred to as a no-arg or no-argument constructor.
                             A class may be defined without constructors. In this case, a no-arg constructor with an
default constructor       empty body is implicitly defined in the class. This constructor, called a default constructor, is
                          provided automatically only if no constructors are explicitly defined in the class.


                          8.5 Accessing Objects via Reference Variables
                          Newly created objects are allocated in the memory. They can be accessed via reference
                          variables.
                                                                    8.5 Accessing Objects via Reference Variables                    271

8.5.1 Reference Variables and Reference Types
Objects are accessed via object reference variables, which contain references to the objects.                reference variable
Such variables are declared using the following syntax:

   ClassName objectRefVar;

A class is essentially a programmer-defined type. A class is a reference type, which means                   reference type
that a variable of the class type can reference an instance of the class. The following statement
declares the variable myCircle to be of the Circle type:

   Circle myCircle;

The variable myCircle can reference a Circle object. The next statement creates an object
and assigns its reference to myCircle:

   myCircle = new Circle();

Using the syntax shown below, you can write a single statement that combines the declaration
of an object reference variable, the creation of an object, and the assigning of an object refer-
ence to the variable.

   ClassName objectRefVar = new ClassName();

Here is an example:

   Circle myCircle = new Circle();

The variable myCircle holds a reference to a Circle object.

      Note
      An object reference variable that appears to hold an object actually contains a reference to that      object vs. object reference
      object. Strictly speaking, an object reference variable and an object are different, but most of the     variable
      time the distinction can be ignored. So it is fine, for simplicity, to say that myCircle is a
      Circle object rather than use the longer-winded description that myCircle is a variable that
      contains a reference to a Circle object.


      Note
      Arrays are treated as objects in Java. Arrays are created using the new operator. An array variable    array object
      is actually a variable that contains a reference to an array.


8.5.2 Accessing an Object’s Data and Methods
After an object is created, its data can be accessed and its methods invoked using the dot oper-
ator (.), also known as the object member access operator:                                                   dot operator

      ■ objectRefVar.dataField                 references a data field in the object.
      ■ objectRefVar.method(arguments)                      invokes a method on the object.
For example, myCircle.radius references the radius in myCircle, and
myCircle.getArea() invokes the getArea method on myCircle. Methods are invoked
as operations on objects.
   The data field radius is referred to as an instance variable, because it is dependent on a                instance variable
specific instance. For the same reason, the method getArea is referred to as an instance                     instance method
method, because you can invoke it only on a specific instance. The object on which an
instance method is invoked is called a calling object.                                                       calling object
272 Chapter 8 Objects and Classes

                              Caution
                              Recall that you use Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a
invoking methods              method in the Math class. Can you invoke getArea() using Circle.getArea()? The answer
                              is no. All the methods in the Math class are static methods, which are defined using the static
                              keyword. However, getArea() is an instance method, and thus nonstatic. It must be invoked from
                              an object using objectRefVar.methodName(arguments) (e.g., myCircle.getArea()).
                              Further explanation is given in §8.7, “Static Variables, Constants, and Methods.”


                              Note
                              Usually you create an object and assign it to a variable. Later you can use the variable to reference
                              the object. Occasionally an object does not need to be referenced later. In this case, you can cre-
                              ate an object without explicitly assigning it to a variable, as shown below:

                              new Circle();

                              or

                              System.out.println("Area is " + new Circle(5).getArea());

                              The former statement creates a Circle object. The latter creates a Circle object and invokes
anonymous object              its getArea method to return its area. An object created in this way is known as an anonymous
                              object.


                        8.5.3      Reference Data Fields and the null Value
reference data fields   The data fields can be of reference types. For example, the following Student class contains
                        a data field name of the String type. String is a predefined Java class.

                           class Student {
                             String name; // name has default value null
                             int age; // age has default value 0
                             boolean isScienceMajor; // isScienceMajor has default value false
                             char gender; // c has default value '\u0000'
                           }

                        If a data field of a reference type does not reference any object, the data field holds a special
null value              Java value, null. null is a literal just like true and false. While true and false are
                        Boolean literals, null is a literal for a reference type.
default field values        The default value of a data field is null for a reference type, 0 for a numeric type, false
                        for a boolean type, and '\u0000' for a char type. However, Java assigns no default value
                        to a local variable inside a method. The following code displays the default values of data
                        fields name, age, isScienceMajor, and gender for a Student object:

                           class Test {
                             public static void main(String[] args) {
                               Student student = new Student();
                               System.out.println("name? " + student.name );
                               System.out.println("age? " + student.age );
                               System.out.println("isScienceMajor? " + student.isScienceMajor );
                               System.out.println("gender? " + student.gender );
                             }
                           }

                        The code below has a compile error, because local variables x and y are not initialized:

                           class Test {
                             public static void main(String[] args) {
                                                                     8.5 Accessing Objects via Reference Variables 273
           int x; // x has no default value
           String y; // y has no default value
           System.out.println("x is " + x );
           System.out.println("y is " + y );
       }
   }



       Caution
       NullPointerException is a common runtime error. It occurs when you invoke a method on            NullPointerException
       a reference variable with null value. Make sure you assign an object reference to the variable
       before invoking the method through the reference variable.


8.5.4 Differences Between Variables of Primitive Types
      and Reference Types
Every variable represents a memory location that holds a value. When you declare a variable,
you are telling the compiler what type of value the variable can hold. For a variable of a prim-
itive type, the value is of the primitive type. For a variable of a reference type, the value is a
reference to where an object is located. For example, as shown in Figure 8.6, the value of int
variable i is int value 1, and the value of Circle object c holds a reference to where the
contents of the Circle object are stored in the memory.



                                                                     Created using new Circle()

           Primitive type   int i = 1      i       1


           Object type      Circle c c         reference                      c: Circle

                                                                             radius = 1


FIGURE 8.6 A variable of a primitive type holds a value of the primitive type, and a variable
of a reference type holds a reference to where an object is stored in memory.



   When you assign one variable to another, the other variable is set to the same value. For a
variable of a primitive type, the real value of one variable is assigned to the other variable. For
a variable of a reference type, the reference of one variable is assigned to the other variable.
As shown in Figure 8.7, the assignment statement i = j copies the contents of j into i for
primitive variables. As shown in Figure 8.8, the assignment statement c1 = c2 copies the
reference of c2 into c1 for reference variables. After the assignment, variables c1 and c2
refer to the same object.



                                     Primitive type assignment i = j

                                        Before:             After:

                                       i       1           i         2

                                       j       2           j         2

FIGURE 8.7     Primitive variable j is copied to variable i.
274 Chapter 8 Objects and Classes

                                                                 Object type assignment c1 = c2

                                              Before:                                            After:

                                         c1                                                 c1


                                         c2                                                 c2


                                                   c2: Circle           c1: Circle                    c2: Circle         c1: Circle

                                                   radius = 9           radius = 5                    radius = 9         radius = 5


                                FIGURE 8.8      Reference variable c2 is copied to variable c1.


                                      Note
                                      As shown in Figure 8.8, after the assignment statement c1 = c2, c1 points to the same object
                                      referenced by c2. The object previously referenced by c1 is no longer useful and therefore is now
garbage                               known as garbage. Garbage occupies memory space. The Java runtime system detects garbage
garbage collection                    and automatically reclaims the space it occupies. This process is called garbage collection.


                                      Tip
                                      If you know that an object is no longer needed, you can explicitly assign null to a reference vari-
                                      able for the object. The JVM will automatically collect the space if the object is not referenced by
                                      any reference variable.


                                8.6 Using Classes from the Java Library
                                Listing 8.1 defined the Circle1 class and created objects from the class. You will frequently
                                use the classes in the Java library to develop programs. This section gives some examples of
                                the classes in the Java library.

                                8.6.1 The Date Class
                                In Listing 2.8, ShowCurrentTime.java, you learned how to obtain the current time using
                                System.currentTimeMillis(). You used the division and remainder operators to extract
                                current second, minute, and hour. Java provides a system-independent encapsulation of date
java.util.Date class            and time in the java.util.Date class, as shown in Figure 8.9.


                                                java.util.Date

    The + sign indicates       +Date()                                               Constructs a Date object for the current time.
    public modifier            +Date(elapseTime: long)                               Constructs a Date object for a given time in
                                                                                       milliseconds elapsed since January 1, 1970, GMT.
                               +toString(): String                                   Returns a string representing the date and time.
                               +getTime(): long                                      Returns the number of milliseconds since January 1,
                                                                                       1970, GMT.
                               +setTime(elapseTime: long): void                      Sets a new elapse time in the object.

    FIGURE 8.9       A Date object represents a specific date and time.

                                   You can use the no-arg constructor in the Date class to create an instance for the current date
                                and time, its getTime() method to return the elapsed time since January 1, 1970, GMT, and its
                                toString method to return the date and time as a string. For example, the following code
                                                                            8.6 Using Classes from the Java Library          275
   java.util.Date date = new java.util.Date() ;                                                           create object
   System.out.println("The elapsed time since Jan 1, 1970 is " +
     date.getTime() + " milliseconds");                                                                   get elapsed time
   System.out.println(date.toString() );                                                                  invoke toString

displays the output like this:
   The elapsed time since Jan 1, 1970 is 1100547210284 milliseconds
   Mon Nov 15 14:33:30 EST 2004

The Date class has another constructor, Date(long elapseTime), which can be used to
construct a Date object for a given time in milliseconds elapsed since January 1, 1970, GMT.

8.6.2      The Random Class
You have used Math.random() to obtain a random double value between 0.0 and 1.0
(excluding 1.0). Another way to generate random numbers is to use the java.util.Random
class, as shown in Figure 8.10, which can generate a random int, long, double, float, and
boolean value.

        java.util.Random
  +Random()                            Constructs a Random object with the current time as its seed.
  +Random(seed: long)                  Constructs a Random object with a specified seed.
  +nextInt(): int                      Returns a random int value.
  +nextInt(n: int): int                Returns a random int value between 0 and n (exclusive).
  +nextLong(): long                    Returns a random long value.
  +nextDouble(): double                Returns a random double value between 0.0 and 1.0 (exclusive).
  +nextFloat(): float                  Returns a random float value between 0.0F and 1.0F (exclusive).
  +nextBoolean(): boolean              Returns a random boolean value.

FIGURE 8.10    A Random object can be used to generate random values.

   When you create a Random object, you have to specify a seed or use the default seed. The
no-arg constructor creates a Random object using the current elapsed time as its seed. If two
Random objects have the same seed, they will generate identical sequences of numbers. For
example, the following code creates two Random objects with the same seed, 3.
   Random random1 = new Random(3);
   System.out.print("From random1: ");
   for (int i = 0; i < 10; i++)
     System.out.print(random1.nextInt(1000) + " ");

   Random random2 = new Random(3);
   System.out.print("\nFrom random2: ");
   for (int i = 0; i < 10; i++)
     System.out.print(random2.nextInt(1000) + " ");

The code generates the same sequence of random int values:
   From random1: 734 660 210 581 128 202 549 564 459 961
   From random2: 734 660 210 581 128 202 549 564 459 961


      Note
      The ability to generate the same sequence of random values is useful in software testing and        same sequence
      many other applications. In software testing, you can test your program using a fixed sequence of
      numbers before using different sequences of random numbers.
276 Chapter 8 Objects and Classes

                   8.6.3     Displaying GUI Components
                        Pedagogical Note
                        Graphical user interface (GUI) components are good examples for teaching OOP. Simple GUI
                        examples are introduced for this purpose. The full introduction to GUI programming begins with
                        Chapter 12, “GUI Basics.”

                   When you develop programs to create graphical user interfaces, you will use Java
                   classes such as JFrame, JButton, JRadioButton, JComboBox, and JList to create
                   frames, buttons, radio buttons, combo boxes, lists, and so on. Listing 8.5 is an example
                   that creates two windows using the JFrame class. The output of the program is shown in
                   Figure 8.11.




                   FIGURE 8.11   The program creates two windows using the JFrame class.



                   LISTING 8.5 TestFrame.java
                    1 import javax.swing.JFrame;
                    2
                    3 public class TestFrame {
                    4   public static void main(String[] args) {
create an object    5     JFrame frame1 = new JFrame();
invoke a method     6     frame1.setTitle("Window 1");
                    7     frame1.setSize(200, 150);
                    8     frame1.setLocation(200, 100);
                    9     frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   10     frame1.setVisible(true);
                   11
create an object   12     JFrame frame2 = new JFrame();
invoke a method    13     frame2.setTitle("Window 2");
                   14     frame2.setSize(200, 150);
                   15     frame2.setLocation(410, 100);
                   16     frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   17     frame2.setVisible(true);
                   18   }
                   19 }

                   This program creates two objects of the JFrame class (lines 5, 12) and then uses the methods
                   setTitle, setSize, setLocation, setDefaultCloseOperation, and setVisible to
                   set the properties of the objects. The setTitle method sets a title for the window (lines 6,
                   13). The setSize method sets the window’s width and height (lines 7, 14). The
                   setLocation method specifies the location of the window’s upper-left corner (lines 8, 15).
                   The setDefaultCloseOperation method terminates the program when the frame is
                   closed (lines 9, 16). The setVisible method displays the window.
                      You can add graphical user interface components, such as buttons, labels, text fields,
                   check boxes, and combo boxes to the window. The components are defined using
                   classes. Listing 8.6 gives an example of creating a graphical user interface, as shown in
                   Figure 8.1.
                                                                     8.6 Using Classes from the Java Library 277

LISTING 8.6 GUIComponents.java
 1 import javax.swing.*;
 2                                                                                                   Video Note
                                                                                                     Use classes
 3 public class GUIComponents {
 4   public static void main(String[] args) {
 5     // Create a button with text OK
 6     JButton jbtOK = new JButton("OK");                                                            create a button
 7
 8     // Create a button with text Cancel
 9     JButton jbtCancel = new JButton("Cancel");                                                    create a button
10
11     // Create a label with text "Enter your name: "
12     JLabel jlblName = new JLabel("Enter your name: ");                                            create a label
13
14     // Create a text field with text "Type Name Here"
15     JTextField jtfName = new JTextField("Type Name Here");                                        create a text field
16
17     // Create a check box with text bold
18     JCheckBox jchkBold = new JCheckBox("Bold");                                                   create a check box
19
20     // Create a check box with text italic
21     JCheckBox jchkItalic = new JCheckBox("Italic");                                               create a check box
22
23     // Create a radio button with text red
24     JRadioButton jrbRed = new JRadioButton("Red");                                                create a radio button
25
26     // Create a radio button with text yellow
27     JRadioButton jrbYellow = new JRadioButton("Yellow");                                          create a radio button
28
29     // Create a combo box with several choices
30     JComboBox jcboColor = new JComboBox(new String[]{"Freshman",                                  create a combo box
31       "Sophomore", "Junior", "Senior"});
32
33     // Create a panel to group components
34     JPanel panel = new JPanel();                                                                  create a panel
35     panel.add(jbtOK); // Add the OK button to the panel                                           add to panel
36     panel.add(jbtCancel); // Add the Cancel button to the panel
37     panel.add(jlblName); // Add the label to the panel
38     panel.add(jtfName); // Add the text field to the panel
39     panel.add(jchkBold); // Add the check box to the panel
40     panel.add(jchkItalic); // Add the check box to the panel
41     panel.add(jrbRed); // Add the radio button to the panel
42     panel.add(jrbYellow); // Add the radio button to the panel
43     panel.add(jcboColor); // Add the combo box to the panel
44
45     JFrame frame = new JFrame(); // Create a frame                                                create a frame
46     frame.add(panel); // Add the panel to the frame                                               add panel to frame
47     frame.setTitle("Show GUI Components");
48     frame.setSize(450, 100);
49     frame.setLocation(200, 100);
50     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
51     frame.setVisible(true);                                                                       display frame
52   }
53 }

This program creates GUI objects using the classes JButton, JLabel, JTextField,
JCheckBox, JRadioButton, and JComboBox (lines 6–31). Then, using the JPanel class
(line 34), it then creates a panel object and adds to it the button, label, text field, check box,
278 Chapter 8 Objects and Classes
                                radio button, and combo box (lines 35–43). The program then creates a frame and adds the
                                panel to the frame (line 45). The frame is displayed in line 51.

                                8.7 Static Variables, Constants, and Methods
instance variable               The data field radius in the circle class in Listing 8.1 is known as an instance variable. An
                                instance variable is tied to a specific instance of the class; it is not shared among objects of the
                                same class. For example, suppose that you create the following objects:
                                   Circle circle1 = new Circle();
Video Note                         Circle circle2 = new Circle(5);
static vs. instance
                                The radius in circle1 is independent of the radius in circle2 and is stored in a different mem-
                                ory location. Changes made to circle1’s radius do not affect circle2’s radius, and vice versa.
static variable                    If you want all the instances of a class to share data, use static variables, also known as
                                class variables. Static variables store values for the variables in a common memory location.
                                Because of this common location, if one object changes the value of a static variable, all
                                objects of the same class are affected. Java supports static methods as well as static variables.
static method                   Static methods can be called without creating an instance of the class.
                                   Let us modify the Circle class by adding a static variable numberOfObjects to count
                                the number of circle objects created. When the first object of this class is created,
                                numberOfObjects is 1. When the second object is created, numberOfObjects becomes 2.
                                The UML of the new circle class is shown in Figure 8.12. The Circle class defines the
                                instance variable radius and the static variable numberOfObjects, the instance methods
                                getRadius, setRadius, and getArea, and the static method getNumberOfObjects.
                                (Note that static variables and methods are underlined in the UML class diagram.)

  UML Notation:
   underline: static variables or methods
                                            instantiate
                                                              circle1: Circle             Memory
                                                          radius = 1                          1    radius      After two Circle
                    Circle                                numberOfObjects = 2                                  Objects were created,
                                                                                                               numberOfObjects
  radius: double                                                                                               is 2.
  numberOfObjects: int
                                                                                              2    numberOfObjects
  getNumberOfObjects(): int
  getArea(): double                         instantiate
                                                              circle2: Circle
                                                          radius = 5                          5    radius
                                                          numberOfObjects = 2

FIGURE 8.12 Instance variables belong to the instances and have memory storage independent of one another. Static
variables are shared by all the instances of the same class.

                                   To declare a static variable or define a static method, put the modifier static in the vari-
                                able or method declaration. The static variable numberOfObjects and the static method
                                getNumberOfObjects() can be declared as follows:
declare static variable            static int numberOfObjects;

define static method               static int getNumberObjects() {
                                     return numberOfObjects;
                                   }

                                Constants in a class are shared by all objects of the class. Thus, constants should be declared
                                final static. For example, the constant PI in the Math class is defined as:
declare constant                   final static double PI = 3.14159265358979323846;
                                                           8.7 Static Variables, Constants, and Methods                 279
The new circle class, named Circle2, is declared in Listing 8.7:

LISTING 8.7 Circle2.java
 1 public class Circle2 {
 2   /** The radius of the circle */
 3   double radius;
 4
 5   /** The number of objects created */
 6   static int numberOfObjects = 0;                                                                static variable
 7
 8   /** Construct a circle with radius 1 */
 9   Circle2() {
10     radius = 1.0;
11     numberOfObjects++;                                                                           increase by 1
12   }
13
14   /** Construct a circle with a specified radius */
15   Circle2(double newRadius) {
16     radius = newRadius;
17     numberOfObjects++;                                                                           increase by 1
18   }
19
20   /** Return numberOfObjects */
21   static int getNumberOfObjects() {                                                              static method
22     return numberOfObjects;
23   }
24
25   /** Return the area of this circle */
26   double getArea() {
27     return radius * radius * Math.PI;
28   }
29 }

Method getNumberOfObjects() in Circle2 is a static method. Other examples of static
methods are showMessageDialog and showInputDialog in the JOptionPane class and
all the methods in the Math class. The main method is static, too.
    Instance methods (e.g., getArea()) and instance data (e.g., radius) belong to instances
and can be used only after the instances are created. They are accessed via a reference variable.
Static methods (e.g., getNumberOfObjects()) and static data (e.g., numberOfObjects)
can be accessed from a reference variable or from their class name.
    The program in Listing 8.8 demonstrates how to use instance and static variables and
methods and illustrates the effects of using them.

LISTING 8.8 TestCircle2.java
 1 public class TestCircle2 {
 2   /** Main method */
 3   public static void main(String[] args) {
 4     System.out.println("Before creating objects");
 5     System.out.println("The number of Circle objects is " +
 6       Circle2.numberOfObjects);                                                                  static variable
 7
 8      // Create c1
 9      Circle2 c1 = new Circle2();
10
11     // Display c1 BEFORE c2 is created
12     System.out.println("\nAfter creating c1");
13     System.out.println("c1: radius (" + c1.radius +                                              instance variable
14       ") and number of Circle objects (" +
280 Chapter 8 Objects and Classes
static variable     15          c1.numberOfObjects + ")");
                    16
                    17       // Create c2
                    18       Circle2 c2 = new Circle2(5);
                    19
                    20       // Modify c1
instance variable   21       c1.radius = 9;
                    22
                    23       // Display c1 and c2 AFTER c2 was created
                    24       System.out.println("\nAfter creating c2 and modifying c1");
                    25       System.out.println("c1: radius (" + c1.radius +
                    26         ") and number of Circle objects (" +
static variable     27         c1.numberOfObjects + ")");
                    28       System.out.println("c2: radius (" + c2.radius +
                    29         ") and number of Circle objects (" +
static variable     30         c2.numberOfObjects + ")");
                    31   }
                    32 }

                     Before creating objects
                     The number of Circle objects is 0
                     After creating c1
                     c1: radius (1.0) and number of Circle objects (1)
                     After creating c2 and modifying c1
                     c1: radius (9.0) and number of Circle objects (2)
                     c2: radius (5.0) and number of Circle objects (2)

                    When you compile TestCircle2.java, the Java compiler automatically compiles
                    Circle2.java if it has not been compiled since the last change.
                       Static variables and methods can be accessed without creating objects. Line 6 displays the
                    number of objects, which is 0, since no objects have been created.
                       The main method creates two circles, c1 and c2 (lines 9, 18). The instance variable radius
                    in c1 is modified to become 9 (line 21). This change does not affect the instance variable radius
                    in c2, since these two instance variables are independent. The static variable numberOfObjects
                    becomes 1 after c1 is created (line 9), and it becomes 2 after c2 is created (line 18).
                       Note that PI is a constant defined in Math, and Math.PI references the constant.
                    c.numberOfObjects could be replaced by Circle2.numberOfObjects. This improves
                    readability, because the reader can easily recognize the static variable. You can also replace
                    Circle2.numberOfObjects by Circle2.getNumberOfObjects().

                          Tip
use class name            Use ClassName.methodName(arguments) to invoke a static method and ClassName.-
                          staticVariable to access a static variable. This improves readability, because the user can
                          easily recognize the static method and data in the class.

                    Static variables and methods can be used from instance or static methods in the class. How-
                    ever, instance variables and methods can be used only from instance methods, not from static
                    methods, since static variables and methods don’t belong to a particular object. Thus the code
                    given below is wrong.

                        1 public class Foo {
                        2   int i = 5;
                        3   static int k = 2;
                        4
                        5   public static void main(String[] args) {
                        6     int j = i; // Wrong because i is an instance variable
                        7     m1(); // Wrong because m1() is an instance method
                                                                          8.7 Static Variables, Constants, and Methods 281
     8      }
     9
    10      public void m1() {
    11        // Correct since instance and static variables and methods
    12        // can be used in an instance method
    13        i = i + k + m2(i, k);
    14      }
    15
    16      public static int m2(int i, int j) {
    17        return (int)(Math.pow(i, j));
    18      }
    19 }

Note that if you replace the code in lines 5–8 with the following new code, the program is fine,
because the instance data field i and method m1 are now accessed from an object foo (lines 6–7):
     1 public class Foo {
     2   int i = 5;
     3   static int k = 2;
     4
     5   public static void main(String[] args) {
     6     Foo foo = new Foo();
     7     int j = foo.i; // OK, foo.i accesses the object's instance variable
     8     foo.m1();    // OK. Foo.m1() invokes object's instance method
     9   }
    10
    11   public void m1() {
    12     i = i + k + m2(i, k);
    13   }
    14
    15   public static int m2(int i, int j) {
    16     return (int)(Math.pow(i, j));
    17   }
    18 }

        Design Guide
        How do you decide whether a variable or method should be an instance one or a static one? A vari-        instance or static?
        able or method that is dependent on a specific instance of the class should be an instance variable or
        method. A variable or method that is not dependent on a specific instance of the class should be a
        static variable or method. For example, every circle has its own radius. Radius is dependent on a spe-
        cific circle. Therefore, radius is an instance variable of the Circle class. Since the getArea
        method is dependent on a specific circle, it is an instance method. None of the methods in the Math
        class, such as random, pow, sin, and cos, is dependent on a specific instance. Therefore, these
        methods are static methods. The main method is static and can be invoked directly from a class.

        Caution
        It is a common design error to define an instance method that should have been defined static.           common design error
        For example, the method factorial(int n) should be defined static, as shown below,
        because it is independent of any specific instance.
public class Test {                                              public class Test {
  public int factorial(int n) {                                    public static int factorial(int n)
    int result = 1;                                                  int result = 1;
    for (int i = 1; i <= n; i++)                                     for (int i = 1; i <= n; i++)
           result *= i;                                                    result *= i;
        return result;                                                   return result;
    }                                                                }
}                                                                }
                    (a) Wrong design                                                     (b) Correct design
282 Chapter 8 Objects and Classes

                             8.8 Visibility Modifiers
                             You can use the public visibility modifier for classes, methods, and data fields to denote that
                             they can be accessed from any other classes. If no visibility modifier is used, then by default
                             the classes, methods, and data fields are accessible by any class in the same package. This is
                             known as package-private or package-access.

                                   Note
using packages                     Packages can be used to organize classes. To do so, you need to add the following line as the first
                                   noncomment and nonblank statement in the program:

                                   package packageName;

                                   If a class is defined without the package statement, it is said to be placed in the default package.
                                   Java recommends that you place classes into packages rather using a default package. For simplic-
                                   ity, however, this book uses default packages. For more information on packages, see Supplement
                                   III.G, “Packages.”

                                In addition to the public and default visibility modifiers, Java provides the private and
                             protected modifiers for class members. This section introduces the private modifier. The
                             protected modifier will be introduced in §11.13, “The protected Data and Methods.”
                                The private modifier makes methods and data fields accessible only from within its own
                             class. Figure 8.13 illustrates how a public, default, and private data field or method in class C1
                             can be accessed from a class C2 in the same package and from a class C3 in a different package.


 package p1;                                 package p1;                                         package p2;

 public class C1 {                           public class C2 {                                   public class C3 {
   public int x;                               void aMethod() {                                    void aMethod() {
   int y;                                        C1 o = new C1();                                    C1 o = new C1();
   private int z;                                can access o.x;                                     can access o.x;
                                                 can access o.y;                                     cannot access o.y;
     public void m1() {                          cannot access o.z;                                  cannot access o.z;
     }
     void m2() {                                     can invoke o.m1();                                  can invoke o.m1();
     }                                               can invoke o.m2();                                  cannot invoke o.m2();
     private void m3() {                             cannot invoke o.m3();                               cannot invoke o.m3();
     }                                           }                                                   }
 }                                           }                                                   }

FIGURE 8.13 The private modifier restricts access to its defining class, the default modifier restricts access to a package,
and the public modifier enables unrestricted access.

                                If a class is not defined public, it can be accessed only within the same package. As shown
                             in Figure 8.14, C1 can be accessed from C2 but not from C3.


                              package p1;                            package p1;                              package p2;

                              class C1 {                             public class C2 {                        public class C3 {
                                ...                                    can access C1                            cannot access C1;
                              }                                      }                                          can access C2;
                                                                                                              }

                             FIGURE 8.14 A nonpublic class has package-access.

                                A visibility modifier specifies how data fields and methods in a class can be accessed from
                             outside the class. There is no restriction on accessing data fields and methods from inside the
                                                                                               8.9 Data Field Encapsulation 283
class. As shown in Figure 8.15(b), an object foo of the Foo class cannot access its private
members, because foo is in the Test class. As shown in Figure 8.15(a), an object foo of the
Foo class can access its private members, because foo is defined inside its own class.                           inside access


          public class Foo {                                                  public class Test {
            private boolean x;                                                  public static void main(String[] args) {
                                                                                  Foo foo = new Foo();
              public static void main(String[] args) {                            System.out.println(foo.x);
                Foo foo = new Foo();                                              System.out.println(foo.convert());
                System.out.println(foo.x);                                      }
                System.out.println(foo.convert());                            }
              }

              private int convert() {
                return x ? 1 : 1;
              }
          }

      (a) This is OK because object foo is used inside the Foo class        (b) This is wrong because x and convert are private in Foo.

     FIGURE 8.15        An object can access its private members if it is defined in its own class.


     Caution
      The private modifier applies only to the members of a class. The public modifier can apply
      to a class or members of a class. Using modifiers public and private on local variables would
      cause a compile error.


     Note
      In most cases, the constructor should be public. However, if you want to prohibit the user from
      creating an instance of a class, use a private constructor. For example, there is no reason to create      private constructor
      an instance from the Math class, because all of its data fields and methods are static. To prevent
      the user from creating objects from the Math class, the constructor in java.lang.Math is
      defined as follows:

      private Math() {
      }


8.9 Data Field Encapsulation
The data fields radius and numberOfObjects in the Circle2 class in Listing 8.7 can be
modified directly (e.g., myCircle.radius = 5 or Circle2.numberOfObjects = 10).
                                                                                                                 Video Note
This is not a good practice—for two reasons:                                                                     Data field encapsulation
      ■       First, data may be tampered with. For example, numberOfObjects is to count the
              number of objects created, but it may be mistakenly set to an arbitrary value (e.g.,
              Circle2.numberOfObjects = 10).

      ■       Second, the class becomes difficult to maintain and vulnerable to bugs. Suppose you
              want to modify the Circle2 class to ensure that the radius is nonnegative after other
              programs have already used the class. You have to change not only the Circle2
              class but also the programs that use it, because the clients may have modified the
              radius directly (e.g., myCircle.radius = -5).
   To prevent direct modifications of data fields, you should declare the data fields private,
using the private modifier. This is known as data field encapsulation.                                           data field encapsulation
   A private data field cannot be accessed by an object from outside the class that defines the
private field. But often a client needs to retrieve and modify a data field. To make a private
284 Chapter 8 Objects and Classes
                              data field accessible, provide a get method to return its value. To enable a private data field to
                              be updated, provide a set method to set a new value.

                                    Note
accessor                            Colloquially, a get method is referred to as a getter (or accessor), and a set method is referred
mutator                             to as a setter (or mutator).

                              A get method has the following signature:

                                 public returnType getPropertyName()

boolean accessor              If the returnType is boolean, the get method should be defined as follows by convention:

                                 public boolean isPropertyName()

                              A set method has the following signature:

                                 public void setPropertyName(dataType propertyValue)

                              Let us create a new circle class with a private data-field radius and its associated accessor and
                              mutator methods. The class diagram is shown in Figure 8.16. The new circle class, named
                              Circle3, is defined in Listing 8.9:


                                                Circle
     The - sign indicates
     private modifier        -radius: double                                    The radius of this circle (default: 1.0).
                             -numberOfObjects: int                              The number of circle objects created.

                             +Circle()                                          Constructs a default circle object.
                             +Circle(radius: double)                            Constructs a circle object with the specified radius.
                             +getRadius(): double                               Returns the radius of this circle.
                             +setRadius(radius: double): void                   Sets a new radius for this circle.
                             +getNumberOfObjects(): int                         Returns the number of circle objects created.
                             +getArea(): double                                 Returns the area of this circle.


FIGURE 8.16     The Circle class encapsulates circle properties and provides get/set and other methods.


                              LISTING 8.9 Circle3.java
                               1 public class Circle3 {
                               2   /** The radius of the circle */
encapsulate radius             3   private double radius = 1;
                               4
                               5   /** The number of the objects created */
encapsulate                    6   private static int numberOfObjects = 0;
  numberOfObjects              7
                               8   /** Construct a circle with radius 1 */
                               9   public Circle3() {
                              10     numberOfObjects++;
                              11   }
                              12
                              13   /** Construct a circle with a specified radius */
                              14   public Circle3(double newRadius) {
                              15     radius = newRadius;
                              16     numberOfObjects++;
                              17   }
                              18
                                                                                     8.9 Data Field Encapsulation 285
19     /** Return radius */
20     public double getRadius() {                                                                      access method
21       return radius;
22     }
23
24     /** Set a new radius */
25     public void setRadius(double newRadius) {                                                        mutator method
26       radius = (newRadius >= 0) ? newRadius : 0;
27     }
28
29     /** Return numberOfObjects */
30     public static int getNumberOfObjects() {                                                         access method
31       return numberOfObjects;
32     }
33
34     /** Return the area of this circle */
35     public double getArea() {
36       return radius * radius * Math.PI;
37     }
38 }

The getRadius() method (lines 20–22) returns the radius, and the setRadius(newRadius)
method (line 25–27) sets a new radius into the object. If the new radius is negative, 0 is set to the
radius in the object. Since these methods are the only ways to read and modify radius, you have
total control over how the radius property is accessed. If you have to change the implementation
of these methods, you need not change the client programs. This makes the class easy to maintain.
    Listing 8.10 gives a client program that uses the Circle class to create a Circle object
and modifies the radius using the setRadius method.

LISTING 8.10 TestCircle3.java
 1 public class TestCircle3 {
 2   /** Main method */
 3   public static void main(String[] args) {
 4     // Create a Circle with radius 5.0
 5     Circle3 myCircle = new Circle3(5.0);
 6     System.out.println("The area of the circle of radius "
 7       + myCircle.getRadius() + " is " + myCircle.getArea() );                                        invoke public method
 8
 9     // Increase myCircle's radius by 10%
10     myCircle.setRadius(myCircle.getRadius() * 1.1);
11     System.out.println("The area of the circle of radius "
12       + myCircle.getRadius() + " is " + myCircle.getArea() );                                        invoke public method
13
14     System.out.println("The number of objects created is "
15       + Circle3.getNumberOfObjects() );                                                              invoke public method
16   }
17 }

The data field radius is declared private. Private data can be accessed only within their
defining class. You cannot use myCircle.radius in the client program. A compile error
would occur if you attempted to access private data from a client.
   Since numberOfObjects is private, it cannot be modified. This prevents tampering. For
example, the user cannot set numberOfObjects to 100. The only way to make it 100 is to
create 100 objects of the Circle class.
   Suppose you combined TestCircle and Circle into one class by moving the main
method in TestCircle into Circle. Could you use myCircle.radius in the main
method? See Review Question 8.15 for the answer.
286 Chapter 8 Objects and Classes

                        Design Guide
                         To prevent data from being tampered with and to make the class easy to maintain, declare data
                         fields private.


                   8.10 Passing Objects to Methods
                   You can pass objects to methods. Like passing an array, passing an object is actually passing
                   the reference of the object. The following code passes the myCircle object as an argument to
                   the printCircle method:

                       1 public class Test {
                       2   public static void main(String[] args) {
                       3     // Circle3 is defined in Listing 8.9
                       4     Circle3 myCircle = new Circle3(5.0);
pass an object         5     printCircle(myCircle);
                       6   }
                       7
                       8   public static void printCircle(Circle3 c) {
                       9     System.out.println("The area of the circle of radius "
                      10       + c.getRadius() + " is " + c.getArea());
                      11   }
                      12 }

pass-by-value      Java uses exactly one mode of passing arguments: pass-by-value. In the preceding code, the
                   value of myCircle is passed to the printCircle method. This value is a reference to a
                   Circle object.
                      Let us demonstrate the difference between passing a primitive type value and passing a ref-
                   erence value with the program in Listing 8.11:

                   LISTING 8.11 TestPassObject.java
                    1 public class TestPassObject {
                    2   /** Main method */
                    3   public static void main(String[] args) {
                    4     // Create a Circle object with radius 1
                    5     Circle3 myCircle = new Circle3(1);
                    6
                    7     // Print areas for radius 1, 2, 3, 4, and 5.
                    8     int n = 5;
pass object         9     printAreas(myCircle, n);
                   10
                   11     // See myCircle.radius and times
                   12     System.out.println("\n" + "Radius is " + myCircle.getRadius());
                   13     System.out.println("n is " + n);
                   14   }
                   15
                   16   /** Print a table of areas for radius */
object parameter   17   public static void printAreas(Circle3 c, int times) {
                   18     System.out.println("Radius \t\tArea");
                   19     while (times >= 1) {
                   20       System.out.println(c.getRadius() + "\t\t" + c.getArea());
                   21       c.setRadius(c.getRadius() + 1);
                   22       times--;
                   23     }
                   24   }
                   25 }
                                                                                        8.11 Array of Objects 287

 Radius                                       Area
  1.0                                          3.141592653589793
  2.0                                         12.566370614359172
  3.0                                         29.274333882308138
  4.0                                         50.26548245743669
  5.0                                         79.53981633974483
 Radius is 6.0
 n is 5



The Circle3 class is defined in Listing 8.9. The program passes a Circle3 object
myCircle and an integer value from n to invoke printAreas(myCircle, n) (line 9),
which prints a table of areas for radii 1, 2, 3, 4, 5, as shown in the sample output.
   Figure 8.17 shows the call stack for executing the methods in the program. Note that the
objects are stored in a heap.


           Stack                       Pass-by-value (here                 Heap
                                       the value is 5)
           Space required for the
           printArea method                         Pass-by-value
                int times: 5                        (here the value is
            Circle c: reference                     the reference for
                                                    the object)
           Space required for the
           main method
            int n: 5                                                      A Circle
            myCircle: reference                                             object


FIGURE 8.17 The value of n is passed to times, and the reference of myCircle is passed to
c in the printAreas method.


   When passing an argument of a primitive data type, the value of the argument is passed. In
this case, the value of n (5) is passed to times. Inside the printAreas method, the content
of times is changed; this does not affect the content of n.
   When passing an argument of a reference type, the reference of the object is passed. In this
case, c contains a reference for the object that is also referenced via myCircle. Therefore,
changing the properties of the object through c inside the printAreas method has the same
effect as doing so outside the method through the variable myCircle. Pass-by-value on refer-
ences can be best described semantically as pass-by-sharing; i.e., the object referenced in the   pass-by-sharing
method is the same as the object being passed.


8.11 Array of Objects
In Chapter 6, “Single-Dimensional Arrays,” arrays of primitive type elements were created.
You can also create arrays of objects. For example, the following statement declares and cre-
ates an array of ten Circle objects:
   Circle[] circleArray = new Circle[10];

To initialize the circleArray, you can use a for loop like this one:
   for (int i = 0; i < circleArray.length; i++) {
     circleArray[i] = new Circle();
   }
288 Chapter 8 Objects and Classes
                          An array of objects is actually an array of reference variables. So, invoking circleArray-
                          [1].getArea() involves two levels of referencing, as shown in Figure 8.18. circleArray
                          references the entire array. circleArray[1] references a Circle object.

                                  circleArray reference                    circleArray[0]                 Circle object 0
                                                                           circleArray[1]

                                                                                    …                     Circle object 1


                                                                           circleArray[9]                 Circle object 9

                          FIGURE 8.18   In an array of objects, an element of the array contains a reference to an object.


                               Note
                               When an array of objects is created using the new operator, each element in the array is a refer-
                               ence variable with a default value of null.

                          Listing 8.12 gives an example that demonstrates how to use an array of objects. The program
                          summarizes the areas of an array of circles. The program creates circleArray, an array
                          composed of five Circle objects; it then initializes circle radii with random values and dis-
                          plays the total area of the circles in the array.

                          LISTING 8.12 TotalArea.java
                           1 public class TotalArea {
                           2   /** Main method */
                           3   public static void main(String[] args) {
                           4     // Declare circleArray
array of objects           5     Circle3[] circleArray;
                           6
                           7     // Create circleArray
                           8     circleArray = createCircleArray() ;
                           9
                          10     // Print circleArray and total areas of the circles
                          11     printCircleArray(circleArray);
                          12   }
                          13
                          14   /** Create an array of Circle objects */
return array of objects   15   public static Circle3[] createCircleArray() {
                          16     Circle3[] circleArray = new Circle3[5];
                          17
                          18     for (int i = 0; i < circleArray.length; i++) {
                          19       circleArray[i] = new Circle3(Math.random() * 100);
                          20     }
                          21
                          22     // Return Circle array
                          23     return circleArray;
                          24   }
                          25
                          26   /** Print an array of circles and their total area */
pass array of objects     27   public static void printCircleArray(Circle3[] circleArray) {
                          28     System.out.printf("%-30s%-15s\n", "Radius", "Area");
                          29     for (int i = 0; i < circleArray.length; i++) {
                          30       System.out.printf("%-30f%-15f\n", circleArray[i].getRadius(),
                          31         circleArray[i].getArea());
                          32     }
                          33
                          34     System.out.println("—————————————————————————————————————————");
                                                                                                   Key Terms 289
35
36         // Compute and display the result
37         System.out.printf("%-30s%-15f\n", "The total area of circles is",
38           sum(circleArray) );
39     }
40
41     /** Add circle areas */
42     public static double sum(Circle3[] circleArray) {                                     pass array of objects
43       // Initialize sum
44       double sum = 0;
45
46         // Add areas to sum
47         for (int i = 0; i < circleArray.length; i++)
48           sum += circleArray[i].getArea();
49
50         return sum;
51     }
52 }


  Radius                                 Area
 70.577708                           15648.941866
 44.152266                            6124.291736
 24.867853                            1942.792644
  5.680718                             101.380949
 36.734246                            4239.280350
 ————————————————————————————————————————————————————-
 The total area of circles is        28056.687544


The program invokes createCircleArray() (line 8) to create an array of five Circle
objects. Several Circle classes were introduced in this chapter. This example uses the
Circle class introduced in §8.9, “Data Field Encapsulation.”
   The circle radii are randomly generated using the Math.random() method (line 19). The
createCircleArray method returns an array of Circle objects (line 23). The array is
passed to the printCircleArray method, which displays the radius and area of each circle
and the total area of the circles.
   The sum of the circle areas is computed using the sum method (line 38), which takes the
array of Circle objects as the argument and returns a double value for the total area.

  KEY TERMS
  accessor method (getter) 284                   mutator method (setter) 285
  action 264                                     null 272
  attribute 264                                  no-arg constructor 266
  behavior 264                                   object-oriented programming (OOP) 264
  class 265                                      Unified Modeling Language
  client 267                                        (UML) 265
  constructor 268                                package-private (or package-access) 282
  data field 268                                 private 283
  data-field encapsulation 283                   property 264
  default constructor 270                        public 282
  dot operator (.) 271                           reference variable 271
  instance 271                                   reference type 271
  instance method 271                            state 264
  instance variable 271                          static method 278
  instantiation 264                              static variable 278
290 Chapter 8 Objects and Classes

                      CHAPTER SUMMARY
                       1. A class is a template for objects. It defines the properties of objects and provides con-
                            structors for creating objects and methods for manipulating them.
                       2. A class is also a data type. You can use it to declare object reference variables. An
                            object reference variable that appears to hold an object actually contains a reference to
                            that object. Strictly speaking, an object reference variable and an object are different,
                            but most of the time the distinction can be ignored.
                       3. An object is an instance of a class. You use the new operator to create an object,
                            and the dot (.) operator to access members of that object through its reference
                            variable.
                       4. An instance variable or method belongs to an instance of a class. Its use is associ-
                            ated with individual instances. A static variable is a variable shared by all instances
                            of the same class. A static method is a method that can be invoked without using
                            instances.
                       5. Every instance of a class can access the class’s static variables and methods. For clarity,
                            however, it is better to invoke static variables and methods using ClassName.variable
                            and ClassName.method.
                       6. Modifiers specify how the class, method, and data are accessed. A      public class,
                            method, or data is accessible to all clients. A private method or data is accessible
                            only inside the class.
                       7. You can provide a get method or a set method to enable clients to see or modify the
                            data. Colloquially, a get method is referred to as a getter (or accessor), and a set
                            method as a setter (or mutator).
                       8. A get method has the signature public returnType   getPropertyName(). If the
                            returnType is boolean, the get method should be defined as public boolean
                            isPropertyName(). A set method has the signature public void setProper-
                            tyName(dataType propertyValue).

                       9. All parameters are passed to methods using pass-by-value. For a parameter of a prim-
                            itive type, the actual value is passed; for a parameter of a reference type, the reference
                            for the object is passed.
                     10. A Java array is an object that can contain primitive type values or object type values.
                            When an array of objects is created, its elements are assigned the default value of
                            null.

                      REVIEW QUESTIONS
                      Sections 8.2–8.5
                      8.1      Describe the relationship between an object and its defining class. How do you
                               define a class? How do you declare an object reference variable? How do you cre-
                               ate an object? How do you declare and create an object in one statement?
                      8.2      What are the differences between constructors and methods?
                      8.3      Is an array an object or a primitive type value? Can an array contain elements of an
                               object type as well as a primitive type? Describe the default value for the elements
                               of an array.
                      8.4      What is wrong with the following program?
                                                                                         Review Questions 291

1 public class ShowErrors {                              1 public class ShowErrors {
2   public static void main(String[] args) {             2   public static void main(String[] args) {
3      ShowErrors t = new ShowErrors(5);                 3     ShowErrors t = new ShowErrors();
4   }                                                    4     t.x();
                                                         5   }
5 }
                                                         6 }

                     (a)                                                          (b)



1 public class ShowErrors {                              1   public class ShowErrors {
2   public void method1() {                              2     public static void main(String[] args) {
3     Circle c;                                          3        C c = new C(5.0);
4     System.out.println("What is radius "               4           System.out.println(c.value);
5       + c.getRadius());                                5       }
6     c = new Circle();                                  6   }
7   }                                                    7
8 }                                                      8   class C {
                                                         9     int value = 2;
                                                        10   }

                    (c)                                                            (d)


8.5    What is wrong in the following code?

        1   class Test {
        2     public static void main(String[] args) {
        3       A a = new A();
        4       a.print();
        5     }
        6   }
        7
        8   class A {
        9     String s;
       10
       11       A(String s) {
       12         this.s = s;
       13       }
       14
       15       public void print() {
       16         System.out.print(s);
       17       }
       18   }

8.6    What is the printout of the following code?

       public class Foo {
         private boolean x;

           public static void main(String[] args) {
             Foo foo = new Foo();
             System.out.println(foo.x);
           }
       }


Section 8.6
8.7    How do you create a Date for the current time? How do you display the current
       time?
8.8    How do you create a JFrame, set a title in a frame, and display a frame?
292 Chapter 8 Objects and Classes

                      8.9     Which packages contain the classes Date, JFrame, JOptionPane, System, and
                              Math?

                      Section 8.7
                      8.10 Suppose that the class Foo is defined in (a). Let f be an instance of Foo. Which of
                              the statements in (b) are correct?

                              public class Foo {                    System.out.println(f.i);
                                int i;                              System.out.println(f.s);
                                static String s;                    f.imethod();
                                                                    f.smethod();
                                  void imethod() {
                                                                    System.out.println(Foo.i);
                                  }
                                                                    System.out.println(Foo.s);
                                  static void smethod() {           Foo.imethod();
                                  }                                 Foo.smethod();
                              }

                                              (a)                                  (b)

                      8.11 Add the static keyword in the place of ? if appropriate.
                              public class Test {
                                private int count;
                                  public ? void main(String[] args) {
                                    ...
                                  }
                                  public ? int getCount() {
                                    return count;
                                  }
                                  public ? int factorial(int n) {
                                    int result = 1;
                                    for (int i = 1; i <= n; i++)
                                      result *= i;
                                      return result;
                                  }
                              }

                      8.12 Can you invoke an instance method or reference an instance variable from a static
                              method? Can you invoke a static method or reference a static variable from an
                              instance method? What is wrong in the following code?

                               1 public class Foo {
                               2   public static void main(String[] args) {
                               3     method1();
                               4   }
                               5
                               6   public void method1() {
                               7     method2();
                               8   }
                               9
                              10   public static void method2() {
                              11     System.out.println("What is radius " + c.getRadius());
                              12   }
                              13
                              14   Circle c = new Circle();
                              15 }
                                                                                              Review Questions 293
    Sections 8.8–8.9
    8.13 What is an accessor method? What is a mutator method? What are the naming
             conventions for accessor methods and mutator methods?
    8.14     What are the benefits of data-field encapsulation?
    8.15     In the following code, radius is private in the Circle class, and myCircle is an
             object of the Circle class. Does the highlighted code below cause any problems?
             Explain why.

             public class Circle {
               private double radius = 1.0;

                 /** Find the area of this circle */
                 public double getArea() {
                   return radius * radius * Math.PI;
                 }

                 public static void main(String[] args) {
                   Circle myCircle = new Circle();
                   System.out.println("Radius is " + myCircle.radius );
                 }
             }


    Section 8.10
    8.16 Describe the difference between passing a parameter of a primitive type and pass-
             ing a parameter of a reference type. Show the output of the following program:

public class Test {                                                      public class Count {
  public static void main(String[] args) {                                 public int count;
    Count myCount = new Count();
                                                                             public Count(int c) {
    int times = 0;
                                                                               count = c;
        for (int i = 0; i < 100; i++)                                        }
           increment(myCount, times);
                                                                             public Count() {
        System.out.println("count is " + myCount.count);                       count = 1;
        System.out.println("times is " + times);                             }
    }                                                                    }

    public static void increment(Count c, int times) {
        c.count++;
        times++;
    }
}

    8.17 Show the output of the following program:
             public class Test {
               public static void main(String[] args) {
                 Circle circle1 = new Circle(1);
                 Circle circle2 = new Circle(2);
                     swap1(circle1, circle2);
                     System.out.println("After swap1: circle1 = " +
                       circle1.radius + " circle2 = " + circle2.radius);
                     swap2(circle1, circle2);
                     System.out.println("After swap2: circle1 = " +
                       circle1.radius + " circle2 = " + circle2.radius);
                 }
294 Chapter 8 Objects and Classes
                                           public static void swap1(Circle x, Circle y) {
                                             Circle temp = x;
                                             x = y;
                                             y = temp;
                                           }
                                           public static void swap2(Circle x, Circle y) {
                                             double temp = x.radius;
                                             x.radius = y.radius;
                                             y.radius = temp;
                                           }
                                       }
                                       class Circle {
                                         double radius;
                                           Circle(double newRadius) {
                                             radius = newRadius;
                                           }
                                       }

                           8.18 Show the printout of the following code:

     public class Test {                                      public class Test {
       public static void main(String[] args) {                 public static void main(String[] args) {
         int[] a = {1, 2};                                        int[] a = {1, 2};
         swap(a[0], a[1]);                                            swap(a);
         System.out.println("a[0] = " + a[0]                          System.out.println("a[0] = " + a[0]
           + " a[1] = " + a[1]);                                        + " a[1] = " + a[1]);
         }                                                        }

         public static void swap(int n1, int n2) {                public static void swap(int[] a) {
           int temp = n1;                                           int temp = a[0];
             n1 = n2;                                               a[0] = a[1];
             n2 = temp;                                             a[1] = temp;
         }                                                        }
     }                                                        }

                           (a)                                                      (b)

     public class Test {                                      public class Test {
       public static void main(String[] args) {                 public static void main(String[] args) {
         T t = new T();                                           T t1 = new T();
             swap(t);                                             T t2 = new T();
             System.out.println("e1 = " + t.e1                    System.out.println("t1's i = " +
               + " e2 = " + t.e2);                                  t1.i + " and j = " + t1.j);
         }                                                        System.out.println("t2's i = " +
                                                                    t2.i + " and j = " + t2.j);
         public static void swap(T t) {                           }
             int temp = t.e1;                                 }
             t.e1 = t.e2;
             t.e2 = temp;                                     class T {
         }                                                      static int i = 0;
     }                                                          int j = 0;

     class T {                                                    T() {
       int e1 = 1;                                                  i++;
       int e2 = 2;                                                  j = 1;
     }                                                            }
                                                              }

                                 (c)                                                  (d)
                                                                                                  Programming Exercises 295

    8.19 What is the output of the following program?

import java.util.Date;                                               import java.util.Date;

public class Test {                                                  public class Test {
  public static void main(String[] args) {                             public static void main(String[] args) {
    Date date = null;                                                    Date date = new Date(1234567);
        m1(date);                                                            m1(date);
        System.out.println(date);                                            System.out.println(date.getTime());
    }                                                                    }

    public static void m1(Date date) {                                   public static void m1(Date date) {
      date = new Date();                                                   date = new Date(7654321);
    }                                                                    }
}                                                                    }

                               (a)                                                               (b)

import java.util.Date;                                               import java.util.Date;

public class Test {                                                  public class Test {
  public static void main(String[] args) {                             public static void main(String[] args) {
    Date date = new Date(1234567);                                       Date date = new Date(1234567);
        m1(date);                                                            m1(date);
        System.out.println(date.getTime());                                  System.out.println(date.getTime());
    }                                                                    }

    public static void m1(Date date) {                                   public static void m1(Date date) {
      date.setTime(7654321);                                               date = null;
    }                                                                    }
}                                                                    }

                               (c)                                                               (d)


    Section 8.11
    8.20 What is wrong in the following code?
              1 public class Test {
              2   public static void main(String[] args) {
              3     java.util.Date[] dates = new java.util.Date[10];
              4     System.out.println(dates[0]);
              5     System.out.println(dates[0].toString());
              6   }
              7 }


    PROGRAMMING EXERCISES

          Pedagogical Note
          The exercises in Chapters 8–14 achieve three objectives:                                      three objectives

          ■ Design classes and draw UML class diagrams;
          ■ Implement classes from the UML;
          ■ Use classes to develop applications.
          Solutions for the UML diagrams for the even-numbered exercises can be downloaded from the
          Student Website and all others can be downloaded from the Instructor Website.
296 Chapter 8 Objects and Classes
                      Sections 8.2–8.5
                      8.1     (The Rectangle class) Following the example of the Circle class in §8.2,
                              design a class named Rectangle to represent a rectangle. The class contains:

                             ■   Two double data fields named width and height that specify the width
                                 and height of the rectangle. The default values are 1 for both width and
                                 height.
                             ■   A no-arg constructor that creates a default rectangle.
                             ■   A constructor that creates a rectangle with the specified width and height.
                             ■   A method named getArea() that returns the area of this rectangle.
                             ■   A method named getPerimeter() that returns the perimeter.
                              Draw the UML diagram for the class. Implement the class. Write a test program
                              that creates two Rectangle objects—one with width 4 and height 40 and the
                              other with width 3.5 and height 35.9. Display the width, height, area, and
                              perimeter of each rectangle in this order.
                      8.2     (The Stock class) Following the example of the Circle class in §8.2, design a
                              class named Stock that contains:

                             ■   A string data field named symbol for the stock’s symbol.
                             ■   A string data field named name for the stock’s name.
                             ■   A double data field named previousClosingPrice that stores the stock
                                 price for the previous day.
                             ■   A double data field named currentPrice that stores the stock price for the
                                 current time.
                             ■   A constructor that creates a stock with specified symbol and name.
                             ■   A method named getChangePercent() that returns the percentage changed
                                 from previousClosingPrice to currentPrice.
                              Draw the UML diagram for the class. Implement the class. Write a test program
                              that creates a Stock object with the stock symbol JAVA, the name Sun Microsys-
                              tems Inc, and the previous closing price of 4.5. Set a new current price to 4.35
                              and display the price-change percentage.

                      Section 8.6
                      8.3* (Using the Date class) Write a program that creates a Date object, sets its elapsed
                              time to 10000, 100000, 10000000, 10000000, 100000000, 1000000000,
                              10000000000, 100000000000, and displays the date and time using the
                              toString() method, respectively.
                      8.4*    (Using the Random class) Write a program that creates a Random object with seed
                              1000 and displays the first 50 random integers between 0 and 100 using the
                              nextInt(100) method.
                      8.5*    (Using the GregorianCalendar class) Java API has the GregorianCalendar
                              class in the java.util package that can be used to obtain the year, month, and day of
                              a date. The no-arg constructor constructs an instance for the current date, and the meth-
                              ods get(GregorianCalendar.YEAR), get(GregorianCalendar.MONTH), and
                              get(GregorianCalendar.DAY_OF_MONTH) return the year, month, and day.
                              Write a program to perform two tasks:
                             ■   Display the current year, month, and day.
                             ■   The GregorianCalendar class has the setTimeInMillis(long), which
                                 can be used to set a specified elapsed time since January 1, 1970. Set the value
                                 to 1234567898765L and display the year, month, and day.
                                                                                      Programming Exercises 297
Sections 8.7–8.9
8.6** (Displaying calendars) Rewrite the PrintCalendar class in Listing 5.12 to dis-
        play calendars in a message dialog box. Since the output is generated from several
        static methods in the class, you may define a static String variable output for
        storing the output and display it in a message dialog box.
8.7     (The Account class) Design a class named Account that contains:
        ■   A private int data field named id for the account (default 0).
        ■   A private double data field named balance for the account (default 0).
        ■   A private double data field named annualInterestRate that stores the cur-
            rent interest rate (default 0). Assume all accounts have the same interest rate.
        ■   A private Date data field named dateCreated that stores the date when the
            account was created.
        ■   A no-arg constructor that creates a default account.
        ■   A constructor that creates an account with the specified id and initial balance.
        ■   The accessor and mutator methods for id, balance, and annualInterestRate.
        ■   The accessor method for dateCreated.
        ■   A method named getMonthlyInterestRate() that returns the monthly
            interest rate.
        ■   A method named withdraw that withdraws a specified amount from the
            account.
        ■   A method named deposit that deposits a specified amount to the account.
        Draw the UML diagram for the class. Implement the class. Write a test program
        that creates an Account object with an account ID of 1122, a balance of $20,000,
        and an annual interest rate of 4.5%. Use the withdraw method to withdraw
        $2,500, use the deposit method to deposit $3,000, and print the balance, the
        monthly interest, and the date when this account was created.
8.8     (The Fan class) Design a class named Fan to represent a fan. The class contains:
        ■   Three constants named SLOW, MEDIUM, and FAST with values 1, 2, and 3 to
            denote the fan speed.                                                               Video Note
        ■   A private int data field named speed that specifies the speed of the fan            The Fan class
            (default SLOW).
        ■   A private boolean data field named on that specifies whether the fan is on
            (default false).
        ■   A private double data field named radius that specifies the radius of the fan
            (default 5).
        ■   A string data field named color that specifies the color of the fan (default
            blue).
        ■   The accessor and mutator methods for all four data fields.
        ■   A no-arg constructor that creates a default fan.
        ■   A method named toString() that returns a string description for the fan. If
            the fan is on, the method returns the fan speed, color, and radius in one com-
            bined string. If the fan is not on, the method returns fan color and radius along
            with the string “fan is off” in one combined string.
        Draw the UML diagram for the class. Implement the class. Write a test program
        that creates two Fan objects. Assign maximum speed, radius 10, color yellow,
        and turn it on to the first object. Assign medium speed, radius 5, color blue, and
        turn it off to the second object. Display the objects by invoking their toString
        method.
8.9**   (Geometry: n-sided regular polygon) In an n-sided regular polygon all sides
        have the same length and all angles have the same degree (i.e., the polygon is
298 Chapter 8 Objects and Classes
                              both equilateral and equiangular). Design a class named RegularPolygon that
                              contains:
                              ■   A private int data field named n that defines the number of sides in the poly-
                                  gon with default value 3.
                              ■   A private double data field named side that stores the length of the side with
                                  default value 1.
                              ■   A private double data field named x that defines the x-coordinate of the center
                                  of the polygon with default value 0.
                              ■   A private double data field named y that defines the y-coordinate of the center
                                  of the polygon with default value 0.
                              ■   A no-arg constructor that creates a regular polygon with default values.
                              ■   A constructor that creates a regular polygon with the specified number of sides
                                  and length of side, centered at (0, 0).
                              ■   A constructor that creates a regular polygon with the specified number of sides,
                                  length of side, and x-and y-coordinates.
                              ■   The accessor and mutator methods for all data fields.
                              ■   The method getPerimeter() that returns the perimeter of the polygon.
                              ■   The method getArea() that returns the area of the polygon. The formula for
                                  computing the area of a regular polygon is
                                                                         n * s2
                                                            Area =                .
                                                                               p
                                                                      4 * tan a b
                                                                               n
                              Draw the UML diagram for the class. Implement the class. Write a test program
                              that creates three RegularPolygon objects, created using the no-arg constructor,
                              using RegularPolygon(6, 4), and using RegularPolygon(10, 4, 5.6,
                              7.8). For each object, display its perimeter and area.
                      8.10*   (Algebra: quadratic equations) Design a class named QuadraticEquation for a
                              quadratic equation ax 2 + bx + x = 0. The class contains:
                              ■   Private data fields a, b, and c that represents three coefficients.
                              ■   A constructor for the arguments for a, b, and c.
                              ■   Three get methods for a, b, and c.
                              ■   A method named getDiscriminant() that returns the discriminant, which is
                                  b2 - 4ac.
                              ■   The methods named getRoot1() and getRoot2() for returning two roots of
                                  the equation

                                                 -b + 2b2 - 4ac          -b - 2b2 - 4ac
                                          r1 =                  and r2 =
                                                      2a                      2a

                              These methods are useful only if the discriminant is nonnegative. Let these meth-
                              ods return 0 if the discriminant is negative.
                              Draw the UML diagram for the class. Implement the class. Write a test program
                              that prompts the user to enter values for a, b, and c and displays the result based on
                              the discriminant. If the discriminant is positive, display the two roots. If the dis-
                              criminant is 0, display the one root. Otherwise, display “The equation has no roots.”
                              See Exercise 3.1 for sample runs.
                                                                                   Programming Exercises 299

8.11* (Algebra: 2 * 2 linear equations) Design a class named LinearEquation for a
        2 * 2 system of linear equations:

                      ax + by = e              ed - bf     af - ec
                                         x =           y =
                      cx + dy = f              ad - bc     ad - bc

        The class contains:
        ■   Private data fields a, b, c, d, e, and f.
        ■   A constructor with the arguments for a, b, c, d, e, and f.
        ■   Six get methods for a, b, c, d, e, and f.
        ■   A method named isSolvable() that returns true if ad - bc is not 0.
        ■   Methods getX() and getY() that return the solution for the equation.
       Draw the UML diagram for the class. Implement the class. Write a test program
       that prompts the user to enter a, b, c, d, e, and f and displays the result. If
       ad - bc is 0, report that “The equation has no solution.” See Exercise 3.3 for
       sample runs.
8.12** (Geometry: intersection) Suppose two line segments intersect. The two endpoints
       for the first line segment are (x1, y1) and (x2, y2) and for the second line seg-
       ment are (x3, y3) and (x4, y5). Write a program that prompts the user to enter
       these four endpoints and displays the intersecting point.
       (Hint: Use the LinearEquation class from the preceding exercise.)

        Enter the endpoints of the first line segment: 2.0 2.0 0 0
        Enter the endpoints of the second line segment: 0 2.0 2.0 0
        The intersecting point is: (1.0, 1.0)


8.13** (The Location class) Design a class named Location for locating a maximal
        value and its location in a two-dimensional array. The class contains public data
        fields row, column, and maxValue that store the maximal value and its indices
        in a two dimensional array with row and column as int type and maxValue as
        double type.
        Write the following method that returns the location of the largest element in a
        two-dimensional array.

        public static Location locateLargest(double[][] a)

        The return value is an instance of Location. Write a test program that prompts
        the user to enter a two-dimensional array and displays the location of the largest
        element in the array. Here is a sample run:

        Enter the number of rows and columns of the array: 3 4
        Enter the array:
        23.5 35 2 10
        4.5 3 45 3.5
        35 44 5.5 9.6
        The location of the largest element is 45 at (1, 2)
This page intentionally left blank
                                                          CHAPTER 9
STRINGS AND TEXT I/O
Objectives
■   To use the String class to process fixed strings (§9.2).
■   To use the Character class to process a single character (§9.3).
■   To use the StringBuilder/StringBuffer class to process flexible strings (§9.4).
■   To distinguish among the String, StringBuilder, and StringBuffer classes
    (§9.2–9.4).
■   To learn how to pass arguments to the main method from
    the command line (§9.5).
■   To discover file properties and to delete and rename files
    using the File class (§9.6).
■   To write data to a file using the PrintWriter class (§9.7.1).
■   To read data from a file using the Scanner class (§9.7.2).
■   (GUI) To open files using a dialog box (§9.8).
302 Chapter 9 Strings and Text I/O

                                  9.1 Introduction
problem                           Often you encounter problems that involve string processing and file input and output. Sup-
                                  pose you need to write a program that replaces all occurrences of a word in a file with a new
                                  word. How do you accomplish this? This chapter introduces strings and text files, which will
                                  enable you to solve problems of this type. (Since no new concepts are introduced here,
                                  instructors may assign this chapter for students to study on their own.)


                                  9.2 The String Class
                                  A string is a sequence of characters. In many languages, strings are treated as an array of char-