Java Programs To Accompany Programming Logic and Design 7th Edition Jo Ann Smith All Chapters Instant Download
Java Programs To Accompany Programming Logic and Design 7th Edition Jo Ann Smith All Chapters Instant Download
https://ebookultra.com/download/microsoft-visual-basic-programs-to-
accompany-programming-logic-and-design-3rd-edition-jo-ann-smith/
ebookultra.com
https://ebookultra.com/download/java-programming-7th-edition-joyce-
farrell/
ebookultra.com
https://ebookultra.com/download/programming-logic-and-design-
comprehensive-6th-edition-joyce-farrell/
ebookultra.com
https://ebookultra.com/download/java-tm-programming-from-problem-
analysis-to-program-design-5th-edition-d-s-malik/
ebookultra.com
Java the UML way integrating object oriented design and
programming Else Lervik
https://ebookultra.com/download/java-the-uml-way-integrating-object-
oriented-design-and-programming-else-lervik/
ebookultra.com
https://ebookultra.com/download/laboratory-explorations-to-accompany-
microelectronic-circuits-7th-edition-vincent-c-gaudet/
ebookultra.com
https://ebookultra.com/download/building-java-programs-a-back-to-
basics-approach-3rd-edition-stuart-reges/
ebookultra.com
https://ebookultra.com/download/student-solutions-manual-to-accompany-
complex-variables-and-applications-7th-edition-james-ward-brown/
ebookultra.com
https://ebookultra.com/download/introduction-to-programming-with-
java-3rd-edition-john-dean/
ebookultra.com
Java Programs to Accompany Programming Logic and
Design 7th Edition Jo Ann Smith Digital Instant
Download
Author(s): Jo Ann Smith
ISBN(s): 9781133526063, 1133526063
Edition: 7
File Details: PDF, 4.14 MB
Year: 2012
Language: english
SEVENTH EDITION
JAVA™ PROGRAMS
TO ACCOMPANY
PROGRAMMING LOGIC
AND DESIGN
BY JO ANN SMITH
Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
This is an electronic version of the print textbook. Due to electronic rights restrictions, some third party content may be suppressed. Editorial
review has deemed that any suppressed content does not materially affect the overall learning experience. The publisher reserves the right to
remove content from this title at any time if subsequent rights restrictions require it. For valuable information on pricing, previous
editions, changes to current editions, and alternate formats, please visit www.cengage.com/highered to search by
ISBN#, author, title, or keyword for materials in your areas of interest
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Java Programs to Accompany Programming © 2013 Course Technology, Cengage Learning
Logic and Design, Seventh Edition
ALL RIGHTS RESERVED. No part of this work covered by the copyright
Jo Ann Smith
herein may be reproduced, transmitted, stored, or used in any form or by
Executive Editor: Marie Lee any means graphic, electronic, or mechanical, including but not limited to
photocopying, recording, scanning, digitizing, taping, Web distribution,
Acquisitions Editor: Brandi Shailer
information networks, or information storage and retrieval systems, except
Senior Product Manager: Alyssa Pratt as permitted under Section 107 or 108 of the 1976 United States Copyright
Senior Content Project Manager: Act, without the prior written permission of the publisher.
Cathie DiMassa
Art Director: Faith Brosnan For product information and technology assistance, contact us at
Cengage Learning Customer & Sales Support, cengage.com/support
Compositor: Integra Software Services
For permission to use material from this text or product,
Cover Designer: Lisa Kuhn/Curio Press, LLC submit all requests online at www.cengage.com/permissions
HYPERLINK “http://www.curiopress.com/” Further permissions questions can be e-mailed to
www.curiopress.com [email protected]
Image credit: © Leigh Prather/Veer
Library of Congress Control Number: 2012931579
ISBN-13: 978-1-133-52606-3
ISBN-10: 1-133-52606-3
Course Technology
20 Channel Center Street
Boston, MA 02210
USA
Cengage Learning is a leading provider of customized learning solutions
with office locations around the globe, including Singapore, the United
Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at:
international.cengage.com/region
Cengage Learning products are represented in Canada by
Nelson Education, Ltd.
For your lifelong learning solutions, visit course.cengage.com
Visit our corporate Web site at cengage.com.
Some of the product names and company names used in this book have
been used for identification purposes only and may be trademarks or
registered trademarks of their respective manufacturers and sellers.
Any fictional data related to persons or companies or URLs used
throughout this book is intended for instructional purposes only. At the
time this book was printed, any such data was fictional and not belonging
to any real persons or companies.
Course Technology, a part of Cengage Learning, reserves the right to revise
this publication and make changes from time to time in its content without
notice.
The programs in this book are for instructional purposes only.
They have been tested with care, but are not guaranteed for any particular
intent beyond educational purposes. The author and the publisher do not
offer any warranties or representations, nor do they accept any liabilities
with respect to the programs.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Brief Contents
iii
Pref ace . . . . . . . . . . . . . . . . . ix
CHAPTER 1 An In t ro ducti on to Jav a and the
J ava Pro grammi ng Env i ronment . . . . . . . 1
CHAPTER 2 Var iables, Constants, Operators,
an d Wr it i ng Programs Usi ng Sequenti al
St at em ents . . . . . . . . . . . . . . . . 13
CHAPTER 3 Wr it in g Structured Jav a Programs . . . . . . 33
CHAPTER 4 Wr it in g Programs that Make Deci si ons . . . . 48
CHAPTER 5 Wr it in g Programs Usi ng Loops . . . . . . . 75
CHAPTER 6 U s in g Ar ray s i n Jav a Programs . . . . . . 101
CHAPTER 7 F ile Han dl i ng and Appl i cati ons . . . . . . 118
CHAPTER 8 Advan ced Array Techni ques . . . . . . . . 135
CHAPTER 9 Advan ced Modul ari zati on Techni ques . . . . 152
CHAPTER 10 Addit io n al Topi cs . . . . . . . . . . . . 180
In dex . . . . . . . . . . . . . . . . . 197
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Contents
iv
Pref ace . . . . . . . . . . . . . . . . . ix
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CONTENTS
In dex . . . . . . . . . . . . . . . . . 197
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface
ix
Programming Logic
Java PAL, Seventh Edition and Design, Seventh Edition
Chapter 1: An Introduction to Chapter 1: An Overview of
Java and the Java Programming Computers and Logic
Environment
Chapter 2: Variables, Constants, Chapter 2: Working with Data,
Operators, and Writing Programs Creating Modules, and Designing
Using Sequential Statements High-Quality Programs
Chapter 3: Understanding Structure
Chapter 3: Writing Structured Java Chapter 2: Working with Data,
Programs Creating Modules, and Designing
High-Quality Programs
Chapter 3: Understanding Structure
(continues)
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
P R E FA C E
(continued)
Programming Logic
Java PAL, Seventh Edition and Design, Seventh Edition
Chapter 4: Writing Programs That Chapter 4: Making Decisions
Make Decisions
x Chapter 5: Writing Programs Using Chapter 5: Looping
Loops
Chapter 6: Using Arrays in Java Chapter 6: Arrays
Programs
Chapter 7: File Handling and Chapter 7: File Handling and
Applications Applications
Chapter 8: Advanced Array Chapter 8: Advanced Array Concepts,
Techniques Indexed Files, and Linked Lists
Chapter 9: Advanced Modularization Chapter 9: Advanced Modularization
Techniques Techniques
Chapter 10: Additional Topics Chapter 10: Object-Oriented
Programming
Chapter 11: More Object-Oriented
Programming Concepts
Chapter 12: Event Driven GUI
Programming, Multithreading,
and Animation
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
P R E FA C E
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
P R E FA C E
Acknowledgments
I would like to thank all the people who helped to make this book
possible. Thanks to Alyssa Pratt, Senior Product Manager, and Brandi
Shailer, Acquisitions Editor, for their help and encouragement. I am
grateful to Cathie DiMassa, Senior Content Project Manager, Serge
Palladino, Quality Assurance, and Sreemannarayana Reddy Syakam,
of Integra Software Services, for overseeing the production of the
printed book. It is a pleasure to work with so many fine people who
are dedicated to producing quality instructional materials.
I am dedicating this book to my husband, Ray, our son, Tim, and our
grandson, William.
Jo Ann Smith
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Read This Before
You Begin xiii
To the User
Data Files
To complete most of the lab exercises, you will need data files that
have been created for this book. Your instructor can provide the data
files. You can also obtain the files electronically from the publisher at
www.CengageBrain.com (search under the ISBN for this book), and
then searching for this book title.
You can use a computer in your school lab or your own computer to
complete the lab exercises in this book.
Solutions
Solutions to the Exercises and Labs are provided to instructors on the
Course Technology Web site at login.cengage.com. The solutions are
password protected.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
R E A D T HRI SE B
AEDF O
TRHEI SY OBUEBFEOGRI N
E
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
RR
EAED
ATDH T
I SHBI E
SF O
BREE
FOYO
R UE B E G I N
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
R E A D T HRI SE B
AEDF O
TRHEI SY OBUEBFEOGRI N
E
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
RR
EAED
ATDH T
I SHBI E
SF O
BREE
FOYO
R UE B E G I N
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
R E A D T HRI SE B
AEDF O
TRHEI SY OBUEBFEOGRI N
E
To the Instructor
To complete some of the Exercises and Labs in this book, your
students must use the data files provided with this book. These files
are available from the publisher at www.CengageBrain.com (search
under the ISBN for this book). Follow the instructions in the Help file
to copy the data files to your server or stand-alone computer. You can
view the Help file using a text editor such as WordPad or Notepad.
Once the files are copied, you may instruct your students to copy the
files to their own computers or workstations.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
An Introduction
CHAPTER 1
to Java and the
Java Programming
Environment
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 An Introduction to Java and the Java Programming Environment
You should do the exercises and labs in this chapter only after you
have finished Chapter 1 of your book, Programming Logic and Design,
Seventh Edition, by Joyce Farrell. This chapter introduces the Java
programming language and its history. It explains some introductory
object-oriented concepts, describes the process of compiling and
executing a Java program, and explains how to download the Java
2
Standard Edition Development Kit (JDK). You begin writing Java pro-
grams in Chapter 2 of this book.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
An Introduction to Object-Oriented Terminology
An Introduction to Object-Oriented 3
Terminology
You must understand a few object-oriented concepts to be successful
at reading and working with Java programs in this book. Note, how-
ever, that you will not learn enough to make you a Java programmer.
You will have to take additional courses in Java to become a Java pro-
grammer. This book teaches you only the basics.
To fully understand the term object-oriented, you need to know a
little about procedural programming. Procedural programming is
a style of programming that is older than object-oriented program-
ming. Procedural programs consist of statements that the computer
runs or executes. Many of the statements make calls (a request to
run or execute) to groups of other statements that are known as
procedures, modules, methods, or subroutines. These programs are
known as “procedural” because they perform a sequence of proce-
dures. Procedural programming focuses on writing code that takes
some data (for example, some sales figures), performs a specific task
using the data (for example, adding up the sales figures), and then
produces output (for example, a sales report). When people who use
procedural programs (the users) decide that they want their pro-
grams to do something slightly different, a programmer must revise
the program code, taking great care not to introduce errors into the
logic of the program.
Today, we need computer programs that are flexible and easy to
revise. Object-oriented programming languages, including Java, were
introduced to meet this need. In object-oriented programming, the
programmer can focus on the data that he or she wants to manipu-
late, rather than the individual lines of code required to manipulate
that data (although those individual lines still must be written even-
tually). An object-oriented program is made up of a collection of
interacting objects.
An object represents something in the real world, such as a car, an
employee, or an item in an inventory. An object includes (or encap-
sulates) both the data related to the object and the tasks you can
perform on that data. The term behavior is sometimes used to refer
to the tasks you can perform on an object’s data. For example, the
data for an inventory object might include a list of inventory items,
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 An Introduction to Java and the Java Programming Environment
the number of each item in stock, the number of days each item has
been in stock, and so on. The behaviors of the inventory object might
include calculations that add up the total number of items in stock
and calculations that determine the average amount of time each item
remains in inventory.
4 In object-oriented programming, the data items within an object are
known collectively as the object’s attributes. You can think of an
attribute as one of the characteristics of an object, such as its shape,
its color, or its name. The tasks the object performs on that data are
known as the object’s methods. (You can also think of a method as
an object’s behavior.) Because methods are built into objects, when
you create a Java program, you don’t always have to write multiple
lines of code telling the program exactly how to manipulate the
object’s data. Instead, you can write a shorter line of code, known as a
call, that passes a message to the method indicating that you need it
to do something.
For example, you can display dialog boxes, scroll bars, and buttons for
a user of your program to type in or click on simply by sending a mes-
sage to an existing object. At other times, you will be responsible for
creating your own classes and writing the code for the methods that
are part of that class. Whether you use existing, prewritten classes or
create your own classes, one of your main jobs as a Java programmer
is to communicate with the various objects in a program (and the
methods of those objects) by passing messages. Individual objects in a
program can also pass messages to other objects.
When Java programmers begin to write a program, they must begin
by creating a class. A class can be thought of as a template for a
group of similar objects. In a class, the programmer specifies the data
(attributes) and behaviors (methods) for all objects that belong to that
class. An object is sometimes referred to as an instance of a class,
and the process of creating an object is referred to as instantiation.
To understand the terms class, instance, and instantiation, it’s help-
ful to think of them in terms of a real-world example—baking a
chocolate cake. The recipe is similar to a class, and an actual cake is
an object. If you wanted to, you could create many chocolate cakes
that are all based on the same recipe. For example, your mother’s
birthday cake, your sister’s anniversary cake, and the cake for your
neighborhood bake sale all might be based on a single recipe that
contains the same data (ingredients) and methods (instructions). In
object-oriented programming, you can create as many objects as you
need in your program from the same class.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
The Structure of a Java Program
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 An Introduction to Java and the Java Programming Environment
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
The Java Development Cycle
System.out.println("Hello World.");
This is the line that causes the words “Hello World.” to appear on
the user’s screen. This line consists of two parts. The first part,
System.out.println();, prints (that is, displays on the screen) what-
ever is included within its parentheses. In this example, the parentheses
contain the message “Hello World.” so that is what will appear on the 7
screen. (The quotation marks will not appear on the screen, but they are
necessary to make the program work.) Note that the semicolon that ends
the System.out.println("Hello World."); statement is required
because it tells the compiler that this is the end of the statement.
In the statement System.out.println("Hello World.");, System
is a class, out is an object, and println() is a method. Java programs
frequently use this class-dot-object-dot-method syntax.
Next, you learn about the Java development cycle so that later in this
chapter, you can compile the Hello World program and execute it.
The Hello World program is saved in a file named HelloWorld.java
and is included in the student files for this chapter.
Step 1 Step 2
Write Java Source code file Compile
source code (MyClass.java) source code
(Notepad) (javac MyClass.java)
Java bytecode
(MyClass.class)
Step 3
Execute the
program
(java MyClass)
Output
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 An Introduction to Java and the Java Programming Environment
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
The Java Development Cycle
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 An Introduction to Java and the Java Programming Environment
6. After the program is compiled, you can use the dir com-
At this point in mand to display a directory listing to see the file named
your program- HelloWorld.class. To execute the dir command, you type
ming career, dir at the command prompt. For example, if your source
don’t expect
code file is located at C:\My Program\Testing, the command
to understand
the contents of a .class
prompt and dir command should look like this:
10
file if you open one using C:\My Program\Testing>dir. The HelloWorld.class
a text editor such as file should be in the same directory as the source code file,
Notepad. HelloWorld.java.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
The Java Development Cycle
11
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 1 An Introduction to Java and the Java Programming Environment
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Variables, Constants,
CHAPTER 2
Operators, and
Writing Programs
Using Sequential
Statements
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 2 Variables, Constants, Operators, and Sequential Statements
In this chapter, you learn about writing programs that use variables,
constants, and arithmetic operators, and that receive interactive
input from a user of your programs. We begin by reviewing variables
and constants and learning how to use them in a Java program. You
should do the exercises and labs in this chapter only after you have
finished Chapters 2 and 3 of your book, Programming Logic and
14
Design, Seventh Edition, by Joyce Farrell.
Variables
As you know, a variable is a named location in the computer’s
memory whose contents can vary (thus the term variable). You use
a variable in a program when you need to store values. The values
stored in variables often change as a program executes.
In Java, you must declare variables before you can use them in a
program. Declaring a variable is a two-part process: first you give
the variable a name, and then you specify its data type. You’ll learn
about data types shortly. But first, we’ll focus on the rules for naming
variables in Java.
Variable Names
A variable is Variable names in Java can consist of letters, numerical digits, a dollar
sometimes sign, and the underscore character, but they cannot begin with a digit.
referred to as
an identifier. You cannot use a Java keyword for a variable name. As you learned in
Chapter 1 of this book, a keyword is a word with a special meaning
in Java. The following are all examples of legal variable names in Java:
my_var, num6, intValue, and frstName. Table 2-1 lists some examples
of invalid variable names, and explains why each is invalid.
By convention,
Name of Variable Explanation
variable
names in Java 3wrong Invalid because it begins with a digit
begin with a $don’t Invalid because it contains a single quotation mark
lowercase
public Invalid because it is a Java keyword
letter; all other words in
the name begin with an Table 2-1 Invalid variable names
uppercase letter—for
example, frstName.
You cannot include When naming variables, keep in mind that Java is case sensitive—
spaces between the in other words, Java knows the difference between uppercase and
words in a variable name. lowercase characters. Tha t means value, Value, and VaLuE are three
different variable names in Java.
In Java, variable names can be as long as you want. A good rule is to
give variables meaningful names that are long enough to describe
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Variables
how the variable is used, but not so long that you make your program
hard to read or cause yourself unnecessary typing. For example, a
variable named frstName will clearly be used to store someone’s first
name. The variable name freshmanStudentFirstName is descriptive
but inconveniently long; the variable name fn is too short and not
meaningful.
15
The int and double data types will be adequate for all the numeric
variables you will use in this book. But what about when you need to
store a group of characters (such as a person’s name) in a variable?
In programming, we refer to a group of one or more characters as a
string. An example of a string is the last name “Wallace” or a product
type such as a “desk”. There is no primitive data type in Java for stor-
ing strings; instead, they are stored in an object known as a String
object. In addition to working with the int and double data types in
this book, you will also work with Strings.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 2 Variables, Constants, Operators, and Sequential Statements
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Declaring and Initializing Variables
int counter;
You can also initialize a Java variable when you declare it. When you Numeric
initialize a Java variable, you give it an initial value. For example, variables are
automatically
you can assign an initial value of 8 to the counter variable when you
initialized to
declare it, as shown in the following code: zero (0),
int counter = 8; unless you specify a
different value.
You can also declare and initialize variables of data type double and
String variables as shown in the following code:
double salary;
double cost = 12.95;
String frstName;
String homeAddress = "123 Main Street";
You can declare more than one variable in one statement as long as
they have the same data type. For example, the following statement
declares two variables, named counter and value. Both variables are
of the int data type.
int counter, value;
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 2 Variables, Constants, Operators, and Sequential Statements
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Constants
Constants
As you know, a constant is a value that never changes. In Java, you
can use both unnamed constants as well as named constants in a
program. You’ll learn about named constants shortly. But first, we’ll
focus on unnamed constants.
19
Unnamed Constants
Computers are able to deal with two basic types of data: text and
numeric. When you use a specific numeric value, such as 35, in a
program, you write it using the numbers, without quotation marks.
A specific numeric value is called a numeric constant because it
does not change; a 35 always has the value 35. When you use a spe-
cific text value, or string of characters, such as “William,” you enclose
the string constant in double quotation marks. Both of the preced-
ing examples, 35 and “William,” are examples of unnamed constants
because they do not have specified names as variables do.
Named Constants
In addition to variables, Java allows you to create named constants. A
named constant is similar to a variable, except it can be assigned a
value only once. You use a named constant when you want to assign a
name to a value that will never be changed when a program executes.
By convention,
To declare a named constant in Java, you use the keyword fnal, fol- in Java the
lowed by the data type, followed by the name of the constant. Named names of
constants must be initialized when they are declared, and their con- constants are
tents may not be changed during the execution of the program. For written in all
example, the following statement declares an int constant named uppercase letters. This
makes it easier for you to
MAX_STUDENTS and initializes MAX_STUDENTS with the value 35.
spot named constants in
fnal int MAX_STUDENTS = 35; a long block of code.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 2 Variables, Constants, Operators, and Sequential Statements
5. Save this source code file in a directory of your choice, and then
make that directory your working directory.
6. Compile the source code file NewAge2.java.
7. Execute the program. Record the output of this program.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Arithmetic and Assignment Operators
Arithmetic Operators
Arithmetic operators are the symbols used to perform arithmetic
calculations. You are probably already very familiar with the arithme-
tic operators for addition (+) and subtraction (−). Table 2-2 lists and
explains Java’s arithmetic operators.
21
Operator Name
and Symbol Example Comment
Addition + num1 + num2
Subtraction − num1 − num2
Multiplication * num1 * num2
Division / 15/2 Integer division; result is 7; fraction is truncated
15.0 / 2.0 Floating-point division; result is 7.5
15.0 / 2 Floating-point division because one of the operands is
a floating-point number; result is 7.5
Modulus % hours % 24 Performs division and finds the remainder; result is 1
if the value of hours is 25
Unary plus + +num1 Maintains the value of the expression; if the value of
num1 is 3, then +num1 is 3
Unary minus − −(num1 − num2) If value of (num1 − num2) is 10, then
−(num1 − num2) is −10
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 2 Variables, Constants, Operators, and Sequential Statements
Operator Name
and Symbol Example Comment
Assignment = count = 5; Places the value on the right side into the memory
location named on the left side.
Initialization = int count = 5; Places the value on the right side into the memory
location named on the left side when the variable
is declared.
Assignment += num += 20; Equivalent to num = num + 20;
Assignment −= num −= 20; Equivalent to num = num − 20;
Assignment *= num *= 20; Equivalent to num = num * 20;
Assignment /= num /= 20; Equivalent to num = num / 20;
Assignment %= num %= 20; Equivalent to num = num % 20;
Table 2-4 Java assignment operators
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Arithmetic and Assignment Operators
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
CHAPTER 2 Variables, Constants, Operators, and Sequential Statements
As you can see in Table 2-5, the parentheses operator, ( ), has the
highest precedence. You use this operator to change the order in
which operations are performed. Note the following example:
average = test1 + test2 / 2;
The task of this statement is to find the average of two test scores. The
24 way this statement is currently written, the compiler will divide the value
in the test2 variable by 2, and then add it to the value in the test1 vari-
able. So, for example, if the value of test1 is 90 and the value of test2
is 88, then the value assigned to average will be 134, which is obviously
not the correct average of these two test scores. By using the parenthe-
ses operator in this example, you can force the addition to occur before
the division. The correct statement looks like this:
average = (test1 + test2) / 2;
In this example, the value of test1, 90, is added to the value of test2,
88, and then the sum is divided by 2. The value assigned to average,
89, is the correct result.
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Arithmetic and Assignment Operators
Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has
deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Discovering Diverse Content Through
Random Scribd Documents
passions et par la vie du monde. Et en cet instant même, avec le
psalmiste, elles chantent pour la désolée :
« Pourquoi vous lever avant la lumière ? Levez-vous après avoir
goûté le repos, vous qui mangez le pain de la douleur !… »
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookultra.com