INTRODUCTION TO
JAVA
PROGRAMMING
TM
This page intentionally left blank
INTRODUCTION TO
JAVA
PROGRAMMING
BRIEF VERSION
Eighth Edition
Y. Daniel Liang
Armstrong Atlantic State University
TM
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
Prentice Hall
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 Dataon file.
10 9 8 7 6 5 4 3 2 1
ISBN-13: 978-0-13-213079-0
ISBN-10: 0-13-213079-3
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
This page intentionally left blank
PREFACE
vii
This book is a brief version of Introduction to Java Programming, Comprehensive Version,
8E. This version is designed for an introductory programming course, commonly known as
CS1. This version contains the first twenty chapters in the comprehensive version.
This book uses the fundamentals-first approach and teaches programming concepts and
techniques in a problem-driven way.
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 funda-
mental concepts and techniques of loops, methods, and arrays are the foundation for pro-
gramming. Building the foundation prepares students to learn object-oriented programming,
GUI, database, and Web programming.
Problem-driven means focused on problem-solving rather than syntax. We make introduc-
tory programming interesting by using interesting problems. The central thread of this book
is on solving problems. Appropriate syntax and library are introduced to support the writing
of a program for solving the problems. To support teaching programming in a problem-
driven way, the book provides a wide variety of problems at various levels of difficulty to
motivate students. In order to appeal to students in all majors, the problems cover many appli-
cation areas in math, science, business, financials, gaming, animation, and multimedia.
What’s New in This Edition?
This edition substantially improves Introduction to Java Programming, Seventh Edition. The
major improvements are as follows:
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-
est in programming, one-fifth of the problems are new.
In the previous edition, console input was covered at the end of Chapter 2. The new edi-
tion introduces console input early in Chapter 2 so that students can write interactive pro-
grams early.
The hand trace box is added for many programs in early chapters to help noive students
to read and trace programs.
Single-dimensional arrays and multidimensional arrays are covered in two chapters to
give instructors the flexibility to cover multidimensional arrays later.
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 exam-
ples. So basic GUI now precedes the introduction of abstract classes and interfaces. The
instructor, however, can still choose to cover abstract classes and interfaces before GUI.
brief version
comprehensive version
fundamentals-first
problem-driven
complete revision
new problems
early console input
hand trace box
multidimensional arrays
Sudoku problem simplified
basic GUI earlier
viii Preface
Exception handling is covered before abstract classes and interfaces. 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
topics can be covered in appropriate context.
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
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
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-
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 establish-
es 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 solv-
ing and programming concepts. The book uses many small, simple, and stimulating exam-
ples 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 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 programming course assessment and management system. Students can
submit programs/quizzes online. The system automatically grades the programs/quizzes
and gives students instant feedback.
Notes, Tips, and Cautions are inserted throughout the text to offer valuable advice and
insight on important aspects of program development.
exception handling earlier
design guidelines
learn from mistakes
programmatic solution
object-oriented programming
Java API
Preface ix
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,
and recursion to be covered earlier or later. The diagram shows the chapter dependencies.
Chapter 1 Introduction to
Computers, Programs, and
Java
Chapter 2 Elementary
Programming
Chapter 4 Loops
Chapter 5 Methods
Chapter 7 Multidimensional
Arrays
Chapter 20 Recursion
Part I: Fundamentals of
Programming
Chapter 3 Selections
Chapter 8 Objects and Classes
Chapter 19 Binary I/O
Chapter 9 Strings and Text I/O
Chapter 10 Thinking in Objects
Chapter 11 Inheritance and
Polymorphism
Chapter 13 Exception
Handling
Chapter 14 Abstract Classes
and Interfaces
Chapter 6 Single-Dimensional
Arrays
Part II: Object-Oriented
Programming
Chapter 12 GUI Basics
Chapter 15 Graphics
Chapter 16 Event-Driven
Programming
Chapter 17 Creating Graphical
User Interfaces
Chapter 18 Applets and
Multimedia
Part III: GUI Programming
Organization of the Book
The chapters in the brief version can be grouped into three parts that, taken together, form a
solid introduction to Java programming. Because knowledge is cumulative, the early chapters
provide the conceptual basis for understanding programming and guide students through
x Preface
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, 20)
The first part of the book is a stepping stone, preparing you to embark on the journey of learn-
ing Java. You will begin to know Java (Chapter 1), and will learn fundamental programming
techniques with primitive data types, variables, constants, 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 solving
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 III: GUI Programming (Chapters 12, 15–18)
This part introduces elementary Java GUI programming in Chapters 12 and 15–18. Major
topics include GUI basics (Chapter 12), drawing shapes (Chapter 15), event-driven program-
ming (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 com-
ponents to develop applications and applets from these elementary GUI chapters.
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
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:
Automatic Grading System: It can automatically grade exercises from the text or created
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.
IDE tutorials
Preface xi
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 submit 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 their own 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 Notesare 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
Source code for book examples
Interactive self-test (organized by chapter sections)
LiveLab
Resource links
Errata
xii Preface
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 addition-
al 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
A Glossary
B Installing and Configuring JDK
C Compiling and Running Java from the
Command Window
D Java Coding Style Guidelines
E Creating Desktop Shortcuts for Java
Applications on Windows
F Using Packages to Organize the Classes
in the Text
Part II IDE Supplements
A TextPad Tutorial
B NetBeans Tutorial | One Page Startup
Instruction
C Learning Java Effectively with
NetBeans
D Eclipse Tutorial | One Page Startup
Instruction
E Learning Java Effectively with Eclipse
Part III Java Supplements
A Java Characteristics
B Discussion on Operator and Operand
Evaluations
C The & and | Operators
D Bitwise Operations
E Statement Labels with break and continue
F Enumerated Types
G Packages
H Regular Expressions
I Formatted Strings
J The Methods in the Object Class
K Hiding Data Fields and Static Methods
L Initialization Blocks
M Extended Discussions on Overriding
Methods
N Design Patterns
O Text I/O Prior to JDK 1.5 (Reader and
Writer Classes)
P Assertions
Q Packaging and Deploying Java Projects
R Java Web Start
S GridBagLayout | OverlayLayout |
SpringLayout
T Networking Using Datagram Protocol
U Creating Internal Frames
V Pluggable Look and Feel
W UML Graphical Notations
X Testing Classes Using JUnit
Y JNI
Z The StringTokenizer Class
Part IV Database Supplements
A SQL Statements for Creating and
Initializing Tables Used in the Book
B MySQL Tutorial
C Oracle Tutorial
D Microsoft Access Tutorial
E Introduction to Database Systems
F Relational Database Concept
G Database Design
H SQL Basics
I Advanced SQL
Part V Web Programming Supplements
A HTML and XHTML Tutorial
B CSS Tutorial
C XML
D Java and XML
E Tomcat Tutorial
F More Examples on JSF and Visual Web
Development
Preface xiii
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
Representative.
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
Technology), Yang Ang (University of Wollongong, Australia), Kevin Bierre (Rochester
Institute of Technology), David Champion (DeVry Institute), James Chegwidden (Tarrant
County College), 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 Technology), 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 Institute of Technology), Roger Kraft (Purdue University at
Calumet), Hong Lin (DeVry Institute), Dan Lipsa (Armstrong Atlantic State University),
James Madison (Rensselaer Polytechnic 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), Maureen 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
xiv Preface
University), Richard Povinelli (Marquette University), Roger Priebe (University of Texas at
Austin), Mary Ann Pumphrey (De Anza Junior College), Pat Roth (Southern 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 University), 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 Disanno, Irwin Zucker,
and their colleagues for organizing, producing, and promoting this project, 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,
and Java 1
2 Elementary Programming 23
3 Selections 71
4 Loops 115
5 Methods 155
6 Single-Dimensional Arrays 197
7 Multidimensional Arrays 235
8 Objects and Classes 263
9 Strings and Text I/O 301
10 Thinking in Objects 343
11 Inheritance and Polymorphism 373
12 GUI Basics 405
13 Exception Handling 431
14 Abstract Classes and Interfaces 457
15 Graphics 497
16 Event-Driven Programming 533
17 Creating Graphical User Interfaces 571
18 Applets and Multimedia 613
19 Binary I/O 649
20 Recursion 677
APPENDIXES
A Java Keywords 707
B The ASCII Character Set 710
C Operator Precedence Chart 712
D Java Modifiers 714
E Special Floating-Point Values 716
F Number Systems 717
INDEX 721
xv
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 StringType 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
xvi
Contents xvii
3.5 Problem: Guessing Birthdays 75
3.6 Two-Way if Statements 79
3.7 Nested if Statements 80
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 switchStatements 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 andcontinue 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 MathClass 172
5.11 Case Study: Generating Random Characters 175
5.12 Method Abstraction and Stepwise Refinement 176
xviii Contents
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
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
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 GuessDateClass 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 superKeyword 380
11.4 Overriding Methods 382
11.5 Overriding vs. Overloading 383
11.6 The ObjectClass and Its toString() Method 384
11.7 Polymorphism 384
11.8 Dynamic Binding 385
11.9 Casting Objects and the instanceofOperator 387
11.10 The Object’s equals()Method 389
11.11 The ArrayListClass 390
11.12 A Custom Stack Class 393
11.13 The protectedData 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
Contents xix
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
Chapter 14 Abstract Classes and Interfaces 457
14.1 Introduction 458
14.2 Abstract Classes 458
14.3 Example: Calendar andGregorianCalendar 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 BigIntegerand BigDecimal Classes 481
14.13 Case Study: The RationalClass 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
xx Contents
Contents xxi
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 StillClockClass 516
15.11 Displaying Images 520
15.12 Case Study: The ImageViewerClass 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 TimerClass 557
Chapter 17 Creating Graphical User Interfaces 571
17.1 Introduction 572
17.2 Buttons 572
17.3 Check Boxes 578
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 W indows 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 URLClass 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
APPENDIXES
Appendix A Java Keywords 707
Appendix B The ASCII Character Set 710
Appendix C Operator Precedence Chart 712
Appendix D Java Modifiers 714
Appendix E Special Floating-Point Values 716
Appendix F Number Systems 717
INDEX 721
xxii Contents
INTRODUCTION TO
JAVA
PROGRAMMING
TM
This page intentionally left blank
INTRODUCTION TO COMPUTERS,
P
ROGRAMS, AND JAVA
CHAPTER 1
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? 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 theInternet 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?
A computer is an electronic device that stores and processes data. It includes both hardware
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))
The components are connected through a subsystem called a bus that transfers data or
power between them.
1.2.1 Central Processing Unit
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 unitand an
arithmetic/logic unit. The control unit controls and coordinates the actions of the other
why Java?
hardware
software
bus
CPU
Memory
e.g., Disk, CD,
and Tape
e.g., Modem
and NIC
e.g., Keyboard,
Mouse
e.g., Monitor,
Printer
CPU
Bus
Storage
Devices
Communication
Devices
Input
Devices
Output
Devices
FIGURE1.1 A computer consists of CPU, memory, storage devices, input devices, output
devices, and communication devices.
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-
puter is usually stated in megahertz (MHz) (1 MHz is 1 million Hz). CPU speed has been
improved continuously. Intel’s Pentium 3 Processor runs at about 500 megahertz and Pentium
4 Processor at about 3 gigahertz (GHz) (1 GHz is 1000 MHz).
1.2.2 Memory
To store and process information, computers use offand on electrical states, referred to by
convention as 0and 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,
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.
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-
bytes (GB), and terabytes (TB). A kilobyte is about 1000 bytes, a megabyte is
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.
2
20
= 1048576,
2
10
= 1024,
speed
hertz
megahertz
gigahertz
bit
byte
01001010
01100001
01110110
01100001
00000011
Encoding for character ‘J’
Encoding for character ‘a’
Encoding for character ‘v’
Encoding for character ‘a’
Encoding for number 3
2000
2001
2002
2003
2004
Memory address Memory content
FIGURE 1.2 Memory stores data and program instructions.
RAM
megabyte
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
Drivesare devices for operating a medium, such as disks, CDs, and tapes.
Disks
Each computer has at least one hard drive. Hard disksare 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 stands for compact disk. There are two types of CD drives: CD-R and CD-RW. A CD-Ris
for read-only permanent storage; the user cannot modify its contents once they are recorded.
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
Tapesare 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 keyboardsand mice. The common output devices are monitors and printers.
The Keyboard
A computer keyboardresembles a typewriter keyboard with extra keys added for certain spe-
cial functions.
Function keysare located at the top of the keyboard and are numbered with prefix F. Their
use depends on the software.
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.
drive
hard disk
CD-R
CD-RW
function key
modifier key
1.3 Programs 5
The numeric keypad,located on the right-hand corner of the keyboard, is a separate set of
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.
Thescreen resolution specifies the number of pixels per square inch. Pixels (short for “pic-
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
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 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
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
network (LAN). The LAN is commonly used in universities and business and government
organizations. A typical NIC called 10BaseT can transfer data at 10 mbps (million bits per
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
Computerprograms, known as software, are instructions to the computer, telling it what to do.
Computers do not understand human languages, so you need to use computer languages in
computer programs. Programmingis the creation of a program that is executable by a com-
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
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 languageis a low-level programming language in which a mnemonic is used to
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
numeric keypad
screen resolution
dot pitch
modem
DSL
NIC
LAN
mbps
software
programming
machine language
assembly language
6 Chapter 1 Introduction to Computers, Programs, and Java
Assembly languages were developed to make programming easy. However, since the com-
puter cannot understand assembly language, a program called an assembleris used to convert
assembly-language programs into machine code, as shown in Figure 1.3.
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.
The high-level languagesare 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)
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.
Java
assembler
high-level language
Assembly Source File
..
ADDF3 R1, R2, R3
..
Machine-Code File
..
1101101010011010
..
Assembler
FIGURE1. 3 Assembler translates assembly-language instructions to machine code.
1.4 Operating Systems 7
A program written in a high-level language is called a source programor source code.
Since a computer cannot understand a source program, a program called a compileris used to
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.
1.4 Operating Systems
The operating system (OS) is the most important program that runs on a computer, which
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.
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.
source program
compiler
OS
Source File
Compiler
Linker
Machine-language
File
Executable
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.
User
Application Programs
Operating System
Hardware
FIGURE 1.5 The operating system is the software that controls and manages 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
multiprocessingto increase system performance.
Multiprogrammingallows 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 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, 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.
Such programs are called applets. Applets employ a modern graphical interface with buttons,
multiprogramming
multithreading
multiprocessing
applet
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.6shows
an applet running from a Web browser for playing a Tic Tac Toe game.
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.comis 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.6 A Java applet for playing TicTacToe is embedded in an HTML page.
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.
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.
The Java language specificationis 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.
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
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-
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-
Beans, Eclipse, and TextPad)—software that provides an integrated development environment
(IDE) for rapidly developing Java programs. Editing, compiling, building, debugging, and
Java language specification
API
Java SE, EE, and ME
JDK 1.6 = JDK 6
FIGURE1. 8 Java can be used to develop applications for hand-held and wireless devices,
such as a BlackBerry©(left) and a cell phone (right).
Java IDE
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
in Listing 1.1.
LISTING 1.1 Welcome.java
1 public class Welcome {
2 public static void main(String[] args) {
3 // Display message Welcome to Java! to the console
4 System.out.println("Welcome to Java!");
5 }
6 }
console
class
main method
display message
Welcome to Java!
Theline numbers are displayed for reference purposes but are not part of the program. So,
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
name is Welcome.
Line 2 defines the main method. In order to run a class, the class must contain a method
namedmain . The program is executed from the mainmethod.
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.
Reserved words,or keywords, have a specific meaning to the compiler and cannot be used
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-
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 blockthat groups the program’s components. In Java,
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
line numbers
class name
main method
statement terminator
reserved word
comment
Video Note
First Java program
block
12 Chapter 1 Introduction to Computers, Programs, and Java
blockthat 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.
Tip
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
Java source programs are case sensitive. It would be wrong, for example, to replace mainin the
program with
Main.
Note
Like any programming language, Java has its own syntax, and you need to write code that obeys
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
1 public class Welcome1 {
2 public static void main(String[] args) {
3 System.out.println("Programming is fun!");
4 System.out.println("Fundamentals First");
5 System.out.println("Problem Driven");
6 }
7 }
matching braces
syntax rules
class
main method
display message
Programming is fun!
Fundamentals First
Problem Driven
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Method block
Class block
Further, you can perform mathematical computations and display the result to the console.
Listing 1.3 gives an example of evaluating
10.5 + 2 * 3
45 - 3.5
.
case sensitive
1.8 Creating, Compiling, and Executing a Java Program 13
class
main method
compute expression
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
Result
Compile Source Code
e.g.,javac Welcome.java
Saved on the disk
Stored on the disk
If compilation errors
If runtime errors or incorrect result
Source code (developed by the programmer)
Bytecode (generated by the compiler for JVM
to read and interpret, not for you to understand)
Method Welcome()
0 aload_0
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to Java!">
5 invokevirtual #4 …
8 return
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Run Bytecode
e.g.,java Welcome
Source Code
Bytecode
“Welcome to Java” is printed on the console
Welcome to Java!
FIGURE 1.9 The Java program-development process consists of repeatedly creating/modifying source code, compiling,
and executing programs.
LISTING 1.3 ComputeExpression.java
1 public class ComputeExpression {
2 public static void main(String[] args) {
3 System.out.println((10.5 + 2 * 3) / (45 3.5));
4 }
5 }
14 Chapter 1 Introduction to Computers, Programs, and Java
You can use any text editoror 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 NotePadto create the Java source code
file, as shown in Figure 1.10.
Note
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:
javac Welcome.java
Note
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, “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 compilergenerates a bytecode file with a .class extension. So
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 bytecodeis 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.
editor
file name
compile
Supplement I.B
Supplement I.C
.class bytecode file
FIGURE1.1 0 You can create the Java source file using Windows NotePad.
J
a
v
a
V
i
r
t
u
a
l
M
a
c
h
i
n
e
Any
Computer
J
a
v
a
B
y
t
e
c
o
d
e
Welcome.java
(Java source
code file)
Welcome.class
(Java bytecode
executable file)
JVM
Java
Compiler
compiled
by
generates executed
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.
Video Note
Brief Eclipse Tutorial
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-
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
Figure 1.12 shows the javaccommand for compiling Welcome.java. The compiler gener-
ated the Welcome.class file. This file is executed using the javacommand.
Note
For simplicity and consistency, all source code and class filesare placed under c:\book unless
specified otherwise.
Caution
Do not use the extension .class in the command line when executing the program. Use java
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 NoClassDefFoundErrorwill occur. If you exe-
cute a class file that does not have a
main method or you mistype the mainmethod (e.g., by
typing
Maininstead of main), a NoSuchMethodError will occur.
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
loads them just before they are needed. After a class is loaded, the JVM uses a program called
bytecode verifierto check the validity of the bytecode and ensure that the bytecode does not vio-
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.
interpreting bytecode
run
c:\book
java ClassName
NoClassDefFoundError
NoSuchMethodError
class loader
bytecode verifier
Compile
Show files
Run
FIGURE 1.12 The output of Listing 1.1 displays the message “Welcome to Java!”
Video Note
Compile and run a Java program
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
packages, please see Supplement I.F, “Using Packagesto 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
showMessageDialogmethod 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.”
You can use the showMessageDialogmethod to display any text in a message dialog box,
as shown in Figure 1.13. The new program is given in Listing 1.4.
LISTING 1.4 WelcomeInMessageDialogBox.java
1 /* This application program displays Welcome to Java!
2 * in a message dialog box.
3 */
4
5
6 public class WelcomeInMessageDialogBox {
7 public static void main(String[] args) {
8 // Display Welcome to Java! in a message dialog box
9
10 }
11 }
This program uses a Java class JOptionPane(line 9). Java’s predefined classes are grouped
into packages. JOptionPaneis 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 JOptionPaneon line 9 with javax.swing.JOptionPane, you don’t need to
import it in line 4.
javax.swing.JOptionPaneis the full name for the JOptionPane class.
The showMessageDialog method is a staticmethod. 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 showMessageDialogmethod can
be invoked with two arguments, as shown below.
JOptionPane.showMessageDialog(null, "Welcome to Java!");
import javax.swing.JOptionPane;
using package
JOptionPane
showMessageDialog
block comment
import
main method
package
Title bar
Message
Click the OK button to
dismiss the dialog box
Title
FIGURE1.1 3 “Welcome to Java!” is displayed in a message box.
display message
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 showMessageDialogmethod. For the time being, you
need to know only two ways. One is to use a statement, as shown in the example:
JOptionPane.showMessageDialog(null, x);
wherex 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 yis 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.
two versions of
showMessageDialog
specific import
wildcard import
no performance difference
java.lang
implicitly imported
.class file 14
.java file 14
assembly language 5
bit 3
block 12
block comment 11
bus 2
byte 3
bytecode 14
bytecode verifier 15
cable modem 5
central processing unit (CPU) 2
class loader 15
comment 11
JOptionPane.showMessageDialog(null,
"Welcome to Java!",
"Display Message",
JOptionPane.INFORMATION_MESSAGE);
Note
There are two types of import statements: specific importand wildcard import. The specific
import specifies a single class in the import statement. For example, the following statement
imports
JOptionPanefrom package javax.swing.
import javax.swing.JOptionPane;
The wildcard import imports all the classes in a package. For example, the following statement
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 differencebetween a specific import and a wildcard
import declaration.
Note
Recall that you have used the Systemclass in the statement
System.out.println(”Welcome
to Java”);
in Listing 1.1. The Systemclass is not imported because it is in the java.lang
package. All the classes in the java.langpackage are implicitly imported in every Java program.
KEY TERMS
18 Chapter 1 Introduction to Computers, Programs, and Java
compiler 7
console 11
dot pitch 5
DSL (digital subscriber line) 5
hardware 2
high-level language 6
Integrated Development Environment
(IDE) 10
javacommand 15
javaccommand 15
Java Development Toolkit (JDK) 10
Java Virtual Machine (JVM) 14
keyword (or reserved word) 11
line comment 11
machine language 5
main method 11
memory 3
modem 5
network interface card (NIC) 5
operating system (OS) 7
pixel 5
program 5
programming 5
resolution 5
software 5
source code 7
source file 14
specific import 17
storage devices 4
statement 11
wildcard import 17
Note
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.
Supplement I.A
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 mainmethod 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
morningfollowed 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 NoSuchMethodErroroccurs when you run a program, what is the cause of
the error?
1.21 Why does the Systemclass 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 difficultyis rated easy (no star),
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
.
level of difficulty
22 Chapter 1 Introduction to Computers, Programs, and Java
1.6 (Summation of a series) Write a program that displays the result of
1.7 (Approximating ) can be computed using the following formula:
Write a program that displays the result of
Use1.0 instead of 1in your program.
1
9
-
1
11
+
1
13
b.
4 * a1 -
1
3
+
1
5
-
1
7
+
p = 4* a1 -
1
3
+
1
5
-
1
7
+
1
9
-
1
11
+
1
13
+
Á
b
pp
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9.
ELEMENTARY PROGRAMMING
CHAPTER 2
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 chartype (§2.13).
To compute monetary changes (§2.14).
To represent a string using the Stringtype (§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 JOptionPaneinput
dialog boxes (§2.18).
24 Chapter 2 Elementar y 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
Tobegin, 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 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 (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:
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 classis followed by the
class name. Assume that you have chosen ComputeAreaas 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 mainmethod 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-
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.
area = radius * radius * p
problem
algorithm
pseudocode
variable
2.2 Writing Simple Programs 25
Rather than using x and y as variable names, choose descriptive names: in this case,
radius for radius, and areafor area. To let the compiler know what radiusand area are,
specify their data types. Java provides simple data types for representing integers, floating-
point numbers (i.e., numbers with a decimal point), characters, and Boolean types. These
types are known as primitive data typesor fundamental types.
Declare radius andarea 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 andarea as variables. The reserved word doubleindicates
thatradius andarea 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 radiusin 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.
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
descriptive names
floating-point number
primitive data types
Compile
Run
FIGURE 2.1 The program displays the area of a circle.
26 Chapter 2 Elementar y Programming
13 System.out.println("The area for the circle of radius " +
14 radius + " is " + area);
15 }
16 }
Variables such as radiusand area correspond to memory locations. Every variable has a
name, a type, a size, and a value. Line 3 declares that radiuscan store a double value. The
value is not defined until you assign a value. Line 7 assigns 20into 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 areaand 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.
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),
the nonstring value is converted into a string and concatenated with the other string. So the
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
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
This example consists of three steps. It is a good approach to develop and test these steps
incrementallyby 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
Scannerclass for console input.
Java uses System.outto 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
declaring variable
assign value
concatenating strings
concatenating strings with
numbers
breaking a long string
incremental development and
testing
line# radius area
3 no value
4 no value
720
10 1256.636
Video Note
Obtain input
2.3 Reading Input from the Console 27
the keyboard. To perform console output, you simply use the printlnmethod to display a
primitive value or a string to the console. Console input is not directly supported in Java, but
you can use the Scannerclass 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 inputdeclares that input is a variable whose type is Scanner. The whole line
Scannerinput =new Scanner(System.in)creates a Scannerobject 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.
import class
create a
Scanner
read a double
TABLE 2.1 Methods for ScannerObjects
Method Description
nextByte()
reads an integer of the bytetype.
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 doubletype.
next()
reads a string that ends before a whitespace character.
nextLine()
reads a line of text (i.e., a string ending with the Enterkey 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 // Scanner is in the java.util package
2
3 public class ComputeAreaWithConsoleInput {
4 public static void main(String[] args) {
5 // Create a Scanner object
6
7
8 // Prompt the user to enter a radius
9 System.out.print("Enter a number for radius: ");
10 double radius = ;
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 }
input.nextDouble()
Scanner input = new Scanner(System.in);
import java.util.Scanner;
Enter a number for radius:
The area for the circle of radius 2.5 is 19.6349375
2.5
28 Chapter 2 Elementar y Programming
Enter a number for radius:
The area for the circle of radius 23.0 is 1661.90111
23
The Scanner class is in the java.utilpackage. It is imported in line 1. Line 6 creates a
Scannerobject.
The statement in line 9 displays a message to prompt the user for input.
System.out. ("Enter a number for radius: ");
The print method is identical to the printlnmethod 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
1 // Scanner is in the java.util package
2
3 public class ComputeAverage {
4 public static void main(String[] args) {
5 // Create a Scanner object
6
7
8 // Prompt the user to enter three numbers
9 System.out.print("Enter three numbers: ");
10 double number1 = ;
11 double number2 = ;
12 double number3 = ;
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 }
input.nextDouble()
input.nextDouble()
input.nextDouble()
Scanner input = new Scanner(System.in);
import java.util.Scanner;
print
printvs. println
import class
create a
Scanner
read a double
Enter three numbers:
The average of 1.0 2.0 3.0 is 2.0
1 2 3
Enter three numbers:
The average of 10.5 11.0 11.5 is 11.0
11.5
11
10.5
enter input in
one line
enter input in
multiple lines
2.5 Variables 29
The code for importing the Scannerclass (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 Enterkey, 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
(_), 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 andd+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.
Tip
Identifiers are for naming variables, constants, methods, classes, and packages. Descriptive iden-
tifiers make programs easy to read.
Tip
Do not name identifiers with the $character. By convention, the $ character should be used only
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
be used later in a program. They are called variables because their values can be changed. In
the program in Listing 2.2, radius andarea are variables of double-precision, floating-
point type. You can assign any numerical value to radius andarea, and the values of
radius andarea 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);
identifier naming rules
case sensitive
descriptive names
the
$character
why called variables?
30 Chapter 2 Elementar y 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 declarationtells
the compiler to allocate appropriate memory space for the variable based on its data type. The
syntax for declaring a variable is
datatype variableName;
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
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
radiusand interestRate.
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
After a variable is declared, you can assign a value to it by using an assignment statement. In
Java, the equal sign (=) is used as the assignment operator. The syntax for assignment state-
ments is as follows:
variable = expression;
declaring variables
naming variables
initializing variables
assignment statement
assignment operator
2.7 Named Constants 31
An expression represents a computation involving values, variables, and operators that,
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 xis 1 before the state-
ment is executed, then it becomes 2after 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 = xwould be wrong.
Note
In mathematics, x = 2 * x + 1denotes an equation. However, in Java, x = 2 * x + 1 is
an assignment statement that evaluates the expression
2 * x + 1and 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
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
xis int. You cannot assign a double value (1.0) to an intvariable 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-
gram, is a constant. If you use it frequently, you don’t want to keep typing 3.14159;
instead, you can declare a constant for Here is the syntax for declaring a constant:
final datatype CONSTANTNAME = VALUE;
p.
p
expression
assignment expression
constant
32 Chapter 2 Elementar y Programming
TABLE 2.2 Numeric Data Types
Name Range Storage Size
byte
to (127)2
7
–1-2
7
1-1282
8-bit signed
short
to (32767)2
15
–1-2
15
1-327682
16-bit signed
int
to (2147483647)2
31
–1-2
31
1-21474836482
32-bit signed
long
to
(i.e.,
to 9223372036854775807)
-9223372036854775808
2
63
–1-2
63
64-bit signed
float
Negative range: to
Positive range:1.4E–45 to 3.4028235E + 38
-1.4E–45-3.4028235E + 38 32-bit IEEE 754
double
Negative range: to
Positive range: to 1.7976931348623157E + 3084.9E - 324
-4.9E–324-1.7976931348623157E + 308
64-bit IEEE 754
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 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) {
// Declare a constant
// Assign a radius
double radius = 20;
// Compute area
double area = radius * radius * ;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
Caution
By convention, constants are named in uppercase: PI, not pior Pi.
Note
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.14to 3.14159 forPI), 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.2lists the six numeric data types, their ranges, and their storage sizes.
PI
final double PI = 3.14159;
p
naming constants
benefits of constants
2.8 Numeric Data Types and Operations 33
Note
IEEE 754is 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 754for the double type. The IEEE
754standard 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
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 anddouble. The double type is
twice as big as float. So, the doubleis known as double precision, float assingle precision.
Normally you should use the doubletype, 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
example, executing the following statement causes overflow, because the largest value that can
be stored in a variable of the
inttype 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
inttype is -2147483648. -2147483649 is too large in size to
be stored in an
intvariable.
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.
2.8.1 Numeric Operators
The operators for numeric data types include the standard arithmetic operators: addition (+),
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
fractional part is truncated. For example, 5 / 2yields 2, not 2.5, and –5 / 2yields -2, not
–2.5. To perform regular mathematical division, one of the operands must be a floating-point
number. For example, 5.0 / 2yields 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 % 3yields 1, 12 % 4 yields0, 26 % 8
yields 2, and 20 % 13yields 7.
floating point
what is overflow?
what is underflow?
integer types
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
operators+, -, *, /, %
integer division
34 Chapter 2 Elementar y Programming
line# seconds minutes remainingSeconds
8 500
10 8
11 20
importScanner
create a Scanner
read an integer
divide
Enter an integer for seconds:
500 seconds is 8 minutes and 20 seconds
500
ThenextInt() 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.
remainder
Remainder
Quotient
Dividend
Divisor
37
6
1
2
412
12
0
3
826
24
2
3
13 20
13
7
1
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 % 3yields -1, -12 % 4 yields0, -26 % -8 yields-2, and 20 % -13 yields7.
Remainder is very useful in programming. For example, an even number % 2is always 0
and an odd number % 2is 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:
(6 + 10) % 7 is 2
After 10 days
Day 2 in a week is Tuesday
Note: Day 0 in a week is Sunday
A week has 7 days
Day 6 in a week is Saturday
Listing 2.4 gives a program that obtains minutes and remaining seconds from an amount of
time in seconds. For example, 500seconds contains 8 minutes and 20seconds.
LISTING 2.4 DisplayTime.java
1
2
3 public class DisplayTime {
4 public static void main(String[] args) {
5
6 // Prompt the user for input
7 System.out.print("Enter an integer for seconds: ");
8 int seconds = ;
9
10 int minutes = ; // Find minutes in seconds
11 int remainingSeconds = ; // Seconds remaining
12 System.out.println(seconds + " seconds is " + minutes +
13 " minutes and " + remainingSeconds + " seconds");
14 }
15 }
seconds % 60
seconds / 60
input.nextInt()
Scanner input = new Scanner(System.in);
import java.util.Scanner;
2.8 Numeric Data Types and Operations 35
literal
longliteral
octal and hex literals
suffix d or D
suffix f or F
doublevs. float
The + and - operators can be both unary and binary. A unaryoperator has only one
operand; a binary operator has two. For example, the - operator in -5is a unary operator
to negate number 5, whereas the - operator in 4-5is a binary operator for subtracting 5
from 4.
Note
Calculations involving floating-point numbers are approximated because these numbers are not
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 and0.305
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 bytetype. (Note that the range for a byte value is from to 127.)
An integer literal is assumed to be of the int type, whose value is between
and To denote an integer literal of the longtype,
append the letter Lor l to it (e.g., 2147483648L).Lis preferred because l (lowercase L) can eas-
ily be confused with 1 (the digit one). To write integer 2147483648in a Java program, you have
to write it as 2147483648L, because 2147483648exceeds 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
leading0 (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
65535for 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 doubletype value. For example, 5.0 is considered a doublevalue, not a float
value. You can make a number a floatby appending the letter f orF, and you can make a
number a
double by appending the letter d orD. For example, you can use 100.2f or
100.2F for a floatnumber, and 100.2d or100.2D for a doublenumber.
Note
Thedouble typevalues are more accurate than the float type values. For example,
2
31
- 1 121474836472.-2
31
1-21474836482
-128
unary operator
binary operator
floating-point approximation
36 Chapter 2 Elementar y Programming
why called floating-point?
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 and 1.23456e-2 is
equivalent to E (or e) represents an exponent and can be in
either lowercase or uppercase.
Note
The float anddouble 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.534is converted into scientif ic 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
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
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 + 4x
5
-
101y - 521a + b + c2
x
+ 9a
4
x
+
9 + x
y
b
1.23456 * 10
-2
= 0.0123456.
1.23456 * 10
2
= 123.456,
evaluating an expression
3 + 4 * 4 + 5 * (4 + 3) - 1
3 + 4 * 4 + 5 * 71
3 + 16 + 5 * 71
3 + 16 + 351
19 + 351
54 – 1
53
(1) inside parentheses first
(2) multiplication
(3) multiplication
(4) addition
(5) addition
(6) subtraction
2.9 Problem: Displaying the Current Time 37
divide
Enter a degree in Fahrenheit:
Fahrenheit 100.0 is 37.77777777777778 in Celsius
100
Listing 2.5 gives a program that converts a Fahrenheit degree to Celsius using the formula
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 = * (fahrenheit - 32);
12 System.out.println("Fahrenheit " + fahrenheit + " is " +
13 celsius + " in Celsius");
14 }
15 }
(5.0 / 9)
celsius =
A
5
9
B
1fahrenheit - 322.
line# fahrenheit
celsius
8 100
11 37.77777777777778
Be careful when applying division. Division of two integers yields an integer in Java. is trans-
lated to 5.0 /9 instead of 5/9in line 11, because 5/9yields0 in Java.
2.9 Problem: Displaying the Current Time
The problem is to develop a program that displays the current time in GMT (Greenwich Mean
Time) in the format hour:minute:second, such as 13:19:8.
The currentTimeMillis method in the Systemclass returns the current time in mil-
liseconds elapsed since the time 00:00:00on 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
system was formally introduced.
5
9
currentTimeMillis
Unix epoch
Video Note
Use operators / and %
Unix Epoch
01-01-1970
00:00:00 GMT
Elapsed
time
Current Time
System.currentTimeMillis()
Time
FIGURE 2.2 TheSystem.currentTimeMillis() returns the number of milliseconds
since the Unix epoch.
integer vs. decimal division
You can use this method to obtain the current time, and then compute the current second,
minute, and hour as follows.
38 Chapter 2 Elementar y 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 totalMillisecondsby 1000
(e.g., 1203183086328 milliseconds / 1000 1203183086seconds).
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 by60 (e.g.,
1203183086seconds / 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 334217hours).
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
4 long totalMilliseconds = System.currentTimeMillis();
5
6 // Obtain the total seconds since midnight, Jan 1, 1970
7 long totalSeconds = totalMilliseconds / 1000;
8
9 // Compute the current second in the minute in the hour
10 long currentSecond = (int)(totalSeconds % 60);
11
12 // Obtain the total minutes
13 long totalMinutes = totalSeconds / 60;
14
15 // Compute the current minute in the hour
16 long currentMinute = totalMinutes % 60;
17
18 // Obtain the total hours
19 long totalHours = totalMinutes / 60;
20
21 // Compute the current hour
22 long currentHour = totalHours % 24;
23
24 // Display results
25 System.out.println("Current time is " + currentHour + ":"
26 + currentMinute + ":" + currentSecond + " GMT");
27 }
28 }
=
=
=
=
=
=
totalMilliseconds
totalSeconds
currentSecond
totalMinutes
Current time is 17:31:26 GMT
currentMinute
totalHours
currentHour
2.10 Shorthand Operators 39
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 longvalue. 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 iwith 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
Table 2.4.
+=
addition assignment operator
line#
variables
4 7 10 13 16 19 22
totalMilliseconds 1203183086328
totalSeconds 1203183086
currentSecond 26
totalMinutes 20053051
currentMinute 31
totalHours 334217
currentHour 17
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 Elementar y Programming
TABLE 2.5 Increment and Decrement Operators
Operator Name Description Example (assume i = 1)
++var
preincrement
Incrementvar by1 and
use the new
varvalue
int j = ++i;// j is 2,
// i is 2
var++
postincrement
Incrementvar by1, but
use the original
varvalue
int j = i++;// j is 1,
// i is 2
--var
predecrement
Decrementvar by1 and
use the new
varvalue
int j = --i;// j is 0,
// i is 0
var--
postdecrement
Decrementvar by1 and
use the original
varvalue
int j = ++i;// j is 1,
// i is 0
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 += 2is a
statement in the first line and an expression in the second line.
; // Statement
System.out.println( ); // 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 iby 1 and decrements jby1.
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.
x += 2
x += 2
preincrement, predecrement
postincrement, postdecrement
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 operatorand the predecrement operator; and the suffixes x++and x—— are referred
to, respectively, as the postincrement operatorand 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:
Same effect as
int i = 10;
int newNum = 10 * (++i);
i = i + 1;
int newNum = 10 * i;
Same effect as
int i = 10;
int newNum = 10 * i++;
int newNum = 10 * i;
i = i + 1;
In this case, iis incremented by 1, then the old value of i is returned and used in the mul-
tiplication. So
newNumbecomes 100. If i++ is replaced by ++ias follows,
2.11 Numeric Type Conversions 41
iis incremented by 1, and the new value of i is returned and used in the multiplication. Thus
newNum becomes110.
Here is another example:
double x = 1.0;
double y = 5.0;
double z = x–– + (++y);
After all three lines are executed, ybecomes 6.0, z becomes7.0, and x becomes0.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:
intk = ++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.5is 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 longvalue to a float variable. You cannot, how-
ever, assign a value to a variable of a type with smaller range unless you use typecasting.
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
type with a smaller range is known as narrowing a type. Widening a type can be performed
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
be cast. For example, the following statement
System.out.println((int)1.7);
displays 1. When a double value is cast into an intvalue, the fractional part is truncated.
The following statement
System.out.println((double)1 / 2);
displays0.5, because 1 is cast to 1.0first, then 1.0 is divided by 2. However, the statement
System.out.println(1 / 2);
displays0, because 1 and2 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
assigning a
doublevalue 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.
widening a type
narrowing a type
type casting
possible loss of precision
42 Chapter 2 Elementar y Programming
line# purchaseAmount tax output
8 197.55
10 11.853
11 11.85
Note
Casting does not change the variable being cast. For example, dis 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
Toassign a variable of the int type to a variable of the short orbyte 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
shortor 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
10 double tax = purchaseAmount * 0.06;
11 System.out.println("Sales tax is " + (int);
12 }
13 }
(tax * 100) / 100.0)
casting
Enter purchase amount:
Sales tax is 11.85
197.55
VariablepurchaseAmount is197.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.
formatting numbers
2.12 Problem: Computing Loan Payments 43
pow(a, b)method
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
student loan, or a home mortgage loan. The program lets the user enter the interest rate, num-
ber of years, and loan amount, and displays the monthly and total payments.
The formula to compute the monthly payment is as follows:
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 The
pow(a, b)method in the Math class can be used to compute The Math class, which
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
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
2
3 public class ComputeLoan {
4 public static void main(String[] args) {
5 // Create a Scanner
6
7
8 // Enter yearly interest rate
9 System.out.print("Enter yearly interest rate, for example 8.25: ");
10
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
19
20 // Enter loan amount
21 System.out.print("Enter loan amount, for example 120000.95: ");
int numberOfYears = input.nextInt();
double annualInterestRate = input.nextDouble();
Scanner input = new Scanner(System.in);
import java.util.Scanner;
11 + monthlyInterestRate2
numberOfYears*12
a
b
.
11 + monthlyInterestRate2
numberOfYears*12
.
monthlyPayment
=
loanAmount * monthlyInterestRate
1 -
1
11 + monthlyInterestRate2
numberOfYears*12
import class
create a
Scanner
enter interest rate
enter years
Video Note
Program computations
44 Chapter 2 Elementar y Programming
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, numberOfYearsis
best declared as an int(line 18), although it could be declared as a long, float, or double.
Note that bytemight be the most appropriate for numberOfYears. For simplicity, however,
the examples in this book will use intfor 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 monthlyPaymentand totalPayment
with two digits after the decimal point.
The program uses the Scannerclass, imported in line 1. The program also uses the Math class;
why isn’t it imported? The Mathclass 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 Mathclass.
2.13 Character Data Type and Operations
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';
chartype
22
23
24 // Calculate payment
25 double = loanAmount * monthlyInterestRate / (1
26 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
27 double = monthlyPayment * numberOfYears * 12;
28
29 // Display results
30 System.out.println("The monthly payment is " +
31 (int)(monthlyPayment * 100) / 100.0);
32 System.out.println("The total payment is " +
33 (int)(totalPayment * 100) / 100.0);
34 }
35 }
totalPayment
monthlyPayment
double loanAmount = input.nextDouble();
enter loan amount
monthlyPayment
totalPayment
casting
casting
Enter yearly interest rate, for example 8.25:
Enter number of years as an integer, for example 5:
Enter loan amount, for example 120000.95:
The monthly payment is 2076.02
The total payment is 373684.53
250000
15
5.75
line#
variables
10 13 18 22 25 27
annualInterestRate 5.75
monthlyInterestRate 0.0047916666666
numberOfYears 15
loanAmount 250000
monthlyPayment 2076.0252175
totalPayment 373684.539
java.langpackage
2.13 Character Data Type and Operations 45
charliteral
character encoding
Unicode
original Unicode
supplementary Unicode
ASCII
The first statement assigns character A to the charvariable letter. The second statement
assigns digit character 4to the char variablenumChar.
Caution
A string literal must be enclosed in quotation marks. A character literal is a single character
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
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
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
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,536characters 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,064characters. Those characters that
go beyond the original 16-bit limit are called supplementary characters. Java supports sup-
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 typevariable.
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 are \u03b1 \u03b2\u03b3.
Most computers use ASCII(American Standard Code for Information Interchange), a 7-bit
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 Ato char variableletter.
a b g
46 Chapter 2 Elementar y Programming
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
Note
The increment and decrement operators can also be used on char variables to get the next or
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.
Toovercome this problem, Java defines escape sequences to represent special characters,
as shown in Table 2.6. An escape sequence begins with the backslashcharacter (\) followed
by a character that has a special meaning to the compiler.
backslash
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
charincrement and
decrement
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 \uFFF4cannot fit into a byte:
byte b = '\uFFF4';
To force assignment, use explicit casting, as follows:
byte b = (byte)'\uFFF4';
Any positive integer between 0and FFFF in hexadecimal can be cast into a character implic-
itly. Any number not in this range must be cast into a charexplicitly.
Note
All numeric operators can be applied to char operands. A charoperand is automatically cast
into a number if the other operand is a number or a character. If the other operand is a string, the
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.
Á,
numeric operators on
characters
48 Chapter 2 Elementar y 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
100to 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
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: ");
11
12
13 int remainingAmount = (int)(amount * 100);
14
15 // Find the number of one dollars
16
17 remainingAmount = remainingAmount % 100;
18
19 // Find the number of quarters in the remaining amount
20
21 remainingAmount = remainingAmount % 25;
22
23 // Find the number of dimes in the remaining amount
24
25 remainingAmount = remainingAmount % 10;
26
27 // Find the number of nickels in the remaining amount
28
29 remainingAmount = remainingAmount % 5;
30
31 // Find the number of pennies in the remaining amount
32 int numberOfPennies = remainingAmount;
33
34 // Display results
35 System.out.println("Your amount " + amount + " consists of \n" +
int numberOfNickels = remainingAmount / 5;
int numberOfDimes = remainingAmount / 10;
int numberOfQuarters = remainingAmount / 25;
int numberOfOneDollars = remainingAmount / 100;
double amount = input.nextDouble();
import class
enter input
dollars
quarters
dimes
nickels
pennies
prepare output
2.14 Problem: Counting Monetary Units 49
line#
variables
11 13 16 17 20 21 24 25 28 29 32
Amount 11.56
remainingAmount 1156 56 6 6 1
numberOfOneDollars 11
numberOfQuarters 2
numberOfDimes 0
numberOfNickles 1
numberOfPennies 1
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:
Your amount 11.56 consists of
11 dollars
2 quarters
0 dimes
1 nickels
1 pennies
11.56
The variable amountstores 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-
ingremainingAmount.
The variable amountis 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 is1156. The division operator yields the inte-
ger part of the division. So 1156/ 100is 11. The remainder operator obtains the remainder
of the division. So 1156% 100is 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
double amount to an intremainingAmount. This could lead to an inaccurate result. If you
try to enter the amount 10.03,10.03 * 100 becomes1002.9999999999999. You will find
that the program displays 10 dollars and 2pennies. To fix the problem, enter the amount as an
integer value representing cents (see Exercise 2.9).
loss of precision
50 Chapter 2 Elementar y Programming
As shown in the sample run, 0dimes, 1 nickels, and 1pennies are displayed in the result.
It would be better not to display 0 dimes, and to display 1nickel 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 Stringvariable, 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
concatenation operator if one of the operands is a string. If one of the operands is a nonstring
(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 messageis “Welcome to Java and Java is fun”.
Suppose that i = 1and 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
forcei + j to be executed first, enclose i + jin the parentheses, as follows:
System.out.println("i + j is " + i + j );
Toread a string from the console, invoke the next() method on a Scannerobject. 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();
)
(
concatenating strings and
numbers
reading strings
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:
s1 is Welcome
s2 is to
s3 is Java
Welcome to Java
The next() method reads a string that ends with a whitespacecharacter (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:
The string entered is "Welcome to Java"
Welcome to Java
Important Caution
To avoid input errors, do not use nextLine() afternextByte(),nextShort(), nextInt(),
nextLong(), nextFloat(), nextDouble(), and next(). The reasons will be explained in
§9.7.3, “How Does
ScannerWork?”
2.16 Programming Style and Documentation
Programming styledeals with what programs look like. A program can compile and run prop-
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. Documentationis the body of explanatory remarks and
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
*/. They can be extracted into an HTML file using JDK’s javadoc command. For more
information, see java.sun.com/j2se/javadoc.
avoiding input errors
programming style
documentation
javadoc comment
52 Chapter 2 Elementar y 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.
Use lowercase for variables and methods. If a name consists of several words, con-
catenate them into one, making the first word lowercase and capitalizing the first let-
ter of each subsequent word—for example, the variables radiusand area and the
method showInputDialog.
Capitalize the first letter of each word in a class name—for example, the class names
ComputeArea, Math, and JOptionPane.
Capitalize every letter in a constant, and use underscores between words—for exam-
ple, the constants PI andMAX_VALUE.
It is important to follow the naming conventions to make programs easy to read.
Caution
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
Avoid using abbreviations for identifiers. Using complete words is more descriptive. For example,
numberOfStudentsis 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.
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:
naming variables and
methods
naming classes
naming constants
naming classes
using full descriptive names
indent code
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
Compile
FIGURE 2.3 The compiler reports syntax errors.
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-linestyle 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 errorsor compile 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.
1 // ShowSyntaxErrors.java: The program contains syntax errors
2 public class ShowSyntaxErrors {
3 public static void main(String[] args) {
4
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.
i = 30;
syntax errors
syntax error
public class Test
{
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
Next-line style
End-of-line style
54 Chapter 2 Elementar y Programming
Run
FIGURE2.4 The runtime error causes the program to terminate abnormally.
2.17.2 Runtime Errors
Runtime errorsare 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.
1 // ShowRuntimeErrors.java: Program contains runtime errors
2 public class ShowRuntimeErrors {
3 public static void main(String[] args) {
4 int i = ;
5 }
6 }
2.17.3 Logic Errors
Logic errorsoccur 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 tonumber2.
// 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.
+=
1 / 0
runtime errors
runtime error
2.18 (GUI) Getting Input from Input Dialogs 55
ClickCancel to dismiss the
dialog without input
String input =
JOptionPane.showInputDialog(
"Enter an input");
ClickOK to accept
input and dismiss the
dialog
FIGURE 2.5 The input dialog box enables the user to enter a string.
Logic errors are called bugs. The process of finding and correcting errors is called
debugging. A common approach is to use a combination of methods to narrow down to the
part of the program where the bug is located. You can hand-tracethe program (i.e., catch
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
debuggerutility.
Pedagogical NOTE
An IDE not only helps debug errors but also is an effective pedagogical tool. Supplement II shows
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.showInputDialogmethod, as shown in Figure 2.5.
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 showInputDialogmethod. For the time being, you need
to know only two ways to invoke it.
One is to use a statement like this one:
JOptionPane.showInputDialog(x);
wherex 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 yis a string for the title of the input dialog
box, as shown in the example below.
bugs
debugging
hand traces
learning tool
JOptionPaneclass
showInputDialogmethod
String input =
JOptionPane.showInputDialog(null,
"Enter an input",
"Input Dialog Demo",
JOptionPane.QUESTION_MESSAGE);
56 Chapter 2 Elementar y Programming
(a)
(c)
(b)
(d)
FIGURE2.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).
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.
Toconvert a string into an int value, use the parseIntmethod in the Integer class, as
follows:
int intValue = Integer.parseInt(intString);
whereintString is a numeric string such as "123".
To convert a string into a doublevalue, use the parseDouble method in the Double
class, as follows:
double doubleValue = Double.parseDouble(doubleString);
wheredoubleString is a numeric string such as "123.45".
TheInteger andDouble classes are both included in the java.langpackage, 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.
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
6 String annualInterestRateString = JOptionPane.showInputDialog(
7 "Enter yearly interest rate, for example 8.25:");
8
9 // Convert string to double
10 double annualInterestRate =
11 Double.parseDouble(annualInterestRateString);
12
Integer.parseIntmethod
Double.parseDouble
method
enter interest rate
convert string to double
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
32
33
34
35 // Format to keep two digits after the decimal point
36
37
38
39 // Display results
40
41
42 JOptionPane.showMessageDialog(null, );
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 JOptionPaneor Scanner, whichever is convenient. For con-
sistency most examples in this book use
Scanner for getting input. You can easily revise the
examples using
JOptionPanefor getting input.
KEY TERMS
output
"\nThe total payment is " + totalPayment;
String output = "The monthly payment is " + monthlyPayment +
totalPayment = (int)(totalPayment * 100) / 100.0;
monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
double totalPayment = monthlyPayment * numberOfYears * 12;
1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
double monthlyPayment = loanAmount * monthlyInterestRate / (1
monthlyPayment
totalPayment
preparing output
JOptionPaneor Scanner?
algorithm 24
assignment operator (=)30
assignment statement 30
backslash (
\)46
byte type 27
casting 41
char type 44
constant 31
data type 25
debugger 55
debugging 55
declaration 30
decrement operator (--)41
double type 33
encoding 45
final 31
58 Chapter 2 Elementar y Programming
floattype 35
floating-point number 33
expression 31
identifier 29
increment operator (++)41
incremental development and testing 26
indentation 52
int type 34
literal 35
logic error 54
longtype 35
narrowing (of types) 41
operator 33
overflow 33
pseudocode 30
primitive data type 25
runtime error 54
shorttype 27
syntax error 53
supplementary Unicode 45
underflow 33
Unicode 45
Unix epoch 43
variable 24
widening (of types) 41
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 Elementar y 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 mileswith initial value 100;
Step 2: Declare a double constant named MILES_PER_KILOMETERwith 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
value20.
Sections 2.8–2.10
2.4 Assume that int a= 1and 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
31r + 342
- 91a + bc2 +
3 + d12 + a2
a + bd
Review Questions 61
2.11 Supposem andr are integers. Write a Java expression for mr
2
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+5is also an expression.
(d) The statement x=y=x=0is 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 doubleto 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 Elementar y 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 JOptionPanebut 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
www.cs.armstrong.edu/liang/intro8e/exercise8e.zipand use the command
java -cp exercise8e.zip Exercise
i
_
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,
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/5is1, but 9.0 /5 is1.8.
Here is a sample run:
sample runs
learn from examples
Enter a degree in Celsius:
43 Celsius is 109.4 Fahrenheit
43
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 Elementar y Programming
Enter the radius and length of a cylinder:
The area is 95.0331
The volume is 1140.4
5.5 12
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.305meter. Here is a sample run:
Enter a value for feet:
16 feet is 4.88 meters
16
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 pounds is 25.197 kilograms
55.5
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
enters10 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:
The gratuity is 2.35 and total is 18.04
15.69 15
2.6** (Summing the digits in an integer) Write a program that reads an integer between
0and 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= 2and 932 /10 =93.
Here is a sample run:
Enter a number between 0 and 1000:
The sum of the digits is 27
999
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 minutes is approximately 1902 years and 214 days.
1000000000
Programming Exercises 65
Enter an ASCII code:
The character for ASCII code 69 is E
69
2.9* (Financial application: monetary units) Rewrite Listing 2.10, Compute-
Change.java, to fix the possible loss of accuracy when converting a doublevalue
to an int value. Enter the input as an integer whose last two digits represent the
cents. For example, the input 1156represents 11 dollars and 56cents.
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:
Enter number of hours worked in a week:
Enter hourly pay rate:
Enter federal tax withholding rate:
Enter state tax withholding rate:
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
0.09
0.20
6.75
10
Smith
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
Section 2.13
2.8* (Finding the character of an ASCII code) Write a program that receives an ASCII
code (an integer between 0and 128) and displays its character. For example, if the
user enters 97, the program displays character a. Here is a sample run:
66 Chapter 2 Elementar y Programming
Enter balance and interest rate (e.g., 3 for 3%):
The interest is 2.91667
1000 3.5
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
years1, the future investment value is 1032.98.
Hint: Use the Math.pow(a,b) method to compute araised to the power of b.
Here is a sample run:
Enter investment amount:
Enter monthly interest rate:
Enter number of years:
Accumulated value is 1043.34
1
4.25
1000
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
user to enter a weight in pounds and height in inches and display the BMI. Note
that one pound is 0.45359237kilograms and one inch is 0.0254 meters. Here is
a sample run:
Enter weight in pounds:
Enter height in inches:
BMI is 26.8573
50
95.5
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 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
0.05 / 12 = 0.00417.
Video Note
Compute BMI
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:
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
whereM is the weight of water in kilograms, temperatures are in degrees Celsius,
and energy Qis measured in joules. Here is a sample run:
Enter the amount of water in kilograms:
Enter the initial temperature:
Enter the final temperature:
The energy needed is 1.62548e+06
10.5
3.5
55.5
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:
where is the outside temperature measured in degrees Fahrenheit and vis the speed
measured in miles per hour. is the wind-chill temperature. The formula cannot be
used for wind speeds below 2 mph or temperatures below or above 41°F.
Write a program that prompts the user to enter a temperature between 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 . Here is a sample run:v
0.16
-58°F
-58°F
t
wc
t
a
t
wc
= 35.74 + 0.6215t
a
- 35.75v
0.16
+ 0.4275t
a
v
0.16
Enter the temperature in Fahrenheit:
Enter the wind speed miles per hour:
The wind chill index is -5.56707
6
5.3
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 Elementar y Programming
Enter x1 and y1:
Enter x2 and y2:
The distance of the two points is 8.764131445842194
4 5
1.5 -3.4
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
Here is a sample run.
area = 2s1s - side121s - side221s - side32
s = 1side1 + side2 + side32/2;
Enter three points for a triangle:
The area of the triangle is 33.6
1.5 -3.4 4.6 5 9.5 -3.4
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
wheres is the length of a side. Here is a sample run:
Area =
313
2
s
2
,
Enter the side:
The area of the hexagon is 78.5895
5.5
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:
Write a program that prompts the user to enter the starting velocity in
meters/second, the ending velocity in meters/second, and the time span tin sec-
onds, and displays the average acceleration. Here is a sample run:
v
1
v
0
a =
v
1
- v
0
t
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 Note you can use the
Math.pow(a,0.5) to compute Here is a sample run:1a.
21x
2
- x
1
2
2
+ 1y
2
- y
1
2
2
.
Programming Exercises 69
Enter v0, v1, and t:
The average acceleration is 10.0889
5.5 50.9 4.5
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:
Write a program that prompts the user to enter v in meters/second (m/s) and the
acceleration a in meters/second squared and displays the minimum run-
way length. Here is a sample run:
1m/s
2
2,
length =
v
2
2a
Enter v and a:
The minimum runway length for this airplane is 514.286
60 3.5
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:
The current time is 4:50:34
-5
This page intentionally left blank
SELECTIONS
CHAPTER 3
Objectives
To declare booleantype and write Boolean expressions using comparison operators (§3.2).
To program AdditionQuizusing Boolean expressions (§3.3).
To implement selection control using one-way if
statements (§3.4)
To program the GuessBirthdaygame 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 ifstatements (§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 radiusin Listing 2.2, ComputeAreaWithConsoleInput.java,
the program prints an invalid result. If the radius is negative, you don’t want the program to
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
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 5in the table).
problem
comparison operators
compare characters
vs. ===
Boolean variable
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
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
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: trueor false. For example, the following
statement displays true:
double radius = 1;
System.out.println(radius > 0);
A variable that holds a Boolean value is known as a Booleanvariable. 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;
trueand false are literals, just like a number such as 10. They are reserved words and can-
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, number1and number2, and displays to the stu-
dent a question such as “What is ”, as shown in the sample run. After the student types
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
6
7
8 // Create a Scanner
9 Scanner input = new Scanner(System.in);
10
11 System.out.print(
12 "What is " + number1 + " + " + number2 + "? ");
13
14
15
16 System.out.println(
17 number1 + " + " + number2 + " = " + answer + " is " +
18 ( ));
19 }
20 }
number1 + number2 == answer
int answer = input.nextInt();
int number2 = (int)(System.currentTimeMillis() * 7 % 10);
int number1 = (int)(System.currentTimeMillis() % 10);
7 + 9?
Boolean literals
generate number1
generate number2
show question
display result
What is 1 + 7?
1 + 7 = 8 is true
8
What is 4 + 8?
4 + 8 = 9 is false
9
line# number1 number2 answer output
54
68
14 9
16 4 + 8 = 9 is false
Video Note
Program addition quiz
74 Chapter 3 Selections
3.4 if Statements
The preceding program displays a message such as “ is false.” If you wish the message
to be “ 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 ifstatements, 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 ifstatement is shown below:
if (boolean-expression) {
statement(s);
}
The execution flow chart is shown in Figure 3.1(a).
6 + 2 = 7
6 + 2 = 7
whyif statement?
ifstatement
If the boolean-expressionevaluates 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 areais 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).
F
IGURE3.1 Anif statement executes statements if the boolean-expressionevaluates to true.
Statement(s)
boolean-
expression
true
false
(a)
area = radius * radius * PI;
System.out.println("The area for the circle of" +
"radius" + radius + "is" + area);
(radius >= 0)
true
false
(b)
if i > 0 {
System.out.println("i is positive");
}
if i > 0 {
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.
enter input
check 5
check even
Enter an integer:
HiEven
4
Enter an integer:
HiFive
HiEven
30
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 HiEvenif 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.
if (i > 0)
System.out.println("i is positive");
}
{
if (i > 0)
System.out.println("i is positive");
Equivalent
(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();
8
9
10 System.out.println("HiFive");
11
12
13 System.out.println("HiEven");
14 }
15 }
if (number % 2 == 0)
if (number % 5 == 0)
16 17 18 19
20 21 22 23
24 25 26 27
28 29 30 31
91011
12 13 14 15
24 25 26 27
28 29 30 31
567
12 13 14 15
20 21 22 23
28 29 30 31
2367
10 11 14 15
18 22 23
26 27 30 31
357
9111315
17 19
1921 23
25 27 29 31
Set1 Set2 Set3 Set4 Set5
= 19
84
1
+
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
35
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
46
47 day += 1;
48
if (answer == 1)
int day = 0;
day to be determined
in Set1?
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
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
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
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
83 day += 16;
84
85 System.out.println("\nYour birthday is " + day + "!");
86 }
87 }
if (answer == 1)
if (answer == 1)
if (answer == 1)
if (answer == 1)
in Set2?
in Set3?
in Set4?
in Set5?
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:
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:
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
1
1
78 Chapter 3 Selections
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
Decimal Binary
1 00001
2 00010
000113
...
19 10011
...
31 11111
10000
10
1+
10011
19 31
10000
1000
100
10
+1
11111
0
00
0
0
0
b
5
b
4
b
3
b
2
b
1
b
5
b
4
b
3
b
2
b
1
0
000
+
(a) (b)
FIGURE3.2 (a) A number between 1 and31 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.
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:
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:
Your birthday is 19
1
0
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 1and 31 has at most five digits, as shown in Figure 3.2(a). Let it
be So, as shown in
Figure 3.2(b). If a day’s binary number has a digit 1in the number should appear in Setk. For
example, number 19is binary 10011, so it appears in Set1, Set2, and Set5. It is binary 1 +10 +
10000= 10011
or decimal 1+2+16=19. Number 31is binary 11111, so it appears in Set1,
Set2, Set3, Set4, and Set5. It is binary 1+ 10+ 100+ 1000+ 10000= 11111or decimal 1+2
+4+8+16=31
.
b
k
,
b
5
b
4
b
3
b
2
b
1
= b
5
0000 + b
4
000 + b
3
00 + b
2
0 + b
1
,b
5
b
4
b
3
b
2
b
1
.
mathematics behind the game
3.6 Two-Way if Statements 79
Statement(s) for the true case Statement(s) for the false case
boolean-
expression
true
false
3.6 Two-Way ifStatements
A one-way ifstatement 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 ifstatement. The actions that a two-way if statement spec-
ifies differ based on whether the condition is trueor false.
Here is the syntax for a two-way ifstatement:
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.
FIGURE 3.3 Anif ...else statement executes statements for the true case if the
boolean-expressionevaluates to true; otherwise, statements for the false case are
executed.
If the
boolean-expressionevaluates 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) {
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 istrue, 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.
two-way ifstatement
80 Chapter 3 Selections
Equivalent
This is better
(a) (b)
if (score >= 90.0)
grade = 'A';
else
if (score >= 80.0)
grade = 'B';
else
if (score >= 70.0)
grade = 'C';
else
if (score >= 60.0)
grade = 'D';
else
grade = 'F';
if (score >= 90.0)
grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';
FIGURE3.4 A preferred format for multiple alternative if statements is shown in (b).
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 orif ...else statement can be any legal Java statement, including
another if orif ...else statement. The inner ifstatement is said to be nested inside the
outer if statement. The inner ifstatement can contain another if statement; in fact, there is
no limit to the depth of the nesting. For example, the following is a nested ifstatement:
if (i > k) {
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 gradeaccording to
the score, with multiple alternatives.
nestedif statement
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.
Theif statement in Figure 3.4(a) is equivalent to the ifstatement 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
if (number % 2 == 0)
even = true;
else
even = false;
boolean even
= number % 2 == 0;
This is shorter
Equivalent
(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 ifstatement 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).
assignboolean variable
Tip
Often, to assign a test condition to a booleanvariable, new programmers write code as in (a)
below:
if (even == true)
System.out.println(
"It is even.");
if (even)
System.out.println(
"It is even.");
This is better
(a) (b)
Equivalent
if (radius >= 0)
area = radius * radius * PI;
System.out.println("The area "
+ " is " + area);
if (radius >= 0)
area = radius * radius * PI;
System.out.println("The area "
+ " is " + area);
}
{
(a) Wrong
(b) Correct
Common Error 2: Wrong Semicolon at the ifLine
Adding a semicolon at the if line, as shown in (a) below, is a common mistake.
if (radius >= 0);
{
area = radius * radius * PI;
System.out.println("The area "
+ " is " + area);
}
if (radius >= 0) { };
{
area = radius * radius * PI;
System.out.println("The area "
+ " is " + area);
}
Equivalent
Logic Error
(a) (b)
Empty Block
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 booleanvariable is true orfalse in a test condition, it is redundant to
use the equality comparison operator like the code in (a):
82 Chapter 3 Selections
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
int i = 1;
int j = 2;
int k = 3;
int i = 1;
int j = 2;
int k = 3;
if (i > j)
if (i > k)
System.out.println("A");
else
System.out.println("B");
(a) (b)
Equivalent
This is better
with correct
indentation
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 trueto even, so that even is always true.
Common Error 4: Dangling elseAmbiguity
The code in (a) below has two ifclauses and one else clause. Which ifclause is matched
by the elseclause? The indentation indicates that the else clause matches the first ifclause.
However, the elseclause 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).
Since (i > j) is false, nothing is printed from the statement in (a) and (b). To force the
elseclause 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 andnumber2, with number1 > =
number2
and displays to the student a question such as “What is ” After the student
enters the answer, the program displays a message indicating whether it is correct.
The previous programs generate random numbers using System.currentTimeMillis().
A better approach is to use the random() method in the Mathclass. Invoking this method
returns a random double value
d such that 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 andnumber2.
If number1 <number2, swap number1 withnumber2.
0.0 d 6 1.0.
9 - 2?
}
{
random()method
Video Note
Program subtraction quiz
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);
7 int number2 = (int)(Math.random() * 10);
8
9 // 2. If number1 < number2, swap number1 with number2
10 {
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
21
22 // 4. Grade the answer and display the result
23
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 }
if (number1 - number2 == answer)
int answer = input.nextInt();
if (number1 < number2)
random numbers
get answer
check the answer
What is 6 - 6?
You are correct!
0
What is 9 - 2?
Your answer is wrong
9 - 2 should be 7
5
line# number1 number2 temp answer output
62
79
11 2
12 9
13 2
20 5
26 Your answer is wrong
9 – 2 should be 7
84 Chapter 3 Selections
BMI
Interpretation
below 16
seriously underweight
16–18 underweight
18–24 normal weight
24–29 overweight
29–35 seriously overweight
above 35 gravely overweight
To swap two variables number1and number2, a temporary variable temp(line 11) is used
to first hold the value in number1. The value in number2is assigned to number1 (line 12),
and the value in tempis 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:
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: ");
9 double weight = input.nextDouble();
10
11 // Prompt the user to enter height in inches
12 System.out.print("Enter height in inches: ");
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;
21 double bmi = weightInKilograms /
22 (heightInMeters * heightInMeters);
23
24 // Display result
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");
input weight
input height
compute
bmi
display output
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:
Enter height in inches:
Your BMI is 20.948603801493316
You are normal weight
70
146
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-
rately, and head of household. The tax rates vary every year. Table 3.2 shows the rates for
2009. If you are, say, single with a taxable income of $10,000, the first $8,350 is taxed at 10%
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
Tax Rate
Single
Married Filing Jointly
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+
Video Note
Use multiple alternative
if statements
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, 1for married filing jointly, 2 for married filing separately, and 3for 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%, at 15%, at 25%, at 28%,
at 33%, and 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: ");
13 int status = input.nextInt();
14
15 // Prompt the user to enter taxable income
16 System.out.print("Enter the taxable income: ");
17 double income = input.nextDouble();
18
19 // Compute tax
20 double tax = 0;
21
22 // 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 +
if (status == 0) {
1400,000 - 372,95021372,950 - 171,5502
1171,550 - 82,2502182,250 - 33,9502133,950 - 8,3502
input status
input income
compute tax
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 // Compute tax for married file jointly
43 // Left as exercise
44 }
45 // Compute tax for married separately
46 // Left as exercise
47 }
48 // Compute tax for head of household
49 // Left as exercise
50 }
51
52 System.out.println("Error: invalid status");
53 System.exit(0);
54 }
55
56 // Display the result
57 System.out.println("Tax is " + (int)(tax * 100) / 100.0);
58 }
59 }
else {
else if (status == 3) {
else if (status == 2) {
else if (status == 1) {
exit program
display output
(0-single filer, 1-married jointly,
2-married separately, 3-head of household)
Enter the filing status:
Enter the taxable income:
Tax is 117683.5
400000
0
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-
nates the program. The argument 0indicates 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
System.exit(0)
88 Chapter 3 Selections
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 is false, because is true.1age 7 182!1age 7182
false true !(gender =='M') istrue, because (gender =='M')
isfalse.
TABLE 3.5 Truth Table for Operator &&
p1 p2 p1 && p2
Example (assume )age = 24, gender = ‘F’
false
false false (age >18) && (gender =='F') istrue,
because
(age> 18)and (gender =='F') are
both
true.
false true false
true false false (age> 18)&&(gender !='F') isfalse,
because
(gender!= 'F')is false.
true true true
statement. The compiler thinks that these statements may not be executed and therefore
reports a syntax error.
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
more code. This is called incremental development and testing. This approach makes debugging
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
asBoolean operators, operate on Boolean values to create a new Boolean value. Table 3.3 gives
a list of Boolean operators. Table 3.4defines the not (!) operator. The not (!) operator negates
true tofalse andfalse totrue. 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 trueif at least one of the operands is
true. Table 3.7 defines the exclusive or (^) operator. The exclusive or (^) of two Boolean
operands is trueif and only if the two operands have different Boolean values.
test all cases
incremental development and
testing
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')
istrue.
false true true
true false true (age >34) ||(gender =='M') isfalse, because (age> 34)and
(gender== 'M')are both false.
true true true
Listing 3.7 gives a program that checks whether a number is divisible by 2and 3, by 2 or
3, and by 2or 3 but not both:
LISTING 3.7 TestBooleanOperators.java
1 import java.util.Scanner;
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
11
12 System.out.println("Is " + number +
13 "\n\tdivisible by 2 and 3? " +
14 ( )
15 + "\n\tdivisible by 2 or 3? " +
16 ( ) +
17 "\n\tdivisible by 2 or 3, but not both? "
18 + ( ));
19 }
20 }
number % 2 == 0 ^ number % 3 == 0
number % 2 == 0 || number % 3 == 0
number % 2 == 0 && number % 3 == 0
int number = input.nextInt();
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
falsebut (gender =='F') istrue.
false true true
true false true (age >34) ||(gender =='M') isfalse, because (age> 34)and
(gender== 'M')are both false.
true true false
import class
input
and
or
exclusive or
Enter an integer:
Is 18
divisible by 2 and 3? true
divisible by 2 or 3? true
divisible by 2 or 3, but not both? false
18
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 2and 3. (number %2== 0|| number%3 ==0) (line 16)
checks whether the number is divisible by 2or 3. (number %2== 0^number %3 ==0)(line
20) checks whether the number is divisible by 2or 3, but not both.
Caution
In mathematics, the expression
1 <= numberOfDaysInAMonth <= 31
is correct. However, it is incorrect in Java, because 1<= numberOfDaysInAMonthis evaluated
to a
booleanvalue, which cannot be compared with 31. Here, two operands (a boolean value
and a numeric value) are incompatible. The correct expression in Java is
(1 <= numberOfDaysInAMonth) && (numberOfDaysInAMonth <= 31)
Note
As shown in the preceding chapter, a charvalue 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
another type be cast into a
booleanvalue.
Note
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 p1is true, evaluates p2; if p1 isfalse, it does not evaluate p2. When eval-
uatingp1 ||p2, Java first evaluates p1 and then, if p1is false, evaluates p2; if p1 istrue,
it does not evaluate p2. Therefore, && is referred to as the conditionalor short-circuit AND
operator, and is referred to as the conditional or short-circuit OR operator.
3.13 Problem: Determining Leap Year
A year is a leap year if it is divisible by 4 but not by 100or 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);
ƒƒ
incompatible operands
cannot cast
boolean
De Morgan’s law
conditional operator
short-circuit operator
leap year
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();
9
10 // Check if the year is a leap year
11 boolean isLeapYear =
12 ;
13
14 // Display the result
15 System.out.println(year + " is a leap year? " + isLeapYear);
16 }
17 }
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
input
leap year?
display result
Enter a year:
2008 is a leap year? true
Enter a year:
2002 is a leap year? false
2002
2008
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
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
12
13 // Get digits from lottery
14 int lotteryDigit1 = lottery / 10;
int guess = input.nextInt();
int lottery = (int)(Math.random() * 100);
generate a lottery
enter a guess
92 Chapter 3 Selections
line#
variable
6 111415181933
lottery 34
guess 23
lotteryDigit1 3
lotteryDigit2 4
guessDigit1 2
guessDigit2 3
output Match one digit:
you win $1,000
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
24
25 System.out.println("Exact match: you win $10,000");
26
27
28 System.out.println("Match all digits: you win $3,000");
29
30
31
32
33 System.out.println("Match one digit: you win $1,000");
34 else
35 System.out.println("Sorry, no match");
36 }
37 }
|| guessDigit2 == lotteryDigit2)
|| guessDigit2 == lotteryDigit1
|| guessDigit1 == lotteryDigit2
else if (guessDigit1 == lotteryDigit1
&& guessDigit1 == lotteryDigit2)
else if (guessDigit2 == lotteryDigit1
if (guess == lottery)
exact match?
match all digits?
Enter your lottery pick (two digits):
The lottery number is 12
Sorry, no match
45
Enter your lottery pick:
The lottery number is 34
Match one digit: you win $1,000
23
The program generates a lottery using the random()method (line 6) and prompts the user to
enter a guess (line 11). Note that
guess% 10obtains the last digit from guess andguess / 10
obtains the first digit from guess, since guessis 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).
match one digit?
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 ifstatements were used. Overuse of nested
ifstatements makes a program difficult to read. Java provides a switch statement to handle
multiple conditions efficiently. You could write the following switchstatement 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 switchstatement is shown in Figure 3.5.
Compute tax for single filers
Compute tax for married file jointly
Compute tax for married file separately
Compute tax for head of household
Default actions
status is 0
status is 1
status is 2
status is 3
default
break
break
break
break
FIGURE 3.5 Theswitch 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) {
case value1: statement(s)1;
break;
switchstatement
94 Chapter 3 Selections
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
The switchstatement 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 breakstatement 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
Do not forget to use a breakstatement 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
switch statement is reached. This is referred to as fall-through behavior. For example, the fol-
lowing code prints character
athree times if ch is'a':
Á,
Á,
withoutbreak
fall-through behavior
true
ch is 'a'
ch is 'b'
ch is 'c'
false
true
false
false
true
System.out.println(ch)
System.out.println(ch)
System.out.println(ch)
switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}
Tip
To avoid programming errors and improve code maintainability, it is a good idea to put a com-
ment in a case clause if
breakis 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 1to y ifx is greater than 0, and -1to y ifx 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 expression1if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number between variable num1 andnum2 tomax.
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 numis
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 operatorbecause it uses three operands. It is the only ternar y 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);
:
?
conditional expression
x is 0.66
However, a better way to accomplish this task is to format the output using the printf
method. The syntax to invoke this method is
System.out.printf(format, item1, item2, ..., item
k
)
whereformat is a string that may consist of substrings and format specifiers.
printf
96 Chapter 3 Selections
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”
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
add spaces before the number. If the number of digits in the item is the width is
automatically increased.
7 5,
6 5,
%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 add spaces before the
number. If the number of digits before the decimal point in the item is the width is
automatically increased.
7 7,
6 7,
%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.
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.8lists some frequently used simple specifiers:
int count = 5;
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
Here is an example:
Items must match the specifiers in order, in number, and in exact type. For example, the
specifier for countis %d and for amountis %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.
3.18 Operator Precedence and Associativity 97
Caution
The items must match the specifiers in exact type. The item for the specifier %for %e must be a
floating-point type value such as 40.0, not 40. Thus an
intvariable 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 precedencerule defines precedence for operators, as shown in Table 3.10, which contains
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 associativitydetermines
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
precedence
associativity
left justify
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:
%
2
f
4 .
double x = 2.0 / 3;
System.out.printf("x is %4.2f", x);
display x is 0.67
field width
precision
conversion code
format specifier
By default, the output is right justified. You can put the minus sign (-) in the specifier to
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
J
3 4 1 2
vaa3 4 12
J v a a
8 characters
8 characters
. 65
. 65
a - b + c - d
equivalent
((a - b) + c) - d
98 Chapter 3 Selections
TABLE 3.10 Operator Precedence Chart
Precedence Operator
var++and var-- (Postfix)
+,- (Unary plus and minus), ++varand --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
a = b += c = 5
equivalent
a = (b += (c = 5))
Supposea, b, and c are 1 before the assignment; after the whole expression is evaluated, a
becomes 6, b becomes 6, and cbecomes 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-
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
showInputDialogto 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:
behind the scenes
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 Ye s 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)
(e)(d) (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;
2
3 public class GuessBirthdayUsingConfirmationDialog {
4 public static void main(String[] args) {
5
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
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
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
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
30 "16 17 18 19\n" +
31 "20 21 22 23\n" +
32 "24 25 26 27\n" +
33 "28 29 30 31";
34
String set5 =
String set4 =
String set3 =
String set2 =
String set1 =
import class
set1
set2
set3
set4
set5
100 Chapter 3 Selections
35 int day = 0;
36
37 // Prompt the user to answer questions
38
39
40
41
42 day += 1;
43
44 answer = JOptionPane.showConfirmDialog(null,
45 "Is your birthday in these numbers?\n" + set2);
46
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
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
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
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
if (answer == JOptionPane.YES_OPTION)
"Is your birthday in these numbers?\n" + set1);
int answer = JOptionPane.showConfirmDialog(null,
in set4?
in set5?
Boolean expression 72
Boolean value 72
booleantype 72
breakstatement 94
conditional operator 90
dangling-else ambiguity 82
fall-through behavior 94
operator associativity 97
operator precedence 97
selection statement 74
short-circuit evaluation 90
CHAPTER SUMMARY
1. A boolean variable stores a trueor false value.
2. The relational operators (<, <=, ==,!=, >, >=) work with numbers and characters, and
yield a Boolean value.
confirmation dialog
in set1?
in set2?
in set3?
Review Questions 101
3. The Boolean operators &&, ||, !, and ^ operate with Boolean values and variables.
4. When evaluating p1&& p2, Java first evaluates p1and then evaluates p2if p1 istrue;
if p1 isfalse, it does not evaluate p2. When evaluating p1 p2, Java first evaluates
p1and then evaluates p2 ifp1 isfalse; if p1 istrue, 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: ifstatements, if ... elsestatements, 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 orfalse 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
breakstatement 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 and35, respec-
tively?
ƒƒ
ƒƒ
if (number % 2 == 0)
System.out.println(number +
" is even.");
System.out.println(number +
" is odd.");
if (number % 2 == 0)
System.out.println(number +
" is even.");
else
System.out.println(number + " is odd.");
(a) (b)
3.4 Suppose x=3and y=2; show the output, if any, of the following code. What is
the output if x=3and y=4? What is the output if x=2andy=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
(j > 0)
x = 0; else
if (k > 0) y = 0;
else z = 0;
(a) (b)
if (i > 0) {
if (j > 0)
x = 0;
else if (k > 0)
y = 0;
}
else
z = 0;
if (i > 0)
if (j > 0)
x = 0;
else if (k > 0)
y = 0;
else
z = 0;
(c) (d)
if (i > 0)
if (j > 0)
x = 0;
else if (k > 0)
y = 0;
else
z = 0;
3.6 Suppose x=2and y=3. Show the output, if any, of the following code. What is
the output if x=3and y=2? What is the output if x=3andy=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)
tax = income * 0.1;
else if (income <= 20000)
tax = 1000 +
(income – 10000) * 0.15;
if (income <= 10000)
tax = income * 0.1;
else if (income > 10000 &&
income <= 20000)
tax = 1000 +
(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 How
do you generate a random integer i such that How do
you generate a random integer
isuch that
3.10 Write an ifstatement that assigns 1 tox ify is greater than 0.
3.11 (a) Write an ifstatement that increases pay by 3% if scoreis greater
than 90. (b) Write an if statement that increases payby 3% if score
is greater than 90, otherwise increases pay by 1%.
10 i 50?
10 i 6 20?
0 i 6 20?
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 xis 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 trueif a number stored in variable
num is between 1and 100.
3.16 Write a Boolean expression that evaluates to trueif a number stored in variable
num is between 1and 100 or the number is negative.
3.17 Assume that xand y areint 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 xis 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' ifch is'A', 'p',
'E', or '5'?
3.20 Suppose, when you run the program, you enter input 236from 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 trueif age is greater than 13and less
than 18.
3.22 Write a Boolean expression that evaluates trueif weight is greater than 50 or
height is greater than 160.
3.23 Write a Boolean expression that evaluates trueif weight is greater than 50and
height is greater than 160.
3.24 Write a Boolean expression that evaluates trueif 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 switchvariable? If the keyword break is not
used after a case is processed, what is the next statement to be executed? Can you
convert a switchstatement to an equivalent if statement, or vice versa? What are
the advantages of using a switchstatement?
3.26 What is yafter the following switch statement is executed?
x= 3; y = 3;
switch (x + 3) {
case 6: y = 1;
default: y += 1;
}
3.27 Use a switchstatement to rewrite the following if statement and draw the flow
chart for the switchstatement:
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 switchstatement that assigns a String variable dayNamewith Sunday,
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, if dayis 0, 1, 2, 3, 4,
5, 6, accordingly.
Section 3.16
3.29 Rewrite the following ifstatement 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
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-
ging your own mistakes.
Section 3.2
3.1* (Algebra: solving quadratic equations) The two roots of a quadratic equation
can be obtained using the following formula:
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 Here are some sample
runs.
1x.
b
2
- 4ac
r
1
=
-b + 2b
2
- 4ac
2a
and r
2
=
-b - 2b
2
- 4ac
2a
ax
2
+ bx + c = 0
document analysis and design
learn from mistakes
Enter a, b, c:
The roots are -0.381966 and -2.61803
1.0 3 1
Enter a, b, c:
The root is -1
1 2.0 1
Enter a, b, c:
The equation has no real roots
1 2 3
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:
Is 25 an even number? false
25
Enter an integer:
Is 2000 an even number? true
2000
Programming Exercises 107
Sections 3.3–3.8
3.3* (Algebra: solving linear equations) You can use Cramer’s rule to solve the
following system of linear equation:
Write a program that prompts the user to enter a, b, c, d, e, and f and display the
result. If is 0, report that “The equation has no solution”.ad - bc
ax + by = e
cx + dy = f
x =
ed - bf
ad - bc
y =
af - ec
ad - bc
2 * 2
2 * 2
Enter a, b, c, d, e, f:
x is -2.0 and y is 3.0
9.0 4.0 3.0 -5.0 -6.0 -21.0
Enter a, b, c, d, e, f:
The equation has no solution
1.0 2.0 2.0 4.0 4.0 5.0
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 5feet and 10 inches, you
will enter 5for 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 1dollar and 1 penny, and plural words for more than one unit such as 2dol-
lars and 3pennies. (Use input 23.67 to test your program.)
3.8* (Sorting three integers) Write a program that sorts three integers. The integers are
entered from the input dialogs and stored in variables num1, num2, and num3,
respectively. The program sorts the numbers so that
3.9 (Business: checking ISBN) An ISBN (International Standard Book Number) con-
sists of 10 digits The last digit is a checksum, which
is calculated from the other nine digits using the following formula:
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.
d
6
* 6 + d
7
* 7 + d
8
* 8 + d
9
* 92 % 11
1d
1
* 1 + d
2
* 2 + d
3
* 3 + d
4
* 4 + d
5
* 5 +
d
10
d
1
d
2
d
3
d
4
d
5
d
6
d
7
d
8
d
9
d
10
.
num1 num2 num3.
Video Note
Sort three integers
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 2and 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 5and 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 or1, 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):
The computer is scissor. You are rock. You won
1
scissor (0), rock (1), paper (2):
The computer is paper. You are paper too. It is a draw
2
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 year: (e.g., 2008):
Enter month: 1-12:
Enter the day of the month: 1-31:
Day of the week is Tuesday
26
3
2002
Enter year: (e.g., 2008):
Enter month: 1-12:
Enter the day of the month: 1-31:
Day of the week is Thursday
2
5
2011
(Hint: for a positive n. January and February are counted as 13 and
14 in the formula. So you need to convert the user input 1to 13 and2 to14 for
the month and change the year to the previous year.)
:n; = 1int2n
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
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
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.
mis the month (3: March, 4: April, 12: December). January and February
are counted as months 13 and 14 of the previous year.
j is the century (i.e., ).
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:
j
year
100
k
Á,
h = aq +
j
261m + 12
10
k
+ k +
j
k
4
k
+
j
j
4
k
+ 5jb % 7
-58°F
Enter three edges:
Can edges 1, 2.5, and 1 form a triangle? false
1 2.5 1
Enter three edges:
Can edges 2.5, 2, and 1 form a triangle? true
2.5 2 1
110 Chapter 3 Selections
Enter a point with two coordinates:
Point (4.0, 5.0) is in the circle
4 5
Enter a point with two coordinates:
Point (9.0, 9.0) is not in the circle
9 9
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 10and 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/ 2and 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:
Point (2.0, 2.0) is in the rectangle
2 2
Enter a point with two coordinates:
Point (6.0, 4.0) is not in the rectangle
6 4
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:
x-axis
(0, 0)
(a) (b)
y-axis
(4, 5)
(9, 9)
(2, 2)
(6, 4)
x-axis
y-axis
(0, 0)
FIGURE3.7 (a) Points inside and outside of the circle; (b) Points inside and outside of the
rectangle.
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 ) Two sample
runs are shown below.)
21x
2
- x
1
2
2
+ 1y
2
- y
1
2
2
.
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:
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
10
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:
Enter a point’s x- and y-coordinates:
The point is in the triangle
100.5 25.5
Enter a point’s x- and y-coordinates:
The point is not in the triangle
100.5 50.5
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.
(a)
w1
(x1,y1)
(x2,y2)
w2
h2
h1
(b)
w1
(x1,y1)
(x2,y2)
w2
h2
h1
FIGURE 3.8 (a) A rectangle is inside another one. (b) A rectangle overlaps another one.
(0, 100)
(0, 0) (200, 0)
p2
p1
112 Chapter 3 Selections
Here are the sample runs:
Enter r1’s center x-, y-coordinates, width, and height:
Enter r2’s center x-, y-coordinates, width, and height:
r2 is inside r1
1.5 5 0.5 3
2.5 4 2.5 43
Enter r1’s center x-, y-coordinates, width, and height:
Enter r2’s center x-, y-coordinates, width, and height:
r2 overlaps r1
3 4 4.5 5
1 2 3 5.5
Enter r1’s center x-, y-coordinates, width, and height:
Enter r2’s center x-, y-coordinates, width, and height:
r2 does not overlap r1
40 45 3 2
1 2 3 3
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 |r1 -r2|
and circle2 overlaps circle1 if the distance between the two centers r1 +r2.)6=
6=
(a) (b)
(x1,y1)
(x2,y2)
r2
r1
(x1,y1)
r1
(x2,y2)
r2
FIGURE3.9 (a) A circle is inside another circle. (b) A circle overlaps another circle.
Enter circle1’s center x-, y-coordinates, and radius:
Enter circle2’s center x-, y-coordinates, and radius:
circle2 is inside circle1
1 1.7 4.5
0.5 5.1 13
Here are the sample runs:
Programming Exercises 113
Enter circle1’s center x-, y-coordinates, and radius:
Enter circle2’s center x-, y-coordinates, and radius:
circle2 overlaps circle1
6.7 3.5 3
3.4 5.7 5.5
Enter circle1’s center x-, y-coordinates, and radius:
Enter circle2’s center x-, y-coordinates, and radius:
circle2 does not overlap circle1
5.5 7.2 1
3.4 5.5 1
This page intentionally left blank
LOOPS
CHAPTER 4
Objectives
To write programs for executing statements repeatedly using a whileloop (§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-whilestatements (§4.3).
To write loops using forstatements (§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).