Java Programming, 9th ed. http://www.a-pdf.com/?tr-demo http://www.a-pdf.com/?tr-demo http://www.a-pdf.com/?tr-demo JAVA™ PROGRAMMING JOYCE FARRELL Australia • Brazil • Mexico • Singapore • United...

1 answer below »

all instructions are in the PDF, i do have a textbook to send but can't seem to attach a 2nd file to this???


1. i need instructions on how to set up on my end as far as where to store anything if there is set up involved on my end how to set up in my ide Intellij


2. code needs to be commented.




Java Programming, 9th ed. http://www.a-pdf.com/?tr-demo http://www.a-pdf.com/?tr-demo http://www.a-pdf.com/?tr-demo JAVA™ PROGRAMMING JOYCE FARRELL Australia • Brazil • Mexico • Singapore • United Kingdom • United States N I N T H E d I T I o N 97070_fm_hr_i-xxiv.indd 1 27/02/18 7:34 pm 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. Important Notice: Media content referenced within the product description or the product text may not be available in the eBook version. Java™ Programming, Ninth Edition Joyce Farrell SVP, GM Skills: Jonathan Lau Product Team Manager: Kristin McNary Associate Product Manager: Kate Mason Executive Director of Content Design, Skills: Marah Bellegarde Director, Learning Design – Skills Computing: Leigh Hefferon Learning Designer: Natalie Onderdonk Product Assistant: Jake Toth Marketing Director: Michele McTighe Marketing Manager: Stephanie Albracht Content Project Manager: Michele Stulga Senior Designer: Diana Graham Production Service/Composition: SPi Global Cover image: Colormos/Photodisc /Getty Images © 2019, 2016, 2014, 2012 Cengage Learning, Inc. Unless otherwise noted, all content is © Cengage. ALL RIGHTS RESERVED. No part of this work covered by the copyright herein may be reproduced or distributed in any form or by any means, except as permitted by U.S. copyright law, without the prior written permission of the copyright owner. Unless otherwise noted all screenshots are courtesy of Microsoft Corporation. Unless otherwise noted all tables/figures exhibits are © 2019 Cengage®. For product information and technology assistance, contact us at Cengage Customer & Sales Support, 1-800-354-9706 or support.cengage.com. For permission to use material from this text or product, submit all requests online at www.cengage.com/permissions. Library of Congress Control Number: 2018933919 Softbound ISBN: 978-1-337-39707-0 Loose Leaf ISBN: 978-1-337-68590-0 Cengage 20 Channel Center Street Boston, MA 02210 USA Cengage is a leading provider of customized learning solutions with employees residing in nearly 40 different countries and sales in more than 125 countries around the world. Find your local representative at www.cengage.com. Cengage products are represented in Canada by Nelson Education, Ltd. To learn more about Cengage platforms and services, visit www.cengage.com. To register or access your online learning solution or purchase materials for your course, visit www.cengagebrain.com. Notice to the Reader Publisher does not warrant or guarantee any of the products described herein or perform any independent analysis in connection with any of the product information contained herein. Publisher does not assume, and expressly disclaims, any obligation to obtain and include information other than that provided to it by the manufacturer. The reader is expressly warned to consider and adopt all safety precautions that might be indicated by the activities described herein and to avoid all potential hazards. By following the instructions contained herein, the reader willingly assumes all risks in connection with such instructions. The publisher makes no representations or warranties of any kind, including but not limited to, the warranties of fitness for particular purpose or merchantability, nor are any such representations implied with respect to the material set forth herein, and the publisher takes no responsibility with respect to such material. The publisher shall not be liable for any special, consequential, or exemplary damages resulting, in whole or part, from the readers’ use of, or reliance upon, this material. Printed in the United States of America Print Number: 01 Print Year: 2018 97070_fm_hr_i-xxiv.indd 2 27/02/18 7:34 pm Brief Contents Preface � � � � � � � � � � � � � � � � xiv CHAPTER 1 Creat ing Java Programs � � � � � � � � � � 1 CHAPTER 2 Us ing Data � � � � � � � � � � � � � � � � 49 CHAPTER 3 Us ing Methods, Classes, and Objects � � � 110 CHAPTER 4 More Object Concepts � � � � � � � � � � 170 CHAPTER 5 Making Decis ions � � � � � � � � � � � � 230 CHAPTER 6 Looping � � � � � � � � � � � � � � � � 283 CHAPTER 7 Characters, Str ings, and the StringBuilder � � � � � � � � � � � � � 330 CHAPTER 8 Arrays � � � � � � � � � � � � � � � � � 369 CHAPTER 9 Advanced Array Concepts � � � � � � � � 416 CHAPTER 10 Introduct ion to Inher i tance � � � � � � � � 467 CHAPTER 11 Advanced Inher i tance Concepts � � � � � � 513 CHAPTER 12 Except ion Handl ing � � � � � � � � � � � 570 CHAPTER 13 F i le Input and Output � � � � � � � � � � � 635 CHAPTER 14 Introduct ion to Swing Components � � � � 698 CHAPTER 15 Us ing JavaFX and Scene Bui lder � � � � � � 758 APPENdIx A Work ing wi th the Java Plat form � � � � � � 799 APPENdIx B Data Representat ion � � � � � � � � � � � 804 APPENdIx C Formatt ing Output � � � � � � � � � � � � 810 APPENdIx d Generat ing Random Numbers � � � � � � � 820 APPENdIx E Javadoc � � � � � � � � � � � � � � � � 826 G lossary � � � � � � � � � � � � � � � � 834 Index � � � � � � � � � � � � � � � � � 853 iii 97070_fm_hr_i-xxiv.indd 3 27/02/18 7:34 pm 97070_fm_hr_i-xxiv.indd 4 27/02/18 7:34 pm Table of Contents Preface � � � � � � � � � � � � � � � � xiv CHAPTER 1 Creat ing Java Programs � � � � � � � � � � 1 Learning Programming Terminology � � � � � � � � � � � � � 2 Comparing Procedural and Object-Oriented Programming Concepts � � � � � � � � � � � � � � � � � � 5 Procedural Programming � � � � � � � � � � � � � � � � � 5 Object-Oriented Programming � � � � � � � � � � � � � � 6 Understanding Classes, Objects, and Encapsulation � � � � 7 Understanding Inheritance and Polymorphism � � � � � � � 9 Features of the Java Programming Language � �
Answered 8 days AfterJan 17, 2021

Answer To: Java Programming, 9th ed. http://www.a-pdf.com/?tr-demo http://www.a-pdf.com/?tr-demo...

Swapnil answered on Jan 24 2021
157 Votes
74655/8016-assignment-1-r2019-jlea5u3z.pdf
ASSIGNMENT ONE – APPLICATION
LO-COMP
8016

Page 1 | Version 9






SUBMISSION INSTRUCTIONS


Send ONE .zip compressed file containing all your .java files. (no .class files)
Submit your assignment through blackboard (submit assignment link).
Name your assignment file (the zip file) Assignment_One_.
For example; Assignment_One_Neilsen_Janeil.zip
GRADING MATRIX
The following provides you with feedback on each area you are graded on for the assignments in this course.
Trait 90% –- 100% 70% –- 89% 50% - 69% 0% - 49%
Specifications The program works
and meets all of the
specifications.
The program works
and produces the
correct results and
displays them
correctly. It also meets
most of the other
specifications.
The program
produces correct
results but does not
display them
correctly.
The program is
producing incorrect
results.
Readability The code is
exceptionally well
organized and very
easy to follow.
The code is fairly easy
to read.
The code is readable
only by someone
who knows what it is
supposed to be
doing.
The code is poorly
organized and very
difficult to read.
Reusability The code could be
reused as a whole or
each routine could be
reused.
Most of the code could
be reused in other
programs.
Some parts of the
code could be reused
in other programs.
The code is not
organized for
reusability.
Documentation The documentation is
well written and
clearly explains what
the code is
accomplishing and
how.
The documentation
consists of embedded
comment and some
simple header
documentation that is
somewhat useful in
understanding the
code.
The documentation
is simply comments
embedded in the
code with some
simple header
comments separating
routines.
The documentation
is simply comments
embedded in the
code and does not
help the reader
understand the code.
Delivery The program was
delivered on time.
The program was
delivered within a
week of the due date.
The code was within
2 weeks of the due
date.
The code was more
than 2 weeks
overdue.
Efficiency The code is extremely
efficient without
sacrificing readability
and understanding.
The code is fairly
efficient without
sacrificing readability
and understanding.
The code is brute
force and
unnecessarily long.
The code is huge and
appears to be
patched together.






ASSIGNMENT ONE – APPLICATION
LO-COMP
8016
Page 2 | Version 9
ASSIGNMENT BACKGROUND
This assignment builds upon the lecture notes and chapters 14 and 15.
ASSIGNMENT PREPARATION
In order to prepare for this assignment question you should attempt:
 all debugging exercise in chapters 14 to 15
 complete 5 exercises from chapters 14 to 14 (odd questions)
ASSIGNMENT QUESTION – Game Zone
Create an abstract alien class. Include at two protected and one private data
members of your choice, such as the number of eyes the alien has. Include a
constructor that requires a value for each data field and a toString() method that
returns a String containing a complete description of the Alien. Always Save the file as
Alien.java.
Create two classes – Martian and Jupiterian – that descend from Alien. Supply each
with a constructor that sets the Alien data fields with values you choose. For example,
you can decide that a Martian has four eyes but a Jupiterian has only two. Save the
files as Martian.java and Jupiterian.java.
Create an application that instantiates one Martian and one Jupiterian using dynamic
method binding. Use the toString() method with each object and display the results.
Save the application as CreateAliens.java.
Now add a draw() method for each child class. The draw() method accepts a
Graphics object x- and y- starting coordinates. The method draws the Aliens in any way
you choose, using lines, ovals, rectangles, and so on. Using the drawstring() method,
include a description that names each drawing. Save the files as Martian.java and
Jupiterian.java
Create a jFrame that instantiates a Martian and a Jupiterian. In the jFrame’s paint()
method, draw each type of Alien. Save the file as JDemoAliens.java. The figure below
shows some sample Aliens, but your Aliens might look very different.
74655/Alien.java
74655/Alien.javaimport java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Alien 
{
  int eyes;
  int legs;
  int hands;
  public int getEyes() 
  {
    return eyes;
  }
  public void setEyes(int eyes) 
  {
    this.eyes = eyes;
  }
  public int getLegs() 
  {
    return legs;
  }
  public void setLegs(int legs) 
  {
    this.legs = legs;
  }
  public int getHands() 
  {
    return hands;
  }
  public void setHands(int hands) 
  {
    this.hands = hands;
  }
  public Alien(int eyes, int legs, int hands) 
  {
    super();
    this.eyes = eyes;
    this.legs = legs;
    this.hands = hands;
  }
  @Override
  public String toString() 
  {
    return "Alien [eyes=" + eyes + ", legs=" + legs + ", hands=" + hands + "]";
  }
}
74655/CreateAliens.java
74655/CreateAliens.javaimport java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class CreateAliens 
{
  public static void main(String[] args) 
  {
    Alien a = new Martian(5, 4);
    System.out.println(a.toString());
    Alien a1 = new Jupiterian(3, 4);
    System.out.println(a1.toString());
  }
}
74655/JDemoAliens.java
74655/JDemoAliens.javaimport java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Jupiterian extends Applet implements ActionListener
{
  Label l1, l2;
  Button b1;
  TextField t1, t2;
  public void init()
  {
    b1 = new Button("Roll");
    b1.addActionListener(this);
    l1 = new Label("Enter X : ");
    l2 = new Label("Enter Y : ");
    t1 = new TextField(15);
    t2 = new TextField(15);
    add(l1);
    add(t1);
    add(l2);
    add(t2);
    add(b1);
  }
  public void paint(Graphics g)
  {
    draw(g);
  }
  void draw(Graphics g)
  {
    int x = Integer.parseInt(t1.getText());
    int y = Integer.parseInt(t2.getText());
    g.drawRect(x, y-410, 250, 350);
    g.drawLine(x+75, y-100, x+75, y);
    g.drawLine(x+175, y-100, x+175, y);
    g.drawLine(x+75, y-450, x+75, y-410);
    g.drawLine(x+105, y-450, x+105, y-410);
    g.drawRect(x, y-520, 250, 70);
    g.drawOval(x+50, y-510, 15, 15);
    g.drawOval(x+100, y-510, 15, 15);
    g.drawOval(x+150, y-510, 15, 15);
    g.drawOval(x+200, y-510, 15, 15);
    g.drawRect(x+75, y-480, 75, 10);
    g.drawString("A Jupitarian", x+20, y-380);
  }
  public void actionPerformed(ActionEvent ae)
  {
    repaint();
  }
}
public class Martian extends Applet implements ActionListener
{
  Label l1, l2;
  Button b1;
  TextField t1, t2;
  public void init()
  {
    b1 = new Button("Roll");
    b1.addActionListener(this);
    l1 = new Label("Enter X : ");
    l2 = new Label("Enter Y : ");
    t1 = new TextField(15);
    t2 = new TextField(15);
    add(l1);
    add(t1);
    add(l2);
    add(t2);
    add(b1);
  }
  public void paint(Graphics g)
  {
    draw(g);
  }
  void draw(Graphics g)
  {
    int x = Integer.parseInt(t1.getText());
    int y = Integer.parseInt(t2.getText());
    g.drawOval(x, y-410, 250, 350);
    g.drawOval(x, y-610, 100, 130);
    g.drawOval(x+150, y-610, 100, 130);
    g.drawLine(x+95, y-405, x+50, y-480);
    g.drawLine(x+145, y-407, x+200, y-480);
    g.drawOval(x+40, y-600, 20, 45);
    g.fillOval(x+40, y-581, 20, 26);
    g.drawOval(x+190, y-600, 20, 45);
    g.fillOval(x+190, y-581, 20, 26);
    g.drawArc(x+20, y-570, 60, 60, 0, -180);
    g.drawArc(x+170, y-540, 60, 60, 0, 180);
    g.drawLine(x+75, y-100, x+75, y);
    g.drawLine(x+175, y-100, x+175, y);
    g.drawString("A Martian", x-50, y-100);
  }
  public void actionPerformed(ActionEvent ae)
  {
    repaint();
  }
}
74655/joyce-farrell-java-programming-2019-idr2o4b5.pdf
http://www.a-pdf.com/?tr-demo
http://www.a-pdf.com/?tr-demo
http://www.a-pdf.com/?tr-demo
JAVA™ PROGRAMMING
JOYCE FARRELL
Australia • Brazil • Mexico • Singapore • United Kingdom • United States
N I N T H E d I T I o N
97070_fm_hr_i-xxiv.indd 1 27/02/18 7:34 pm
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.
Important Notice: Media content referenced within the product description or the product
text may not be available in the eBook version.
Java™ Programming, Ninth Edition
Joyce Farrell
SVP, GM Skills: Jonathan Lau
Product Team Manager: Kristin McNary
Associate Product Manager:
Kate Mason
Executive Director of Content Design,
Skills: Marah Bellegarde
Director, Learning Design –
Skills Computing: Leigh Hefferon
Learning Designer:
Natalie Onderdonk
Product Assistant: Jake Toth
Marketing Director: Michele McTighe
Marketing Manager: Stephanie Albracht
Content Project Manager:
Michele Stulga
Senior Designer: Diana Graham
Production Service/Composition:
SPi Global
Cover image: Colormos/Photodisc
/Getty Images
© 2019, 2016, 2014, 2012 Cengage Learning, Inc.
Unless otherwise noted, all content is © Cengage.
ALL RIGHTS RESERVED. No part of this work covered by the copyright
herein may be reproduced or distributed in any form or by any
means, except as permitted by U.S. copyright law, without the prior
written permission of the copyright owner.
Unless otherwise noted all screenshots are courtesy of Microsoft
Corporation.
Unless otherwise noted all tables/figures exhibits are © 2019 Cengage®.
For product information and technology assistance, contact us at
Cengage Customer & Sales Support, 1-800-354-9706
or support.cengage.com.
For permission to use material from this text or product, submit
all requests online at www.cengage.com/permissions.
Library of Congress Control Number: 2018933919
Softbound ISBN: 978-1-337-39707-0
Loose Leaf ISBN: 978-1-337-68590-0
Cengage
20 Channel Center Street
Boston, MA 02210
USA
Cengage is a leading provider of customized learning solutions with
employees residing in nearly 40 different countries and sales in more
than 125 countries around the world. Find your local representative at
www.cengage.com.
Cengage products are represented in Canada by Nelson Education, Ltd.
To learn more about Cengage platforms and services, visit
www.cengage.com.
To register or access your online learning solution or purchase
materials for your course, visit www.cengagebrain.com.
Notice to the Reader
Publisher does not warrant or guarantee any of the products described herein or perform any independent analysis in
connection with any of the product information contained herein. Publisher does not assume, and expressly disclaims,
any obligation to obtain and include information other than that provided to it by the manufacturer. The reader is
expressly warned to consider and adopt all safety precautions that might be indicated by the activities described herein
and to avoid all potential hazards. By following the instructions contained herein, the reader willingly assumes all risks in
connection with such instructions. The publisher makes no representations or warranties of any kind, including but not
limited to, the warranties of fitness for particular purpose or merchantability, nor are any such representations implied
with respect to the material set forth herein, and the publisher takes no responsibility with respect to such material. The
publisher shall not be liable for any special, consequential, or exemplary damages resulting, in whole or part, from the
readers’ use of, or reliance upon, this material.
Printed in the United States of America
Print Number: 01 Print Year: 2018
97070_fm_hr_i-xxiv.indd 2 27/02/18 7:34 pm
Brief Contents
Preface � � � � � � � � � � � � � � � � xiv
CHAPTER 1 Creat ing Java Programs � � � � � � � � � � 1
CHAPTER 2 Us ing Data � � � � � � � � � � � � � � � � 49
CHAPTER 3 Us ing Methods, Classes, and Objects � � � 110
CHAPTER 4 More Object Concepts � � � � � � � � � � 170
CHAPTER 5 Making Decis ions � � � � � � � � � � � � 230
CHAPTER 6 Looping � � � � � � � � � � � � � � � � 283
CHAPTER 7 Characters, Str ings, and the
StringBuilder � � � � � � � � � � � � � 330
CHAPTER 8 Arrays � � � � � � � � � � � � � � � � � 369
CHAPTER 9 Advanced Array Concepts � � � � � � � � 416
CHAPTER 10 Introduct ion to Inher i tance � � � � � � � � 467
CHAPTER 11 Advanced Inher i tance Concepts � � � � � � 513
CHAPTER 12 Except ion Handl ing � � � � � � � � � � � 570
CHAPTER 13 F i le Input and Output � � � � � � � � � � � 635
CHAPTER 14 Introduct ion to Swing Components � � � � 698
CHAPTER 15 Us ing JavaFX and Scene Bui lder � � � � � � 758
APPENdIx A Work ing wi th the Java Plat form � � � � � � 799
APPENdIx B Data Representat ion � � � � � � � � � � � 804
APPENdIx C Formatt ing Output � � � � � � � � � � � � 810
APPENdIx d Generat ing Random Numbers � � � � � � � 820
APPENdIx E Javadoc � � � � � � � � � � � � � � � � 826
G lossary � � � � � � � � � � � � � � � � 834
Index � � � � � � � � � � � � � � � � � 853
iii
97070_fm_hr_i-xxiv.indd 3 27/02/18 7:34 pm
97070_fm_hr_i-xxiv.indd 4 27/02/18 7:34 pm
Table of Contents
Preface � � � � � � � � � � � � � � � � xiv
CHAPTER 1 Creat ing Java Programs � � � � � � � � � � 1
Learning Programming Terminology � � � � � � � � � � � � � 2
Comparing Procedural and Object-Oriented
Programming Concepts � � � � � � � � � � � � � � � � � � 5
Procedural Programming � � � � � � � � � � � � � � � � � 5
Object-Oriented Programming � � � � � � � � � � � � � � 6
Understanding Classes, Objects, and Encapsulation � � � � 7
Understanding Inheritance and Polymorphism � � � � � � � 9
Features of the Java Programming Language � � � � � � � 10
Analyzing a Java Application that Produces
Console Output � � � � � � � � � � � � � � � � � � � � 12
Understanding the Statement that Produces
the Output � � � � � � � � � � � � � � � � � � � � � � 13
Understanding the First Class � � � � � � � � � � � � 15
Understanding the main() Method � � � � � � � � � � � 17
Indent Style � � � � � � � � � � � � � � � � � � � � � � 19
Saving a Java Class � � � � � � � � � � � � � � � � � � 20
Compiling a Java Class and Correcting Syntax Errors � � � � 22
Compiling a Java Class � � � � � � � � � � � � � � � � 22
Correcting Syntax Errors � � � � � � � � � � � � � � � � 23
Running a Java Application and Correcting Logic Errors � � � 29
Running a Java Application � � � � � � � � � � � � � � � 29
Modifying a Compiled Java Class � � � � � � � � � � � � 29
Correcting Logic Errors � � � � � � � � � � � � � � � � 31
Adding Comments to a Java Class � � � � � � � � � � � � 32
Creating a Java Application that Produces GUI Output� � � � 35
Finding Help � � � � � � � � � � � � � � � � � � � � � � 38
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � � 39
Key Terms � � � � � � � � � � � � � � � � � � � � � � � 41
Chapter Summary � � � � � � � � � � � � � � � � � � � � 41
Exercises � � � � � � � � � � � � � � � � � � � � � � � � 45
v
97070_fm_hr_i-xxiv.indd 5 27/02/18 7:34 pm
vi
C o N T E N T s
CHAPTER 2 Us ing Data � � � � � � � � � � � � � � � � 49
Declaring and Using Constants and Variables � � � � � � � 50
Declaring Variables � � � � � � � � � � � � � � � � � � 51
Declaring Named Constants � � � � � � � � � � � � � � 52
The Scope of Variables and Constants � � � � � � � � � 54
Concatenating Strings to Variables and Constants � � � � 54
Pitfall: Forgetting that a Variable Holds One Value
at a Time � � � � � � � � � � � � � � � � � � � � � � 57
Learning About Integer Data Types � � � � � � � � � � � 60
Using the boolean Data Type � � � � � � � � � � � � � � 65
Learning About Floating-Point Data Types � � � � � � � � � 67
Using the char Data Type � � � � � � � � � � � � � � � � 68
Using the Scanner Class to Accept Keyboard Input � � � � 74
Pitfall: Using nextLine() Following One of
the Other Scanner Input Methods � � � � � � � � � � � 77
Using the JOptionPane Class to Accept GUI Input� � � � � 82
Using Input Dialog Boxes� � � � � � � � � � � � � � � � 83
Using Confirm Dialog Boxes � � � � � � � � � � � � � � 86
Performing Arithmetic Using Variables and Constants � � � � 88
Associativity and Precedence� � � � � � � � � � � � � � 89
Writing Arithmetic Statements Efficiently � � � � � � � � 91
Pitfall: Not Understanding Imprecision in
Floating-Point Numbers � � � � � � � � � � � � � � � � 91
Understanding Type Conversion� � � � � � � � � � � � � � 96
Automatic Type Conversion� � � � � � � � � � � � � � � 96
Explicit Type Conversions � � � � � � � � � � � � � � � 97
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �101
Key Terms � � � � � � � � � � � � � � � � � � � � � � �102
Chapter Summary � � � � � � � � � � � � � � � � � � � �102
Exercises � � � � � � � � � � � � � � � � � � � � � � � �105
CHAPTER 3 Us ing Methods, Classes, and Objects � � � 110
Understanding Method Calls and Placement � � � � � � � �111
Understanding Method Construction� � � � � � � � � � � �114
Access Specifiers � � � � � � � � � � � � � � � � � � �115
Return Type � � � � � � � � � � � � � � � � � � � � � �116
Method Name � � � � � � � � � � � � � � � � � � � � �116
Parentheses � � � � � � � � � � � � � � � � � � � � �117
Adding Parameters to Methods � � � � � � � � � � � � � �121
Creating a Method that Receives a Single Parameter � � �122
Creating a Method that Requires Multiple Parameters � � �125
Creating Methods that Return Values � � � � � � � � � � �127
Chaining Method Calls � � � � � � � � � � � � � � � � �129
97070_fm_hr_i-xxiv.indd 6 27/02/18 7:34 pm
vii

Learning About Classes and Objects � � � � � � � � � � �133
Creating a Class � � � � � � � � � � � � � � � � � � � �136
Creating Instance Methods in a Class � � � � � � � � � � �138
Organizing Classes � � � � � � � � � � � � � � � � � �141
Declaring Objects and Using Their Methods � � � � � � � �145
Understanding Data Hiding � � � � � � � � � � � � � � �147
An Introduction to Using Constructors � � � � � � � � � � �150
Understanding that Classes Are Data Types � � � � � � � �154
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �158
Key Terms � � � � � � � � � � � � � � � � � � � � � � �158
Chapter Summary � � � � � � � � � � � � � � � � � � � �159
Exercises � � � � � � � � � � � � � � � � � � � � � � � �163
CHAPTER 4 More Object Concepts � � � � � � � � � � 170
Understanding Blocks and Scope � � � � � � � � � � � � �171
Overloading a Method � � � � � � � � � � � � � � � � � �179
Automatic Type Promotion in Method Calls � � � � � � � �181
Learning About Ambiguity � � � � � � � � � � � � � � � �185
Creating and Calling Constructors with Parameters � � � � �187
Overloading Constructors � � � � � � � � � � � � � � �188
Learning About the this Reference � � � � � � � � � � � �192
Using the this Reference to Make Overloaded
Constructors More Efficient � � � � � � � � � � � � � �195
Using static Fields � � � � � � � � � � � � � � � � � �199
Using Constant Fields � � � � � � � � � � � � � � � � �201
Using Automatically Imported, Prewritten
Constants and Methods � � � � � � � � � � � � � � � � �206
The Math Class � � � � � � � � � � � � � � � � � � � �206
Importing Classes that Are Not Imported Automatically � �208
Using the LocalDate Class � � � � � � � � � � � � � �210
Understanding Composition and Nested Classes � � � � � �216
Composition � � � � � � � � � � � � � � � � � � � � �216
Nested Classes � � � � � � � � � � � � � � � � � � � �218
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �220
Key Terms � � � � � � � � � � � � � � � � � � � � � � �220
Chapter Summary � � � � � � � � � � � � � � � � � � � �220
Exercises � � � � � � � � � � � � � � � � � � � � � � � �224
CHAPTER 5 Making Decis ions � � � � � � � � � � � � 230
Planning Decision-Making Logic � � � � � � � � � � � � � �231
The if and if…else Statements � � � � � � � � � � � � �233
The if Statement � � � � � � � � � � � � � � � � � � �233
Pitfall: Misplacing a Semicolon in an if Statement � � � �234
C o n t e n t s
97070_fm_hr_i-xxiv.indd 7 27/02/18 7:34 pm
viii
C o N T E N T s
Pitfall: Using the Assignment Operator Instead
of the Equivalency Operator � � � � � � � � � � � � � �235
Pitfall: Attempting to Compare Objects Using
the Relational Operators � � � � � � � � � � � � � � �236
The if…else Statement � � � � � � � � � � � � � � � �236
Using Multiple Statements in if and if…else Clauses � � �239
Nesting if and if…else Statements � � � � � � � � � � �245
Using Logical AND and OR Operators � � � � � � � � � � �247
The AND Operator � � � � � � � � � � � � � � � � � � �247
The OR Operator � � � � � � � � � � � � � � � � � � �249
Short-Circuit Evaluation � � � � � � � � � � � � � � � �250
Making Accurate and Efficient Decisions� � � � � � � � � �253
Making Accurate Range Checks� � � � � � � � � � � � �253
Making Efficient Range Checks � � � � � � � � � � � � �256
Using && and || Appropriately � � � � � � � � � � � � �256
Using the switch Statement � � � � � � � � � � � � � � �258
Using the Conditional and NOT Operators � � � � � � � � �264
Using the NOT Operator � � � � � � � � � � � � � � � �265
Understanding Operator Precedence � � � � � � � � � � �266
Adding Decisions and Constructors to Instance
Methods� � � � � � � � � � � � � � � � � � � � � � � �269
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �272
Key Terms � � � � � � � � � � � � � � � � � � � � � � �273
Chapter Summary � � � � � � � � � � � � � � � � � � � �273
Exercises � � � � � � � � � � � � � � � � � � � � � � � �277
CHAPTER 6 Looping � � � � � � � � � � � � � � � � 283
Learning About the Loop Structure � � � � � � � � � � � �284
Creating while Loops � � � � � � � � � � � � � � � � � �285
Writing a Definite while Loop � � � � � � � � � � � � �285
Pitfall: Failing to Alter the Loop Control Variable
Within the Loop Body � � � � � � � � � � � � � � � � �287
Pitfall: Unintentionally Creating a Loop with
an Empty Body� � � � � � � � � � � � � � � � � � � �288
Altering a Definite Loop’s Control Variable � � � � � � � �289
Writing an Indefinite while Loop � � � � � � � � � � � �290
Validating Data � � � � � � � � � � � � � � � � � � � �292
Using Shortcut Arithmetic Operators � � � � � � � � � � �296
Creating a for Loop� � � � � � � � � � � � � � � � � � �300
Unconventional for Loops � � � � � � � � � � � � � � �302
Learning How and When to Use a do…while Loop � � � � �306
Learning About Nested Loops � � � � � � � � � � � � � �308
Improving Loop Performance � � � � � � � � � � � � � � �313
Avoiding Unnecessary Operations � � � � � � � � � � � �314
97070_fm_hr_i-xxiv.indd 8 27/02/18 7:34 pm
ix

Considering the Order of Evaluation of
Short-Circuit Operators � � � � � � � � � � � � � � � �314
Comparing to Zero � � � � � � � � � � � � � � � � � �315
Employing Loop Fusion � � � � � � � � � � � � � � � �316
A Final Note on Improving Loop Performance � � � � � �317
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �320
Key Terms � � � � � � � � � � � � � � � � � � � � � � �320
Chapter Summary � � � � � � � � � � � � � � � � � � � �320
Exercises � � � � � � � � � � � � � � � � � � � � � � � �324
CHAPTER 7 Characters, Str ings, and the
StringBuilder � � � � � � � � � � � � � 330
Understanding String Data Problems � � � � � � � � � � �331
Using Character Class Methods� � � � � � � � � � � � �332
Declaring and Comparing String Objects � � � � � � � � �336
Comparing String Values � � � � � � � � � � � � � � �336
Empty and null Strings � � � � � � � � � � � � � � � �340
Using a Variety of String Methods � � � � � � � � � � � �342
Converting String Objects to Numbers� � � � � � � � �347
Learning About the StringBuilder
and StringBuffer Classes � � � � � � � � � � � � � �352
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �358
Key Terms � � � � � � � � � � � � � � � � � � � � � � �359
Chapter Summary � � � � � � � � � � � � � � � � � � � �359
Exercises � � � � � � � � � � � � � � � � � � � � � � � �362
CHAPTER 8 Arrays � � � � � � � � � � � � � � � � � 369
Declaring an Array� � � � � � � � � � � � � � � � � � � �370
Initializing an Array � � � � � � � � � � � � � � � � � � �375
Using Variable Subscripts with an Array � � � � � � � � � �378
Using the Enhanced for Loop � � � � � � � � � � � � �380
Using Part of an Array � � � � � � � � � � � � � � � � �380
Declaring and Using Arrays of Objects � � � � � � � � � �383
Using the Enhanced for Loop with Objects � � � � � � �385
Manipulating Arrays of Strings � � � � � � � � � � � �385
Searching an Array and Using Parallel Arrays � � � � � � �392
Using Parallel Arrays � � � � � � � � � � � � � � � � �393
Searching an Array for a Range Match� � � � � � � � � �395
Passing Arrays to and Returning Arrays from Methods � � �399
Returning an Array from a Method � � � � � � � � � � �402
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �405
Key Terms � � � � � � � � � � � � � � � � � � � � � � �405
Chapter Summary � � � � � � � � � � � � � � � � � � � �405
Exercises � � � � � � � � � � � � � � � � � � � � � � � �409
C o n t e n t s
97070_fm_hr_i-xxiv.indd 9 27/02/18 7:34 pm
x
C o N T E N T s
CHAPTER 9 Advanced Array Concepts � � � � � � � � 416
Sorting Array Elements Using the Bubble Sort Algorithm � �417
Using the Bubble Sort Algorithm � � � � � � � � � � � �418
Improving Bubble Sort Efficiency � � � � � � � � � � � �420
Sorting Arrays of Objects � � � � � � � � � � � � � � �420
Sorting Array Elements Using the Insertion
Sort Algorithm � � � � � � � � � � � � � � � � � � � � �425
Using Two-Dimensional and Other Multidimensional Arrays� �430
Passing a Two-Dimensional Array to a Method � � � � � �433
Using the length Field with a Two-Dimensional Array� � �433
Understanding Jagged Arrays � � � � � � � � � � � � �434
Using Other Multidimensional Arrays � � � � � � � � � �435
Using the Arrays Class � � � � � � � � � � � � � � � � �438
Using the ArrayList Class � � � � � � � � � � � � � � �446
Creating Enumerations � � � � � � � � � � � � � � � � � �449
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �456
Key Terms � � � � � � � � � � � � � � � � � � � � � � �456
Chapter Summary � � � � � � � � � � � � � � � � � � � �456
Exercises � � � � � � � � � � � � � � � � � � � � � � � �460
CHAPTER 10 Introduct ion to Inher i tance � � � � � � � � 467
Learning About the Concept of Inheritance � � � � � � � � �468
Diagramming Inheritance Using the UML � � � � � � � � �468
Inheritance Terminology � � � � � � � � � � � � � � � �470
Extending Classes � � � � � � � � � � � � � � � � � � � �472
Overriding Superclass Methods � � � � � � � � � � � � � �479
Using the @Override Tag � � � � � � � � � � � � � � �480
Calling Constructors During Inheritance � � � � � � � � � �483
Using Superclass Constructors that Require Arguments � �484
Accessing Superclass Methods � � � � � � � � � � � � � �489
Comparing this and super � � � � � � � � � � � � � �491
Employing Information Hiding � � � � � � � � � � � � � � �493
Methods You Cannot Override � � � � � � � � � � � � � �495
A Subclass Cannot Override static Methods
in Its Superclass � � � � � � � � � � � � � � � � � � �495
A Subclass Cannot Override final Methods
in Its Superclass � � � � � � � � � � � � � � � � � � �499
A Subclass Cannot Override Methods in a
final Superclass � � � � � � � � � � � � � � � � � �501
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �502
Key Terms � � � � � � � � � � � � � � � � � � � � � � �502
Chapter Summary � � � � � � � � � � � � � � � � � � � �503
Exercises � � � � � � � � � � � � � � � � � � � � � � � �506
97070_fm_hr_i-xxiv.indd 10 27/02/18 7:34 pm
xi

CHAPTER 11 Advanced Inher i tance Concepts � � � � � � 513
Creating and Using Abstract Classes � � � � � � � � � � �514
Using Dynamic Method Binding � � � � � � � � � � � � � �523
Using a Superclass as a Method Parameter Type � � � � �525
Creating Arrays of Subclass Objects � � � � � � � � � � �527
Using the Object Class and Its Methods � � � � � � � � �530
Using the toString() Method� � � � � � � � � � � � �532
Using the equals() Method � � � � � � � � � � � � � �535
Using Inheritance to Achieve Good Software Design � � � �540
Creating and Using Interfaces � � � � � � � � � � � � � �541
Creating Interfaces to Store Related Constants � � � � �548
Using Anonymous Inner Classes and Lambda Expressions � �552
Lambda Expressions� � � � � � � � � � � � � � � � � �554
Creating and Using Packages� � � � � � � � � � � � � � �555
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �557
Key Terms � � � � � � � � � � � � � � � � � � � � � � �558
Chapter Summary � � � � � � � � � � � � � � � � � � � �558
Exercises � � � � � � � � � � � � � � � � � � � � � � � �562
CHAPTER 12 Except ion Handl ing � � � � � � � � � � � 570
Learning About Exceptions � � � � � � � � � � � � � � � �571
Trying Code and Catching Exceptions � � � � � � � � � � �576
Using a try Block to Make Programs “Foolproof” � � � �580
Declaring and Initializing Variables in try…catch
Blocks � � � � � � � � � � � � � � � � � � � � � � �582
Throwing and Catching Multiple Exceptions � � � � � � � �585
Using the finally Block � � � � � � � � � � � � � � � �591
Understanding the Advantages of Exception Handling � � � �593
Specifying the Exceptions that a Method Can Throw � � � �596
Tracing Exceptions Through the Call Stack� � � � � � � � �600
Creating Your Own Exception Classes � � � � � � � � � �605
Using Assertions � � � � � � � � � � � � � � � � � � � �608
Displaying the Virtual Keyboard � � � � � � � � � � � � � �622
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �625
Key Terms � � � � � � � � � � � � � � � � � � � � � � �626
Chapter Summary � � � � � � � � � � � � � � � � � � � �626
Exercises � � � � � � � � � � � � � � � � � � � � � � � �630
CHAPTER 13 F i le Input and Output � � � � � � � � � � 635
Understanding Computer Files � � � � � � � � � � � � � �636
Using the Path and Files Classes � � � � � � � � � � � �638
Creating a Path � � � � � � � � � � � � � � � � � � � �638
Retrieving Information About a Path � � � � � � � � � � �640
C o n t e n t s
97070_fm_hr_i-xxiv.indd 11 27/02/18 7:34 pm
xii
C o N T E N T s
Converting a Relative Path to an Absolute One � � � � � �641
Checking File Accessibility � � � � � � � � � � � � � � �642
Deleting a Path � � � � � � � � � � � � � � � � � � � �643
Determining File Attributes � � � � � � � � � � � � � � �645
File Organization, Streams, and Buffers � � � � � � � � � �648
Using Java’s IO Classes � � � � � � � � � � � � � � � � �651
Writing to a File � � � � � � � � � � � � � � � � � � � �654
Reading from a File � � � � � � � � � � � � � � � � � �656
Creating and Using Sequential Data Files � � � � � � � � �657
Learning About Random Access Files � � � � � � � � � � �663
Writing Records to a Random Access Data File � � � � � � �667
Reading Records from a Random Access Data File � � � � �673
Accessing a Random Access File Sequentially � � � � � �674
Accessing a Random Access File Randomly � � � � � � �675
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �689
Key Terms � � � � � � � � � � � � � � � � � � � � � � �689
Chapter Summary � � � � � � � � � � � � � � � � � � � �689
Exercises � � � � � � � � � � � � � � � � � � � � � � � �693
CHAPTER 14 Introduct ion to Swing Components � � � � 698
Understanding Swing Components � � � � � � � � � � � �699
Using the JFrame Class � � � � � � � � � � � � � � � � �700
Customizing a JFrame’s Appearance � � � � � � � � � �704
Using the JLabel Class � � � � � � � � � � � � � � � � �708
Changing a JLabel’s Font � � � � � � � � � � � � � � �710
Using a Layout Manager � � � � � � � � � � � � � � � � �712
Extending the JFrame Class � � � � � � � � � � � � � � �715
Adding JTextFields and JButtons to a JFrame � � � � �718
Adding JTextFields � � � � � � � � � � � � � � � � �718
Adding JButtons � � � � � � � � � � � � � � � � � � �720
Learning About Event-Driven Programming � � � � � � � � �724
Preparing Your Class to Accept Event Messages � � � � �725
Telling Your Class to Expect Events to Happen � � � � � �726
Telling Your Class How to Respond to Events � � � � � �726
An Event-Driven Program � � � � � � � � � � � � � � � �727
Using Multiple Event Sources � � � � � � � � � � � � � �728
Using the setEnabled() Method � � � � � � � � � � �730
Understanding Swing Event Listeners � � � � � � � � � � �733
Using the JCheckBox, ButtonGroup,
and JComboBox Classes � � � � � � � � � � � � � � � �736
The JCheckBox Class � � � � � � � � � � � � � � � � �736
The ButtonGroup Class � � � � � � � � � � � � � � �740
The JComboBox Class � � � � � � � � � � � � � � � � �741
97070_fm_hr_i-xxiv.indd 12 27/02/18 7:34 pm
xiii

Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �748
Key Terms � � � � � � � � � � � � � � � � � � � � � � �749
Chapter Summary � � � � � � � � � � � � � � � � � � � �749
Exercises � � � � � � � � � � � � � � � � � � � � � � � �753
CHAPTER 15 Us ing JavaFX and Scene Bui lder � � � � � 758
What Is JavaFX? � � � � � � � � � � � � � � � � � � � � �759
The Life Cycle of JavaFX Applications � � � � � � � � � � �760
Understanding JavaFX Structure: Stage, Scene,
Panes, and Widgets � � � � � � � � � � � � � � � � � �762
Deploying JavaFX Applications � � � � � � � � � � � � � �768
Creating JavaFX Applications Using Scene Builder � � � � �768
Scene Builder Sections � � � � � � � � � � � � � � � �773
Using Widgets as Design Elements in FXML Layouts � � �774
Using CSS to Create Visual Effects � � � � � � � � � � � �778
Creating Animations in JavaFX � � � � � � � � � � � � � �785
Don’t Do It � � � � � � � � � � � � � � � � � � � � � � �790
Key Terms � � � � � � � � � � � � � � � � � � � � � � �790
Chapter Summary � � � � � � � � � � � � � � � � � � � �790
Exercises � � � � � � � � � � � � � � � � � � � � � � � �795
APPENdIx A Work ing wi th the Java Plat form � � � � � � 799
APPENdIx B Data Representat ion � � � � � � � � � � � 804
APPENdIx C Formatt ing Output � � � � � � � � � � � � 810
APPENdIx d Generat ing Random Numbers � � � � � � � 820
APPENdIx E Javadoc � � � � � � � � � � � � � � � � 826
G lossary � � � � � � � � � � � � � � � � 834
Index � � � � � � � � � � � � � � � � � 853
C o n t e n t s
97070_fm_hr_i-xxiv.indd 13 27/02/18 7:34 pm
Preface
Java Programming, Ninth Edition, provides the beginning programmer with a guide to
developing applications using the Java programming language. Java is popular among
professional programmers because it can be used to build visually interesting graphical user
interface (GUI) and Web-based applications. Java also provides an excellent environment
for the beginning programmer—a student can quickly build useful programs while learning
the basics of structured and object-oriented programming techniques.
This textbook assumes that you have little or no programming experience. It provides
a solid background in good object-oriented programming techniques and introduces
terminology using clear, familiar language. The programming examples are business
examples; they do not assume a mathematical background beyond high school business
math. In addition, the examples illustrate only one or two major points; they do not
contain so many features that you become lost following irrelevant and extraneous details.
Complete, working programs appear frequently in each chapter; these examples help
students make the transition from the theoretical to the practical. The code presented in
each chapter also can be downloaded from the publisher’s website, so students easily can
run the programs and experiment with changes to them.
The student using Java Programming, Ninth Edition, builds applications from the bottom
up rather than starting with existing objects. This facilitates a deeper understanding of
the concepts used in object-oriented programming and engenders appreciation for the
existing objects students use as their knowledge of the language advances. When students
complete this book, they will know how to modify and create simple Java programs,
and they will have the tools to create more complex examples. They also will have a
fundamental knowledge about object-oriented programming, which will serve them well in
advanced Java courses or in studying other object-oriented languages such as C++, C#, and
Visual Basic.
organization and Coverage
Java Programming, Ninth Edition, presents Java programming concepts, enforcing good
style, logical thinking, and the object-oriented paradigm. Objects are covered right from
the beginning, earlier than in many other textbooks. You create your first Java program
in Chapter 1. Chapters 2, 3, and 4 increase your understanding about how data, classes,
objects, and methods interact in an object-oriented environment.
Chapters 5 and 6 explore input and repetition structures, which are the backbone of
programming logic and essential to creating useful programs in any language. You learn
the special considerations of string and array manipulation in Chapters 7, 8, and 9.
xiv
97070_fm_hr_i-xxiv.indd 14 27/02/18 7:34 pm
xv
New in This Edition
Chapters 10, 11, and 12 thoroughly cover inheritance and exception handling. Inheritance
is the object-oriented concept that allows you to develop new objects quickly by adapting
the features of existing objects; exception handling is the object-oriented approach to
handling errors. Both are important concepts in object-oriented design. Chapter 13
provides information about handling files so you can store and retrieve program output.
Chapter 14 introduces GUI Swing components, which are used to create visually pleasing,
user-friendly, interactive applications.
Chapter 15 introduces JavaFX, which is the newest platform for creating and delivering
applications for the desktop and the Internet. Chapter 15 is written by Sandra Lavallee,
a professor and Computer and Design Technologies Department chairperson at Lakes
Region Community College in Laconia, New Hampshire.
New in This Edition
The following features are new for the Ninth Edition:
• Java 9e: All programs have been tested using Java 9e, the newest edition of Java.
• Windows 10: All programs have been tested in Windows 10, and all screen shots have
been taken in this environment.
• Programming exercises: Each chapter contains several new programming exercises
not seen in previous editions. All exercises and their solutions from the previous edition
that were replaced in this edition are still available on the Instructor Companion site.
• Anonymous inner classes and lambda expressions: These two new topics are
introduced in this edition of the book.
• JavaFX: This edition includes coverage of JavaFX.
Additionally, Java Programming, Ninth Edition, includes the following features:
• OBJECTIVES: Each chapter begins with a list of objectives so you know the topics that
will be presented in the chapter. In addition to providing a quick reference to topics
covered, this feature provides a useful study aid.
• YOU DO IT: In each chapter, step-by-step exercises help students create multiple
working programs that emphasize the logic a programmer uses in choosing statements
to include. These sections provide a means for students to achieve success on their
own—even those in online or distance learning classes.
• NOTES: These highlighted tips provide additional information—for example, an
alternative method of performing a procedure, another term for a concept, background
information about a technique, or a common error to avoid.
• EMPHASIS ON STUDENT RESEARCH: The student frequently is directed to
the Java website to investigate classes and methods. Computer languages evolve,
and programming professionals must understand how to find the latest language
improvements. This book encourages independent research.
P R E FA C E
97070_fm_hr_i-xxiv.indd 15 27/02/18 7:34 pm
xvi
New in This EditionP R E FA C E
• FIGURES: Each chapter contains many figures. Code figures are most frequently
25 lines or fewer, illustrating one concept at a time. Frequent screen shots show exactly
how program output appears. Callouts appear where needed to emphasize a point.
• COLOR: The code figures in each chapter contain all Java keywords in blue. This helps
students identify keywords more easily, distinguishing them from programmer-selected
names.
• FILES: More than 200 student files can be downloaded from the publisher’s website.
Most files contain the code presented in the figures in each chapter; students can run
the code for themselves, view the output, and make changes to the code to observe
the effects. Other files include debugging exercises that help students improve their
programming skills.
• TWO TRUTHS & A LIE: A short quiz reviews each chapter section, with answers
provided. This quiz contains three statements based on the preceding section of
text—two statements are true, and one is false. Over the years, students have requested
answers to problems, but we have hesitated to distribute them in case instructors want
to use problems as assignments or test questions. These true-false quizzes provide
students with immediate feedback as they read, without “giving away” answers to the
multiple-choice questions and programming exercises.
• DON’T DO IT: This section at the end of each chapter summarizes common mistakes
and pitfalls that plague new programmers while learning the current topic.
• KEY TERMS: Each chapter includes a list of newly introduced vocabulary, shown in
the order of appearance in the text. The list of key terms provides a short review of the
major concepts in the chapter.
• SUMMARIES: Following each chapter is a summary that recaps the programming
concepts and techniques covered in the chapter. This feature provides a concise means
for students to check their understanding of the main points in each chapter.
• REVIEW QUESTIONS: Each chapter includes 20 multiple-choice questions that serve
as a review of chapter topics.
• GAME ZONE: Each chapter provides one or more exercises in which students can
create interactive games using the programming techniques learned up to that point;
50 game programs are suggested in the book. The games are fun to create and play;
writing them motivates students to master the necessary programming techniques.
Students might exchange completed game programs with each other, suggesting
improvements and discovering alternate ways to accomplish tasks.
• CASES: Each chapter contains two running case problems. These cases represent
projects that continue to grow throughout a semester using concepts learned in each
new chapter. Two cases allow instructors to assign different cases in alternate semesters
or to divide students in a class into two case teams.
• GLOSSARY: A glossary contains definitions for all key terms in the book.
97070_fm_hr_i-xxiv.indd 16 27/02/18 7:34 pm
xvii
Instructor Companion Site
• APPENDICES: This edition includes useful appendices on working with the Java
platform, data representation, formatting output, generating random numbers, and
creating Javadoc comments.
• QUALITY: Every program example, exercise, and game solution was tested by the
author and then tested again by a quality assurance team using Java Standard Edition
(SE) 9, the most recent version available.
Instructor Resources
MindTap
MindTap activities for Java Programming, Ninth Edition are designed to help students
master the skills they need in today’s workforce. Research shows employers need critical
thinkers, troubleshooters, and creative problem-solvers to stay relevant in our fast-paced,
technology-driven world. MindTap helps you achieve this with assignments and activities
that provide hands-on practice and real-life relevance. Students are guided through
assignments that help them master basic knowledge and understanding before moving on
to more challenging problems.
All MindTap activities and assignments are tied to defined unit learning objectives.
Hands-on coding labs provide real-life application and practice. Readings and dynamic
visualizations support the lecture, while a post-course assessment measures exactly
how much a student has learned. MindTap provides the analytics and reporting to easily
see where the class stands in terms of progress, engagement, and completion rates.
Use the content and learning path as-is, or pick-and-choose how our materials will wrap
around yours. You control what the students see and when they see it. Learn more at
http://www.cengage.com/mindtap/.
The Java Programming MindTap also includes:
• Unit Quizzes: Students apply what they have learned in each unit by taking the quizzes
provided in the learning path.
• Video Lessons: Each unit is accompanied by video lessons that help to explain
important unit concepts. These videos were created and narrated by the author.
• Interactive Study Aids: Flashcards and crossword puzzles help users review main
concepts from the units and coding Snippets allow students to practice key coding
concepts.
Instructor Companion site
The following teaching tools are available for download at the Companion Site for this text.
Simply search for this text at www.cengagebrain.com and choose “Instructor Downloads.”
An instructor login is required.
P R E FA C E
97070_fm_hr_i-xxiv.indd 17 27/02/18 7:34 pm
xviii
AcknowledgmentsP R E FA C E
• Instructor’s Manual: The Instructor’s Manual that accompanies this textbook includes
additional instructional material to assist in class preparation, including items such as
Overviews, Chapter Objectives, Teaching Tips, Quick Quizzes, Class Discussion Topics,
Additional Projects, Additional Resources, and Key Terms. A sample syllabus also is
available.
• Test Bank: Cengage Testing Powered by Cognero is a flexible, online system that allows
you to:
° Author, edit, and manage test bank content from multiple Cengage solutions.
° Create multiple test versions in an instant.
° Deliver tests from your LMS, your classroom, or wherever you want.
• PowerPoint Presentations: This text provides PowerPoint slides to accompany each
chapter. Slides can be used to guide classroom presentations, to make available to
students for chapter review, or to print as classroom handouts.
• Student Files: Files are provided for every figure in the text. Instructors can use the
files to customize PowerPoint slides, illustrate quizzes, or create handouts.
• Solutions: Solutions to all programming exercises are available. If an input file is
needed to run a programming exercise, it is included with the solution file.
• Data Files: Data files necessary to complete the steps and projects in the book are
available at www.cengagebrain.com, or your instructor will provide the data files to you.
Acknowledgments
I would like to thank all of the people who helped to make this book a reality, including
Natalie Onderdonk, Learning Designer; Michele Stulga, Content Project Manager; and
John Freitas, Quality Assurance Tester. I am lucky to work with these professionals who are
dedicated to producing high-quality instructional materials.
I am also grateful to the reviewers who provided comments and encouragement during this
book’s development, including Cliff Brozo, Monroe College; Fred D’Angelo, University of
Arizona; Cassandra Henderson, Albany Technical College; Zack Hubbard, Rowan-Cabarrus
Community College; and Sandra Lavallee, Lakes Region Community College.
Thanks, too, to my husband, Geoff, for his constant support, advice, and encouragement.
Finally, this book is dedicated to George Edward Farrell Peterson and Clifford Geoffrey
Farrell Peterson. You each had a book dedicated to you earlier, but those books were

published before I knew your names. Now you are here, and I love you!
Joyce Farrell
97070_fm_hr_i-xxiv.indd 18 27/02/18 7:34 pm
xix
Using Your Own Computer
Read This Before You Begin
The following information will help you as you prepare to use this textbook.
To the User of the data Files
To complete the steps and projects in this book, you need data files that have been created
specifically for this book. Your instructor will provide the data files to you. You also can
obtain the files electronically from www.CengageBrain.com. Find the ISBN of your title
on the back cover of your book, then enter the ISBN in the search box at the top of the
Cengage Brain home page. You can find the data files on the product page that opens. Note
that you can use a computer in your school lab or your own computer to complete the
exercises in this book.
Using Your own Computer
To use your own computer to complete the steps and exercises, you need the following:
• Software: Java SE 9, available from www.oracle.com/technetwork/java/index.html.
Although almost all of the examples in this book will work with earlier versions of Java,
this book was created using Java 9e. You also need a text editor, such as Notepad. A few
exercises ask you to use a browser for research. Chapter 15 uses NetBeans to develop
JavaFX programs; you can downoad this software from Https:netbens.org.
• Hardware: For operating system requirements (memory and disk space), see
http://java.com/en/download/help.
P R E FA C E
97070_fm_hr_i-xxiv.indd 19 27/02/18 7:34 pm
Https:netbens.org
Features
58
Using DataC h a p t e r 2
Declaring and Using a Variable
In this section, you write an application to work with a variable and a constant.
1. Open a new document in your text editor. Create a class header and an opening
and closing curly brace for a new class named DataDemo by typing the following:
public class DataDemo
{
}
2. Between the curly braces, indent a few spaces and type the following main()
method header and its curly braces:
public static void main(String[] args)
{
}
3. Between the main() method’s curly braces, type the following variable
declaration:
int aWholeNumber = 315;
4. Type the following output statements. The first uses the print() method to
display a string that includes a space before the closing quotation mark and
leaves the insertion point for the next output on the same line. The second
statement uses println() to display the value of aWholeNumber and then
advance to a new line.
System.out.print("The number is ");
System.out.println(aWholeNumber);
5. Save the file as DataDemo.java.
6. Up to this point in the book, every print() and println() statement you
have seen has used a String as an argument. When you added the last two
statements to the DataDemo class, you wrote a println() statement that uses
an int as an argument. As a matter of fact, there are many different versions of
print() and println() that use different data types. Go to the Java website
(www.oracle.com/technetwork/java/index.html), select Java APIs, and
then select Java SE 9. Scroll through the list of All Classes, and select
PrintStream; you will recall from Chapter 1 that PrintStream is the data type
for the out object used with the println() method. Scroll down to view the list
of methods in the Method Summary, and notice the many versions of the print()
and println() methods, including ones that accept a String, an int, a long,
and so on. In the last two statements you added to this program, one used a
You Do It
(continues)
97070_ch02_hr_049-109.indd 58 07/02/18 3:23 pm
88
Using DataC h a p t e r 2
performing arithmetic Using Variables and Constants
Table 2-8 describes the five standard arithmetic operators that you use to perform calcula-
tions with values in your programs. A value used on either side of an operator is an operand.
For example, in the expression 45 + 2, the numbers 45 and 2 are operands. The arithmetic
operators are examples of binary operators, so named because they require two operands.
Confirm dialog boxes provide more practical uses when your applications can make decisions based on the
users’ responses. In the chapter “Making Decisions,” you will learn how to make decisions within programs.
The false statement is #3. A confirm dialog box displays the options Yes, No, and
Cancel.
tWO trUthS & a LIe
Using the JOptionPane Class to Accept GUI Input
1. You can create an input dialog box using the showInputDialog() method;
the method returns a String that represents a user’s response.
2. You can use methods from the Java classes Integer and Double when you
want to convert a dialog box’s returned values to numbers.
3. A confirm dialog box can be created using the showConfirmDialog()
method in the JOptionPane class; a confirm dialog box displays the options
Accept, Reject, and Escape.
Watch the video Getting Input.
You will learn about the Java shortcut arithmetic operators in the chapter “Looping.”
The operators / and % deserve special consideration. Java supports two types of division:
• Floating-point division occurs when either or both of the operands are floating-point
values. For example, 45.0 / 2 is 22.5.
• Integer division occurs when both of the operands are integers. The result is an inte-
ger, and any fractional part of the result is lost. For example, the result of 45 / 2 is 22. As
another example, 39 / 5 is 7 because 5 goes into 39 seven whole times; 38 / 5, 37 / 5, 36 / 5,
and 35 / 5 all evaluate to 7.
97070_ch02_hr_049-109.indd 88 07/02/18 3:24 pm
The author does an
awesome job: the examples,
problems, and material are
very easy to understand!
—Bernice Cunningham,
Wayne County Community
College district
VIdEo LEssoNs help explain
important chapter concepts�
Videos are part of the eBook in
MindTap and are also posted on
the Instructor Companion Site�
NoTEs provide
additional information—
for example, another
location in the book that
expands on a topic, or a
common error to watch
out for�
YoU do IT sections
walk students through
program development
step by step�
This text focuses on helping students become better programmers and
understand Java program development through a variety of key features.
In addition to Chapter Objectives, Summaries, and Key Terms, these useful
features will help students regardless of their learning styles.xx
97070_fm_hr_i-xxiv.indd 20 27/02/18 7:34 pm
xxi

158
Using Methods, Classes, and ObjectsC h a p t e r 3
Don’t Do It
• Don’t place a semicolon at the end of a method header. After you get used to putting
semicolons at the end of every statement, it’s easy to start putting them in too many
places. Method headers never end in a semicolon.
• Don’t think “default constructor” means only the automatically supplied constructor.
Any constructor that does not accept parameters is a default constructor.
• Don’t think that a class’s methods must accept its own fields’ values as parameters or
return values to its own fields. When a class contains both fields and methods, each
method has direct access to every field within the class.
• Don’t create a class method that has a parameter with the same identifier as a class
field—yet. If you do, you will only be allowed to access the local variable within the
method, and you will not be able to access the field. You will be able to use the same
identifier and still access both values after you read the next chapter. For now, make
sure that the parameter in any method has a different identifier from any field.
where it is assigned to the object used in the method call. Add a closing curly
brace for the method.
service.setServiceDescription(service);
service.setPrice(price);
return service;
}
8. Save the file, compile it, and execute it. The execution looks no different from the
original version in Figure 3-28 earlier in this chapter, but by creating a method
that accepts an unfilled SpaService object and returns one filled with data, you
have made the main() method shorter and reused the data entry code.
(continued)
method
invoke
call
calling method
called method
abstraction
method header
declaration
method body
implementation
stub
access modifier
return type
return a value
fully qualified identifier
Key terms
97070_ch03_hr_110-169.indd 158 07/02/18 3:16 pm
5
Comparing Procedural and Object-Oriented Programming Concepts
Comparing Procedural and Object-Oriented
Programming Concepts
Procedural programming and object-oriented programming describe two different
approaches to writing computer programs.
Procedural Programming
Procedural programming is a style of programming in which operations are executed one
after another in sequence.
The typical procedural program defines and uses named computer memory locations that
are called variables. Variables hold the data a program uses. For example, data might be
read from an input device and stored in a location the programmer has named rateOfPay.
The variable value might be used in an arithmetic statement, used as the basis for a
decision, sent to an output device, or have other operations performed with it. The data
stored in a variable can change, or vary, during a program’s execution.
For convenience, the individual operations used in a computer program are often grouped
into logical units called procedures. For example, a series of four or five comparisons and
calculations that together determine a person’s federal withholding tax value might be
grouped as a procedure named calculateFederalWithholding(). (As a convention, this
book will show parentheses following every procedure name.) As a procedural computer
executes its statements, it can sometimes pause to call a procedure. When a program
The false statement is #3. A language translator finds syntax errors, but logic
errors can still exist in a program that is free of syntax errors.
TWO TRUTHS & A LIE
Learning Programming Terminology
In each “Two Truths & a Lie” section, two of the numbered statements are true, and
one is false. Identify the false statement and explain why it is false.
1. Unlike a low-level programming language, a high-level programming language
allows you to use a vocabulary of reasonable terms instead of the sequences
of on-and-off switches that perform the corresponding tasks.
2. A syntax error occurs when you violate the rules of a language; locating and
repairing all syntax errors is part of the process of debugging a program.
3. Logic errors are fairly easy to find because the software that translates a
program finds all the logic errors for you.
97070_ch01_hr_001-048.indd 5 07/02/18 3:21 pm
77
Using the Scanner Class to Accept Keyboard Input
It is legal to write a single prompt that requests multiple input values—for example,
Please enter your age, area code, and zip code >>. The user could then enter the three
values separated with spaces, tabs, or Enter key presses. The values would be interpreted
as separate tokens and could be retrieved with three separate nextInt() method calls.
However, asking a user to enter multiple values is more likely to lead to mistakes. For
example, if a program asks a user to enter a name, address, and birthdate all at once, the
user is likely to forget one of the values or to enter them in the wrong order. This book will
follow the practice of using a separate prompt for each input value required.
Pitfall: Using nextLine() Following One of the Other Scanner
Input Methods
You can encounter a problem when you use one of the numeric Scanner class retrieval
methods or the next() method before you use the nextLine() method. Consider the pro-
gram in Figure 2-19. It is identical to the one in Figure 2-17, except that the user is asked for
an age before being asked for a name. Figure 2-20 shows a typical execution.
Figure 2-19 The GetUserInfo2 class
import java.util.Scanner;
public class GetUserInfo2
{
public static void main(String[] args)
{
String name;
int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter your age >> ");
age = inputDevice.nextInt();
System.out.print("Please enter your name >> ");
name = inputDevice.nextLine();
System.out.println("Your name is " + name +
" and you are " + age + " years old.");
}
}
If you accept numeric input
prior to string input, the
string input is ignored
unless you take special
action.
Don’t Do It
Figure 2-20 Typical execution of the GetUserInfo2 program
97070_ch02_hr_049-109.indd 77 07/02/18 3:05 pm
TWo TRUTHs & A LIE quizzes appear
after each chapter section, with answers
provided� The quiz contains three state-
ments based on the preceding section of
text—two statements are true and one is
false� Answers give immediate feedback
without “giving away” answers to the
multiple-choice questions and programming
problems later in the chapter� Students also
have the option to take these quizzes in
MindTap�
doN’T do IT sections at the end of
each chapter list advice for avoiding
common programming errors�
THE doN’T do IT ICoN illustrates
how NOT to do something—for
example, having a dead code path
in a program� This icon provides a
visual jolt to the student, emphasizing
that particular figures are NOT to be
emulated and making students more
careful to recognize problems in
existing code�
F E AT U R E sF E AT U R E s
97070_fm_hr_i-xxiv.indd 21 27/02/18 7:34 pm
xxii
Assessment
160
Using Methods, Classes, and ObjectsC h a p t e r 3
• A constructor establishes an object and provides specific initial values for the object’s
data fields. A constructor always has the same name as the class of which it is a member.
By default, numeric fields are set to 0 (zero), character fields are set to Unicode
‘\u0000’, Boolean fields are set to false, and object type fields are set to null.
• A class is an abstract, programmer-defined data type, similar to Java’s built-in, primitive
data types.
Review Questions
1. In Java, methods must include all of the following except _____________.
a. a call to another method
b. a declaration
c. curly braces
d. a body
2. All method declarations contain _____________.
a. arguments
b. one or more explicitly named access specifiers
c. parentheses
d. the keyword static
3. A public static method named computeSum() is located in ClassA. To call the
method from within ClassB, use the statement _____________.
a. ClassA.computeSum();
b. ClassB(computeSum());
c. ComputeSum(ClassA);
d. You cannot call computeSum() from within ClassB.
4. Which of the following method declarations is correct for a static method
named displayFacts() if the method receives an int argument?
a. public static int displayFacts()
b. public void displayFacts(int data)
c. public static void displayFacts(int data)
d. Two of these are correct.
5. The method with the declaration public static int aMethod(double d) is a
method type of _____________.
a. static
b. int
c. double
d. You cannot determine the method type.
97070_ch03_hr_110-169.indd 160 07/02/18 3:25 pm
163
Exercises
Exercises
Programming Exercises
1. Suppose that you have created a program with only the following variables.
int x = 2;
int y = 3;
Suppose that you also have a method with the following header:
public static void mathMethod(int x)
Which of the following method calls are legal?
a. mathMethod(x);
b. mathMethod(y);
c. mathMethod(x, y);
d. mathMethod(x + y);
e. mathMethod(12L);
f. mathMethod(12);
g. mathMethod(12.2);
h. mathMethod();
i. mathMethod(a);
j. mathMethod(a / x);
2. Suppose that you have created a program with only the following variables.
int age = 34;
int weight = 180;
double height = 5.9;
Suppose that you also have a method with the following header:
public static void calculate(int age, double size)
Which of the following method calls are legal?
a. calculate(age, weight);
b. calculate(age, height);
c. calculate(weight, height);
d. calculate(height, age);
e. calculate(45.5, 120);
f. calculate(12, 120.2);
g. calculate(age, size);
h. calculate(2, 3);
i. calculate(age);
j. calculate(weight, weight);
3. Suppose that a class named Bicycle contains a private nonstatic integer named
height, a public nonstatic String named model, and a public static integer named
wheels. Which of the following are legal statements in a class named BicycleDemo
that has instantiated an object as Bicycle myBike = new Bicycle();?
a. myBike.height = 26;
b. myBike.model = "Cyclone";
c. myBike.wheels = 3;
d. myBike.model = 108;
e. Bicycle.height = 24;
f. Bicycle.model = "Hurricane";
g. Bicycle.int = 3;
h. Bicycle.model = 108;
i. Bicycle.wheels = 2;
j. Bicycle yourBike = myBike;
97070_ch03_hr_110-169.indd 163 07/02/18 3:25 pm
I found the author’s explanation of difficult topics
to be very clear and thorough.
—Leslie spivey,
Edison Community College
PRoGRAMMING ExERCIsEs
provide opportunities to practice
concepts� These exercises
increase in difficulty and allow
students to explore each major
programming concept presented
in the chapter� Additional coding
labs and snippets are available
in the MindTap�
REVIEW QUEsTIoNs
test student
comprehension of
the major ideas and
techniques presented�
Twenty questions
follow each chapter�
97070_fm_hr_i-xxiv.indd 22 27/02/18 7:34 pm
xxiii

48
Creating Java ProgramsC h a p t e r 1
Appendix D contains information about generating random numbers. To fully
understand the process, you must learn more about Java classes and methods.
For now, however, you can copy the following statement to generate and use a
dialog box that displays a random number between 1 and 10:
JOptionPane.showMessageDialog(null,"The number is "+
(1 + (int)(Math.random() * 10)));
Write a Java application that displays two dialog boxes in sequence. The first asks
you to think of a number between 1 and 10. The second displays a randomly
generated number; the user can see whether his or her guess was accurate.
(In future chapters, you will improve this game so that the user can enter a
guess and the program can determine whether the user was correct. If you
wish, you also can tell the user how far off the guess was, whether the guess was
high or low, and provide a specific number of repeat attempts.) Save the file as
RandomGuess.java.
Case Problems
The case problems in this section introduce two fictional businesses. Throughout this
book, you will create increasingly complex classes for these businesses that use the newest
concepts you have mastered in each chapter.
1. Carly’s Catering provides meals for parties and special events. Write a program
that displays Carly’s motto, which is “Carly’s makes the food that makes it a
party.” Save the file as CarlysMotto.java. Create a second program that displays
the motto surrounded by a border composed of asterisks. Save the file as
CarlysMotto2.java.
2. Sammy’s Seashore Supplies rents beach equipment such as kayaks, canoes, beach
chairs, and umbrellas to tourists. Write a program that displays Sammy’s motto,
which is “Sammy’s makes it fun in the sun.” Save the file as SammysMotto.java.
Create a second program that displays the motto surrounded by a border
composed of repeated Ss. Save the file as SammysMotto2.java.
97070_ch01_hr_001-048.indd 48 07/02/18 3:23 pm
47
Exercises
Debugging Exercises
1. Each of the following files in the Chapter01 folder in your downloadable
student files has syntax and/or logic errors. In each case, determine the
problem and fix the errors. After you correct the errors, save each file using
the same filename preceded with Fix. For example, DebugOne1.java will
become FixDebugOne1.java.
a. DebugOne1.java
b. DebugOne2.java
c. DebugOne3.java
d. DebugOne4.java
When you change a filename, remember to change every instance of the class name within the file so
that it matches the new filename. In Java, the filename and class name must always match.
Game Zone
1. In 1952, A. S. Douglas wrote his University of Cambridge Ph.D. dissertation on
human-computer interaction, and created the first graphical computer game—a
version of Tic-Tac-Toe. The game was programmed on an EDSAC vacuum-tube
mainframe computer. The first computer game is generally assumed to be
“Spacewar!”, developed in 1962 at MIT; the first commercially available video
game was “Pong,” introduced by Atari in 1973. In 1980, Atari’s “Asteroids”
and “Lunar Lander” became the first video games to be registered in the U.S.
Copyright Office. Throughout the 1980s, players spent hours with games that
now seem very simple and unglamorous; do you recall playing “Adventure,”
“Oregon Trail,” “Where in the World Is Carmen Sandiego?,” or “Myst”?
Today, commercial computer games are much more complex; they require
many programmers, graphic artists, and testers to develop them, and large
management and marketing staffs are needed to promote them. A game might
cost many millions of dollars to develop and market, but a successful game might
earn hundreds of millions of dollars. Obviously, with the brief introduction
to programming you have had in this chapter, you cannot create a very
sophisticated game. However, you can get started.
For games to hold your interest, they almost always include some random,
unpredictable behavior. For example, a game in which you shoot asteroids loses
some of its fun if the asteroids follow the same, predictable path each time you
play the game. Therefore, generating random values is a key component in
creating most interesting computer games.
97070_ch01_hr_001-048.indd 47 07/02/18 3:22 pm
GAME ZoNE ExERCIsEs
are included at the end of
each chapter� Students
can create games as an
additional entertaining way to
understand key programming
concepts�
dEBUGGING ExERCIsEs
are included with each chapter
because examining programs
critically and closely is a crucial
programming skill� Students
can download these exercises
at www.Cengagebrain.com�
These files are also available
to instructors through
sso.cengage.com�
CAsE PRoBLEMs provide
opportunities to build more
detailed programs that
continue to incorporate
increasing functionality
throughout the book�
A s s E s s M E N T
97070_fm_hr_i-xxiv.indd 23 27/02/18 7:34 pm
97070_fm_hr_i-xxiv.indd 24 27/02/18 7:34 pm
C H A P T E R 1
Creating Java
Programs
Upon completion of this chapter, you will be able to:
Define basic programming terminology
Compare procedural and object-oriented programming
Describe the features of the Java programming language
Analyze a Java application that produces console output
Compile a Java class and correct syntax errors
Run a Java application and correct logic errors
Add comments to a Java class
Create a Java application that produces GUI output
Find help
97070_ch01_hr_001-048.indd 1 24/02/18 3:27 pm
2
Creating Java ProgramsC H A P T E R 1
Learning Programming Terminology
A computer program is a set of instructions that you write to tell a computer what to do.
Computer equipment, such as a monitor or keyboard, is hardware, and programs are
software. A program that performs a task for a user (such as calculating and producing
paychecks, word processing, or playing a game) is application software; a program that
manages the computer itself (such as Windows or Linux) is system software. The logic
behind any computer program, whether it is an application or system program, determines
the exact order of instructions needed to produce desired results. Much of this book
describes how to develop the logic to create programs that are application software, called
applications (or, especially if used on a mobile device, apps) for short.
You can write computer programs in a high-level programming language such as
Java, Visual Basic, C++, or C#. A high-level programming language allows you to use
English-like, easy-to-remember terms such as read, write, and add. These languages are
called high-level languages to distinguish them from low-level languages that correspond
closely to a computer’s circuitry and are not as easily read or understood. Because they
correspond to circuitry, low-level languages must be customized for every type of machine
on which a program runs.
All computer programs ultimately are converted to the lowest level language, which
is machine language. Machine language, or machine code, is the most basic set of
instructions that a computer can execute. Each type of processor (the internal hardware
that handles computer instructions) has its own set of machine language instructions.
Programmers often describe machine language using 1s and 0s to represent the on-and-off
circuitry of computer systems.
The system that uses only 1s and 0s is the binary numbering system. Appendix B describes the binary
system in detail. Later in this chapter, you will learn that bytecode is the name for the binary code
created when Java programs are converted to machine language.
Every programming language has its own syntax, or rules about how language elements are
combined correctly to produce usable statements. For example, depending on the specific
high-level language, you might use the verb print or write to produce output. All languages
have a specific, limited vocabulary (the language’s keywords) and a specific set of rules for
using that vocabulary. When you are learning a computer programming language, such as
Java, C++, or Visual Basic, you are learning the vocabulary and syntax for that language.
Using a programming language, programmers write a series of program statements, which
are similar to English sentences. The statements carry out the program’s tasks. Program
statements are also known as commands because they are orders to the computer, such as
Output this word or Add these two numbers.
After the program statements are written in a high-level programming language, a
computer program called a compiler or interpreter translates the statements into machine
language. A compiler translates an entire program before carrying out any statements,
or executing them, whereas an interpreter translates one program statement at a time,
executing a statement as soon as it is translated.
97070_ch01_hr_001-048.indd 2 24/02/18 3:27 pm
3
Learning Programming Terminology
Compilers and interpreters issue one or more error messages each time they encounter
an invalid program statement—that is, a statement containing a syntax error, or misuse
of the language. Examples of syntax errors include misspelling a keyword or omitting a
word that a statement requires. When a syntax error is detected, the programmer can
correct the error and attempt another translation. Repairing all syntax errors is the first
part of the process of debugging a program—freeing the program of all flaws or errors,
also known as bugs. Figure 1-1 illustrates the steps a programmer takes while developing
an executable program. You will learn more about debugging Java programs later in this
chapter.
As Figure 1-1 shows, you might write a program that compiles successfully (that is, it
contains no syntax errors), but it still might not be a correct program because it might
contain one or more logic errors. A logic error is a bug that allows a program to run, but
that causes it to operate incorrectly. Correct logic requires that all the right commands be
issued in the appropriate order. Examples of logic errors include multiplying two values
when you meant to divide them or producing output prior to obtaining the appropriate
input. When you develop a program of any significant size, you should plan its logic before
you write any program statements.
Correcting logic errors is much more difficult than correcting syntax errors. Syntax errors
are discovered by the language translator when you compile a program, but a program can
be free of syntax errors and execute while still retaining logic errors. Sometimes you can
find logic errors by carefully examining the structure of your program (when a group of
programmers do this together, it is called a structured walkthrough), but sometimes you
can identify logic errors only when you examine a program’s output. For example, if you
know an employee’s paycheck should contain the value $4,000, but when you examine a
payroll program’s output you see that it holds $40, then a logic error has occurred. Perhaps
an incorrect calculation was performed, or maybe the hours worked value was output
by mistake instead of the net pay value. When output is incorrect, the programmer must
carefully examine all the statements within the program, revise or move the offending
statements, and translate and test the program again.
Whether you use a compiler or interpreter often depends on the programming language you use.
For example, C++ is a compiled language, and Visual Basic is an interpreted language. Each type of
translator has its supporters; programs written in compiled languages execute more quickly, whereas
programs written in interpreted languages can be easier to develop and debug. Java uses the best of
both technologies: a compiler to translate your programming statements and an interpreter to read the
compiled code line by line when the program executes (also called at run time).
Programmers call some logic errors semantic errors. For example, if you misspell a programming
language word, you commit a syntax error, but if you use a correct word in the wrong context, you
commit a semantic error.
Just because a program produces correct output does not mean it is free from logic errors. For
example, suppose that a program should multiply two values entered by the user, that the user
enters two 2s, and the output is 4. The program might actually be adding the values by mistake.
The programmer would discover the logic error only by entering different values, such as 5 and 7,
and examining the result.
97070_ch01_hr_001-048.indd 3 24/02/18 3:27 pm
4
Creating Java ProgramsC H A P T E R 1
Figure 1-1 The program development process
De
bu
gg
in
g
pr
oc
es
s
De
bu
gg
in
g
pr
oc
es
s
Yes
Yes
No
No
Use translating software (a compiler or
interpreter) that translates programming
language statements to machine language
Examine list of
syntax errors
Write program language statements
that correspond to the logic
Examine
program output
Are there runtime
or output errors?
Can all statements
be successfully
translated?
Plan program logic
Execute the program
97070_ch01_hr_001-048.indd 4 24/02/18 3:27 pm
5
Comparing Procedural and Object-Oriented Programming Concepts
Comparing Procedural and Object-Oriented
Programming Concepts
Procedural programming and object-oriented programming describe two different
approaches to writing computer programs.
Procedural Programming
Procedural programming is a style of programming in which operations are executed one
after another in sequence.
The typical procedural program defines and uses named computer memory locations that
are called variables. Variables hold the data a program uses. For example, data might be
read from an input device and stored in a location the programmer has named rateOfPay.
The variable value might be used in an arithmetic statement, used as the basis for a
decision, sent to an output device, or have other operations performed with it. The data
stored in a variable can change, or vary, during a program’s execution.
For convenience, the individual operations used in a computer program are often grouped
into logical units called procedures. For example, a series of four or five comparisons and
calculations that together determine a person’s federal withholding tax value might be
grouped as a procedure named calculateFederalWithholding(). (As a convention, this
book will show parentheses following every procedure name.) As a procedural computer
executes its statements, it can sometimes pause to call a procedure. When a program
The false statement is #3. A language translator finds syntax errors, but logic
errors can still exist in a program that is free of syntax errors.
TWO TRUTHS & A LIE
Learning Programming Terminology
In each “Two Truths & a Lie” section, two of the numbered statements are true, and
one is false. Identify the false statement and explain why it is false.
1. Unlike a low-level programming language, a high-level programming language
allows you to use a vocabulary of reasonable terms instead of the sequences
of on-and-off switches that perform the corresponding tasks.
2. A syntax error occurs when you violate the rules of a language; locating and
repairing all syntax errors is part of the process of debugging a program.
3. Logic errors are fairly easy to find because the software that translates a
program finds all the logic errors for you.
97070_ch01_hr_001-048.indd 5 24/02/18 3:27 pm
6
Creating Java ProgramsC H A P T E R 1
calls a procedure, the current logic is temporarily suspended so that the procedure’s
commands can execute. A single procedural program might contain any number of
procedure calls. Procedures are also called modules, methods, functions, and subroutines.
Users of different programming languages tend to use different terms. As you will learn
later in this chapter, Java programmers most frequently use the term method.
Object-Oriented Programming
Object-oriented programming is an extension of procedural programming in which you
take a slightly different approach to writing computer programs. Writing object-oriented
programs involves:
• Creating classes, which are blueprints for objects
• Creating objects, which are specific instances of those classes
• Creating applications that manipulate or use those objects
Programmers use OO as an abbreviation for object-oriented; it is pronounced “oh oh.” Object-oriented
programming is abbreviated OOP, and pronounced to rhyme with soup.
Originally, object-oriented programming was used most frequently for two major types of
applications:
• Computer simulations, which attempt to mimic real-world activities so that their
processes can be improved or so that users can better understand how the real-world
processes operate
• Graphical user interfaces, or GUIs (pronounced gooeys), which allow users to interact
with a program in a graphical environment
Thinking about objects in these two types of applications makes sense. For example, a city
might want to develop a program that simulates traffic patterns and controls traffic signals
to help prevent tie-ups. Programmers would create classes for objects such as cars and
pedestrians that contain their own data and rules for behavior. For example, each car has a
speed and a method for changing that speed. The specific instances of cars could be set in
motion to create a simulation of a real city at rush hour.
Creating a GUI environment for users is also a natural use for object orientation. It is easy
to think of the components a user manipulates on a computer screen, such as buttons
and scroll bars, as similar to real-world objects. Each GUI object contains data—for
example, a button on a screen has a specific size and color. Each object also contains
behaviors—for example, each button can be clicked and reacts in a specific way when
clicked. Some people consider the term object-oriented programming to be synonymous
with GUI programming, but object-oriented programming means more. Although many
GUI programs are object oriented, not all object-oriented programs use GUI objects.
Modern businesses use object-oriented design techniques when developing all sorts of
97070_ch01_hr_001-048.indd 6 24/02/18 3:27 pm
7
Comparing Procedural and Object-Oriented Programming Concepts
business applications, whether they are GUI applications or not. In the first 13 chapters of
this book, you will learn object-oriented techniques that are appropriate for any program
type; in the last chapters, you will apply what you have learned about those techniques
specifically to GUI applications.
Understanding object-oriented programming requires grasping three basic concepts:
• Encapsulation as it applies to classes as objects
• Inheritance
• Polymorphism
Understanding Classes, Objects, and Encapsulation
In object-oriented terminology, a class is a group or collection of objects with common
properties. In the same way that a blueprint exists before any houses are built from it, and
a recipe exists before any cookies are baked from it, a class definition exists before any
objects are created from it. A class definition describes what attributes its objects will have
and what those objects will be able to do. Attributes are the characteristics that define an
object; they are properties of the object. When you learn a programming language such as
Java, you learn to work with two types of classes: those that have already been developed by
the language’s creators and your own new, customized classes.
An object is a specific, concrete instance of a class. Creating an instance is called
instantiation. You can create objects from classes that you write and from classes written
by other programmers, including Java’s creators. The values contained in an object’s
properties often differentiate instances of the same class from one another. For example,
the class Automobile describes what Automobile objects are like. Some properties of the
Automobile class are make, model, year, and color. Each Automobile object possesses the
same attributes, but not necessarily the same values for those attributes. One Automobile
might be a 2014 white Ford Taurus and another might be a 2018 red Chevrolet Camaro.
Similarly, your dog has the properties of all Dogs, including a breed, name, age, and
whether the dog’s shots are current. The values of the properties of an object are referred
to as the object’s state. In other words, you can think of objects as roughly equivalent to
nouns (words that describe a person, place, or thing), and of their attributes as similar to
adjectives that describe the nouns.
When you understand an object’s class, you understand the characteristics of the object.
If your friend purchases an Automobile, you know it has a model name, and if your
friend gets a Dog, you know the dog has a breed. Knowing what attributes exist for classes
allows you to ask appropriate questions about the states or values of those attributes. For
example, you might ask how many miles the car gets per gallon, but you would not ask
whether the car has had shots. Similarly, in a GUI operating environment, you expect each
component to have specific, consistent attributes and methods, such as a window having a
title bar and a close button, because each component gains these properties as a member
of the general class of GUI components. Figure 1-2 shows the relationship of some Dog
objects to the Dog class.
97070_ch01_hr_001-048.indd 7 24/02/18 3:27 pm
8
Creating Java ProgramsC H A P T E R 1
Besides defining properties, classes define methods their objects can use. A method is a
self-contained block of program code that carries out some action, similar to a procedure
in a procedural program. An Automobile, for example, might have methods for moving
forward, moving backward, and determining the status of its gas tank. Similarly, a Dog
might have methods for walking, eating, and determining its name, and a program’s
GUI components might have methods for maximizing and minimizing them as well as
determining their size. In other words, if objects are similar to nouns, then methods are
similar to verbs.
In object-oriented classes, attributes and methods are encapsulated into objects.
Encapsulation refers to two closely related object-oriented notions:
• Encapsulation is the enclosure of data and methods within an object. Encapsulation
allows you to treat all of an object’s methods and data as a single entity. Just as an actual
dog contains all of its attributes and abilities, so would a program’s Dog object.
• Encapsulation also refers to the concealment of an object’s data and methods from
outside sources. Concealing data is sometimes called information hiding, and concealing
how methods work is implementation hiding; you will learn more about both terms in
the chapter “Using Methods, Classes, and Objects.” Encapsulation lets you hide specific
object attributes and methods from outside sources and provides the security that keeps
data and methods safe from inadvertent changes.
By convention, programmers using Java begin their class names with an uppercase letter. Thus,
the class that defines the attributes and methods of an automobile probably would be named
Automobile, and the class for dogs probably would be named Dog. This convention, however, is
not required to produce a workable program.
Figure 1-2 Dog class definition and some objects created from it
Dog class definition Dog class instances (objects)
Every Dog that is
created will have a:
Ginger
6
Akita
Up to date
Bowser
2
Retriever
Up to date
Roxy
1
Beagle
Up to date
Name
Age
Breed
Shot status
is
to
ck
.c
om
/G
lo
ba
lP
is
to
ck
.c
om
/G
lo
ba
lP
is
to
ck
.c
om
/o
la
se
r
97070_ch01_hr_001-048.indd 8 24/02/18 3:27 pm
9
Comparing Procedural and Object-Oriented Programming Concepts
If an object’s methods are well written, the user can be unaware of the low-level details
of how the methods are executed, and the user must simply understand the interface
or interaction between the method and the object. For example, if you can fill your
Automobile with gasoline, it is because you understand the interface between the gas pump
nozzle and the vehicle’s gas tank opening. You don’t need to understand how the pump
works mechanically or where the gas tank is located inside your vehicle. If you can read
your speedometer, it does not matter how the displayed figure is calculated. As a matter of
fact, if someone produces a superior, more accurate speed-determining device and inserts
it in your Automobile, you don’t have to know or care how it operates, as long as your
interface remains the same. The same principles apply to well-constructed classes used in
object-oriented programs—programs that use classes only need to work with interfaces.
Understanding Inheritance and Polymorphism
An important feature of object-oriented program design that differentiates it from procedural
program design is inheritance—the ability to create classes that share the attributes and
methods of existing classes, but with more specific features. For example, Automobile is a
class, and all Automobile objects share many traits and abilities. Convertible is a class that
inherits from the Automobile class; a Convertible is a type of Automobile that has and can
do everything a “plain” Automobile does—but with an added ability to lower its top. (In turn,
Automobile inherits from the Vehicle class.) Convertible is not an object—it is a class.
A specific Convertible is an object—for example, my1967BlueMustangConvertible.
Inheritance helps you understand real-world objects. For example, the first time you
encounter a convertible, you already understand how the ignition, brakes, door locks,
and other systems work because you realize that a convertible is a type of automobile.
Therefore, you need to be concerned only with the attributes and methods that are “new”
with a convertible. The advantages in programming are the same—you can build new
classes based on existing classes and concentrate on the specialized features you are adding.
A final important concept in object-oriented terminology (that does not exist in procedural
programming terminology) is polymorphism. Literally, polymorphism means many
forms—it describes the feature of languages that allows the same word or symbol to be
interpreted correctly in different situations based on the context. For example, although
the classes Automobile, Sailboat, and Airplane all inherit from Vehicle, methods
such as turn and stop work differently for instances of those classes. The advantages of
polymorphism will become more apparent when you begin to create GUI applications
containing features such as windows, buttons, and menu bars. In a GUI application, it is
convenient to remember one method name, such as setColor or setHeight, and have it
work correctly no matter what type of object you are modifying.
When you see a plus sign (+) between two numbers, you understand they are being added. When you see
it carved in a tree between two names, you understand that the names are linked romantically. Because
the symbol has diverse meanings based on context, it is polymorphic. Chapters 10 and 11 provide more
information about inheritance and polymorphism and how they are implemented in Java. Using Java, you
can write either procedural or object-oriented programs. In this book, you will learn about how to do both.
97070_ch01_hr_001-048.indd 9 24/02/18 3:27 pm
10
Creating Java ProgramsC H A P T E R 1
Features of the Java Programming Language
Java was developed by Sun Microsystems as an object-oriented language for
general-purpose business applications and for interactive, World Wide Web-based Internet
applications. (Sun was later acquired by Oracle Corporation.) Some of the advantages that
make Java a popular language are its security features and the fact that it is architecturally
neutral. That means that, unlike many other languages, you can use Java to write a program
that runs on any operating system (such as Windows, Mac OS, or Linux) or device (such as
PCs, phones, and tablet computers).
Java can be run on a wide variety of computers and devices because it does not
execute instructions on a computer directly. Instead, Java runs on a hypothetical
computer known as the Java Virtual Machine (JVM). When programmers call the
JVM hypothetical, they mean it is not a physical entity created from hardware, but is
composed only of software.
Figure 1-3 shows the Java environment. Programming statements written in a high-level
programming language are source code. When you write a Java program, you first
construct the source code using a plain text editor such as Notepad, or you can use
a development environment such as Eclipse, NetBeans, or jGRASP. A development
environment is a set of tools that help you write programs by providing such features as
displaying a language’s keywords in color.
The Java source code statements you write are saved in a file; then, the Java compiler
converts the source code into a binary program of bytecode. A program called the
Java interpreter then checks the bytecode and communicates with the operating
system, executing the bytecode instructions line by line within the JVM. Because
Watch the video Object-Oriented Programming.
The false statement is #3. Inheritance is the ability to create classes that share
the attributes and methods of existing classes, but with more specific features;
polymorphism describes the ability to use one term to cause multiple actions.
TWO TRUTHS & A LIE
Comparing Procedural and Object-Oriented Programming Concepts
1. An instance of a class is a created object that possesses the attributes and
methods described in the class definition.
2. Encapsulation protects data by hiding it within an object.
3. Polymorphism is the ability to create classes that share the attributes and
methods of existing classes, but with more specific features.
97070_ch01_hr_001-048.indd 10 24/02/18 3:27 pm
11
Features of the Java Programming Language
the Java program is isolated from the operating system, it is also insulated from
the particular hardware on which it is run. Because of this insulation, the JVM
provides security against intruders accessing your computer’s hardware through
the operating system. Therefore, Java is more secure than other languages. Another
advantage provided by the JVM means less work for programmers—when using
other programming languages, software vendors usually have to produce multiple
versions of the same product (a Windows version, Macintosh version, UNIX version,
Linux version, and so on) so all users can run the program. With Java, one program
version runs on all these platforms. “Write once, run anywhere” (WORA) is the slogan
developed by Sun Microsystems to describe the ability of one Java program version to
work correctly on multiple platforms.
Java also is simpler to use than many other object-oriented languages. Java is modeled after
C++. Although neither language is easy to read or understand on first exposure, Java does
eliminate some of the most difficult-to-understand features in C++, such as pointers and
multiple inheritance.
Figure 1-3 The Java environment
Java Source Code
Source code is
stored on a disk in
a file with a name
ending in .java
Compiler creates
bytecode that
is stored on a
disk in a file with
a name ending in
.class
JVM (named java.exe)
performs security checks
and translates bytecode to
machine language, which
executes
Java Compiler
Java Virtual Machine
Java Interpreter
Computer Operating
System
97070_ch01_hr_001-048.indd 11 24/02/18 3:27 pm
12
Creating Java ProgramsC H A P T E R 1
You can write two types of Java applications:
• Console applications, which support character or text output to a computer screen
• Windowed applications, which create a GUI with elements such as menus, toolbars,
and dialog boxes
Console applications are the easier applications to create; you start using them in the next
section. You will create your first simple GUI application later in this chapter.
Analyzing a Java Application that Produces
Console Output
At first glance, even the simplest Java application involves a fair amount of confusing
syntax. Consider the application in Figure 1-4. This program is written on seven lines,
and its only task is to display First Java application on the screen.
In program code in figures in this book, Java keywords as well as true, false, and null are
blue, and all other program elements are black. A complete list of Java keywords is shown later in this
chapter.
Figure 1-4 The First class
public class First
{
public static void main(String[] args)
{
System.out.println("First Java application");
}
}
The false statement is #1. Java was developed to be architecturally neutral, which
means that you can use Java to write a program that will run on any platform.
TWO TRUTHS & A LIE
Features of the Java Programming Language
1. Java was developed to be architecturally neutral, which means that anyone
can build an application without extensive study.
2. After you write a Java program, the compiler converts the source code into a
binary program of bytecode.
3. You can create both console applications and windowed applications using Java.
97070_ch01_hr_001-048.indd 12 24/02/18 3:27 pm
13
Analyzing a Java Application that Produces Console Output
Figure 1-5 Anatomy of a Java statement
System.out.println("First Java application");
System is a class.
out is a property of the
System class.
Dots separate classes,
objects, and methods.
Every Java statement ends
with a semicolon.
println() is a method.
Method names are always
followed by parentheses.
"First Java application"
is a literal string that is the argument
to the println() method.
The code for every complete program shown in this book is available in a set of student files you can
download so that you can execute the programs on your own computer.
Understanding the Statement that Produces the Output
Although the program in Figure 1-4 occupies several lines, it contains only one Java
programming statement. This statement does the actual work of the program:
System.out.println(“First Java application”);
Like all Java statements, this one ends with a semicolon. Most Java programming
statements can be spread across as many lines as you choose, as long as you place line
breaks in appropriate places. For example, in the program in Figure 1-4, you could place a
line break before or after the opening parenthesis, or before or after the closing parenthesis.
However, you usually want to place a short statement on a single line.
The text First Java application is a literal string of characters—a series of characters that
will appear in output exactly as entered. Any literal string in Java is written between double
quotation marks. In Java, a literal string cannot be broken and placed on multiple lines.
Figure 1-5 labels this string and the other parts of the statement.
The string First Java application appears within parentheses because the string is
an argument to a method, and arguments to methods always appear within parentheses
following the method name. Arguments are pieces of information that are sent into a
method. The act of sending arguments to a method is called passing arguments to the
method.
As an analogy, consider placing a catalog order with a company that sells sporting
goods. Processing a catalog order is a method that consists of a set of standard
procedures—recording the order, checking the availability of the item, pulling the item
97070_ch01_hr_001-048.indd 13 24/02/18 3:27 pm
14
Creating Java ProgramsC H A P T E R 1
from the warehouse, and so on. Each catalog order also requires a set of data items,
such as which item number you are ordering and the quantity of the item desired; these
data items can be considered the arguments to the order-processing method. If you
order two of item 5432 from a catalog, you expect different results than if you order
1,000 of item 9008. Likewise, if you pass the argument “Happy Holidays” to a Java
display method, you expect different results than if you pass the argument “First Java
application”.
Within the statement System.out.println(“First Java application”);, the
method to which you are passing “First Java application” is named println().
The Java methods println() and print() both produce output. With println(),
after the output is displayed, the insertion point moves to the following line so that
subsequent output appears on a new line. With print(), however, the insertion
point does not advance to a new line, so subsequent output appears at the end of the
current line.
When you call a method, you always use parentheses following the method name. In
this book, you will learn about many methods that require arguments between their
parentheses, and many others for which you leave the parentheses empty. The println()
method can be used with no arguments when you want to output a blank line. Later in this
chapter, you will learn about a method named showMessageDialog() that requires two
arguments. Other methods require more.
Within the statement System.out.println(“First Java application”);, out is an
object that is a property of the System class, one that refers to the standard output
device for a system, normally the monitor. The out object itself is an instance of the
PrintStream class, which contains several methods, including println(). Technically,
you could create the out object and write the instructions within the println() method
yourself, but it would be time consuming, and the creators of Java assumed you would
want to frequently display output on a screen. Therefore, the System and PrintStream
classes, the out object, and the println() method were created as a convenience to the
programmer.
Within the statement System.out.println(“First Java application”);, System is a
class. Therefore, System defines attributes for System objects, just as the Dog class defines
the attributes for Dog objects. One of the System attributes is out. (You can probably guess
that another attribute is in and that it represents an input device.)
The dots (periods) in System.out.println() are used to separate the names of the
components in the statement. You will use this format repeatedly in your Java programs.
Java is case sensitive; the class named System is a completely different class from one
named system, SYSTEM, or even sYsTeM, and out is a different object from one named Out
or OUT. You must pay close attention to using correct uppercase and lowercase values when
you write Java programs.
So, the statement that displays the string “First Java application” contains a
class, an object reference, a method call, a method argument, and a statement-ending
semicolon, but the statement cannot stand alone; it is embedded within a class, as
shown in Figure 1-4.
97070_ch01_hr_001-048.indd 14 24/02/18 3:27 pm
15
Analyzing a Java Application that Produces Console Output
Understanding the First Class
Everything that you use within a Java program must be part of a class. When you write
public class First, you are defining a class for which you have chosen the name First.
You can define a Java class using any name or identifier you need, as long as it meets the
following requirements:
• A Java identifier must begin with a letter of the English alphabet, a non-English letter
(such as α or π), an underscore, or a dollar sign. A class name cannot begin with a digit.
• A Java identifier can contain only letters, digits, underscores, or dollar signs.
• A Java identifier cannot be a reserved keyword, such as public or class. (See Table 1-1
for a list of reserved keywords.)
• A Java identifier cannot be one of the following values: true, false, or null. These are
not keywords (they are primitive values), but they are reserved and cannot be used.
Java is based on Unicode, which is an international system of character representation. The term letter
indicates English-language letters as well as characters from Arabic, Greek, and other alphabets. You
can learn more about Unicode in Appendix B.
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
Table 1-1 Java reserved keywords
Although const and goto are reserved as keywords, they are not used in Java programs, and they
have no function. Both words are used in other languages and were reserved in case developers of
future versions of Java wanted to implement them.
It is a Java standard, although not a requirement, to begin class identifiers with an
uppercase letter and employ other uppercase letters as needed to improve readability.
(By contrast, method identifiers, like println(), conventionally begin with a lowercase
letter.) The style that joins words in which each word begins with an uppercase letter is
called Pascal casing, or sometimes upper camel casing. You should follow established
conventions for Java so your programs will be easy for other programmers to interpret and
follow. This book uses established Java programming conventions.
97070_ch01_hr_001-048.indd 15 24/02/18 3:27 pm
16
Creating Java ProgramsC H A P T E R 1
Table 1-2 lists some valid and conventional class names that you could use when writing
programs in Java. Table 1-3 provides some examples of class names that could be used in
Java (if you use these class names, the class will compile) but that are unconventional and
not recommended. Table 1-4 provides some class name examples that are illegal.
Class Name Description
Undergradstudent New words are not indicated with initial uppercase letters, making this
identifier difficult to read
Inventory_Item Underscore is not commonly used to indicate new words
BUDGET2019 Using all uppercase letters for class identifiers is not conventional
budget2019 Conventionally, class names do not begin with a lowercase letter
Table 1-3 Legal but unconventional and nonrecommended class names in Java
Class Name Description
Inventory Item Space character is illegal in an identifier
class class is a reserved word
2019Budget Class names cannot begin with a digit
phone# The number symbol (#) is illegal in an identifier
Table 1-4 Some illegal class names in Java
Class Name Description
Employee Begins with an uppercase letter
UnderGradStudent Begins with an uppercase letter, contains no spaces, and emphasizes
each new word with an initial uppercase letter
InventoryItem Begins with an uppercase letter, contains no spaces, and emphasizes
the second word with an initial uppercase letter
Budget2019 Begins with an uppercase letter and contains no spaces
Table 1-2 Some valid class names in Java
Figure 1-6 shows the parts of the First class shell in its first, second, and last lines—its
header, and its opening and closing curly braces. The header contains the keyword class,
which identifies First as a class. The keyword public is an access specifier. An access
specifier defines the circumstances under which a class can be accessed and the other
classes that have the right to use a class. Public access is the most liberal type of access;
you will learn about public access and other types of access in the chapter “Using Methods,
Classes, and Objects.”
97070_ch01_hr_001-048.indd 16 24/02/18 3:27 pm
17
Analyzing a Java Application that Produces Console Output
After the class header, you enclose the contents of a class within curly braces ({ and }); any data
items and methods between the curly braces make up the class body. A class body can be
composed of any number of data items and methods. In Figure 1-6 (and again in Figure 1-7), the
class First contains four lines between the curly braces; these will be described in the next section.
Understanding the main() Method
The main() method in Figure 1-7 is made up of the four lines between the curly braces of
the First class.
Figure 1-6 The parts of a typical class
{
public static void main(String[] args)
{
System.out.println("First Java application");
}
}
public class First
public is an access
specifier.
The keyword class
identifies First as
a class.
First is the name of
the class.
Everything
between the
curly braces is
the class body.
This line is
the class
header.
Figure 1-7 The parts of a typical main() method
public class First
{
public static void main(String[] args)

{
System.out.println("First Java application");
}
}
public is an access specifier.
args is the identifier of the array of
Strings that is the argument to
this method.
This line is the
method header.
Everything between
the curly braces is the
method body.
static means this method works without
instantiating an object of the class.
void is the method’s return type.
The square brackets mean the
argument to this method is an
array of Strings. Chapters 8
and 9 provide more information
about Strings and arrays.
String is a class. Any
arguments to this method
must be String objects.
97070_ch01_hr_001-048.indd 17 24/02/18 3:27 pm
18
Creating Java ProgramsC H A P T E R 1
The method header is public static void main(String[] args). The meaning and
purpose of each of the terms used in the method header will become clearer as you
complete this textbook; a brief explanation will suffice for now.
• The keyword public is an access specifier, just as it is when you use it to define the
First class.
• The keyword static means that a method is accessible and usable even though no
objects of the class exist.
• The keyword void indicates that the main() method does not return any value when it
is called. This doesn’t mean that main() doesn’t produce output—in fact, the method
does. It only means that the main() method does not send any value back to any
other method that might use it. You will learn more about return values in the chapter
“Methods, Classes, and Objects.”
• The name of the method is main(). As is the convention with Java methods, its
identifier begins with a lowercase letter. Not all classes have a main() method; in
fact, many do not. All Java applications, however, must include a class containing a
public method named main(), and most Java applications have additional classes and
methods. When you execute a Java application, the JVM always executes the main()
method first.
• In the method header, the contents between the parentheses, String[] args,
represent the type of argument that can be passed to the main() method, just as
the string “First Java application” is an argument passed to the println()
method. String is a Java class that can be used to hold character strings (according
to Java convention, it begins with an uppercase letter, like other classes). The
brackets following String mean that argument is a list of Strings. You will learn
more about the String class and lists, or arrays, in Chapters 7, 8, and 9.) The
identifier args is used to hold any String objects that might be sent to the main()
method. The main() method could do something with those arguments, such as
display them, but in Figure 1-4, the main() method does not actually use the args
identifier. Nevertheless, you must place an identifier within the main() method’s
parentheses. The identifier does not need to be named args—it could be any legal
Java identifier—but the name args is traditional.
In this book, you won’t pass any arguments to a program’s main() method, but when you run
a program, you could. Even though you pass no arguments, the main() method must contain
String[] and a legal identifier (such as args) within its parentheses.
The simple application originally shown in Figure 1-4 has many pieces to remember.
However, for now you can use the Java code shown in Figure 1-8 as a shell, in which you
replace AnyClassName with a class name you choose and the line /******/ with any
statements that you want to execute.
97070_ch01_hr_001-048.indd 18 24/02/18 3:27 pm
19
Analyzing a Java Application that Produces Console Output
Indent Style
In general, whitespace is optional in Java. Whitespace is any combination of nonprinting
characters. You use whitespace to organize your program code and make it easier to
read. You can insert whitespace between words or lines in your program code by typing
spaces, tabs, or blank lines because the compiler ignores these extra spaces. However, you
cannot use whitespace within an identifier or keyword, or surrounding the dots in any
class-object-method combination.
For every opening curly brace ({) in a Java program, there must be a corresponding closing
curly brace (}), but the placement of the opening and closing curly braces is not important
to the compiler. For example, the following class executes in exactly the same way as the
one shown in Figure 1-4. The only difference is the layout of the braces—the line breaks
occur in different locations.
public class First{
public static void main(String[] args){
System.out.println("First Java application");
}
}
The indent style shown in the preceding example, in which opening braces do not stand
alone on separate lines, is known as the K & R style and is named for Kernighan and
Ritchie, who wrote the first book about the C programming language. The indent style
shown in Figures 1-4, 1-6, and 1-7, in which curly braces are aligned and each occupies
its own line, is called the Allman style and is named for Eric Allman, a programmer who
popularized the style. The Allman style is used throughout this book. However, Java
programmers use a variety of indent styles, and all can produce workable Java programs.
When you write your own code, you should develop a consistent style. In school, your
instructor might have a preferred style, and when you get a job as a Java programmer, your
organization most likely will have a preferred style. With many development environments,
indentations are made for you automatically as you type.
Most programmers indent a method’s statements a few spaces more than its curly braces.
Some programmers indent two spaces, some three, and some four. Some programmers use
the Tab key to create indentations, but others are opposed to this practice because the Tab
key can indicate different indentation sizes on different systems. Some programmers don’t
care whether tabs or spaces are used, as long as they are not mixed in the same program.
The Java compiler does not care how you indent. Again, the most important rule is to
develop a consistent style of which your organization approves.
Figure 1-8 Shell code
public class AnyClassName
{
public static void main(String[] args)
{
/******/
}
}
97070_ch01_hr_001-048.indd 19 24/02/18 3:27 pm
20
Creating Java ProgramsC H A P T E R 1
Your First Application
Now that you understand the basics of an application written in Java, you are ready to
enter your own Java application into a text editor. It is a tradition among programmers
that the first program you write in any language produces “Hello, world!” as its output.
Saving a Java Class
When you write a Java class, you must save it using a writable storage medium such as a
disk, DVD, or USB device. In Java, if a class is public (that is, if you use the public access
specifier before the class name), you must save the class in a file with exactly the same name
and a .java extension. For example, the First class must be stored in a file named First.
java. The class name and filename must match exactly, including the use of uppercase and
lowercase characters. If the extension is not .java, the Java compiler does not recognize the
file as containing a Java class. Appendix A contains additional information about saving a
Java application.
Watch the video A Java Program.
(continues)
The false statement is #3. In the method header public static void
main(String[] args), the word void means that the main() method does not
return any value when it is called.
TWO TRUTHS & A LIE
Analyzing a Java Application that Produces Console Output
1. In the method header public static void main(String[] args), the
word public is an access specifier.
2. In the method header public static void main(String[] args), the
word static means that a method is accessible and usable, even though no
objects of the class exist.
3. In the method header public static void main(String[] args), the
word void means that the main() method is an empty method.
You Do It
97070_ch01_hr_001-048.indd 20 24/02/18 3:27 pm
21
Analyzing a Java Application that Produces Console Output
You will create such a program now. You can use any text editor, such as Notepad or
TextPad, or a development environment, such as jGRASP.
1. Start the text editor, and then open a new document.
2. Type the class header as follows:
public class Hello
In this example, the class name is Hello. You can use any valid name you want
for the class. If you choose Hello, you always must refer to the class as Hello,
and not as hello, because Java is case sensitive.
3. Press Enter once, type { (opening curly brace), press Enter again, and
type } (closing curly brace). You will add the main() method between these
curly braces. Although it is not required, the convention used in this book is
to place each curly brace on its own line and to align opening and closing
curly brace pairs with each other. Using this format makes your code easier
to read.
4. As shown in Figure 1-9, add the main() method header between the curly
braces, and then type a set of curly braces for main().
5. Next, add the statement within the main() method that will produce the output
Hello, world!. Use Figure 1-10 as a guide for adding the println() statement to
the main() method.
Figure 1-9 The main() method shell for the Hello class
public class Hello
{
public static void main(String[] args)
{
}
}
It is best to use the simplest available text editor when writing Java programs. Multifeatured
word-processing programs save documents as much larger files because of all the
built-in features, such as font styles and margin settings, which the Java compiler cannot
interpret. Additionally, one school of thought is that you should use a simple text editor
such as Notepad because it does not provide features such as automatically completing
statements for you or color-coding language features, thus forcing you to better learn all
the nuances of the language.
(continues)
(continued)
97070_ch01_hr_001-048.indd 21 24/02/18 3:27 pm
22
Creating Java ProgramsC H A P T E R 1
6. Save the application as Hello.java. The class name and filename must match
exactly, and you must use the .java extension.
(continued)
Figure 1-10 Complete Hello class
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello, world!");
}
}
Compiling a Java Class and Correcting Syntax Errors
After you write and save an application, two steps must occur before you can view the
application’s output.
1. You must compile the class you wrote (called the source code) into bytecode.
2. You must use the Java interpreter to translate the bytecode into executable
statements.
Compiling a Java Class
If you are using a development environment such as jGRASP, you can compile your
program by clicking the Compile button, or by clicking the Build menu and selecting
Compile. If you are using a text editor such as Notepad, you can compile your source code
file from the command line. Your prompt should show the folder or directory where your
program file is stored. Then, you type javac followed by the name of the file that contains
the source code. For example, to compile a file named First.java, you type the following and
then press Enter:
javac First.java
Compiling the program will produce one of three outcomes:
• You receive a message such as 'javac' is not recognized as an internal or
external command, operable program or batch file.
• You receive one or more programming language error messages.
• You receive no messages, which means that the application compiled successfully.
97070_ch01_hr_001-048.indd 22 24/02/18 3:27 pm
23
Compiling a Java Class and Correcting Syntax Errors
When compiling, if the source code file is not in the current path, you can type a full path with the
filename. For example:
javac c:\java\MyClasses\Chapter.01\First.java
In a DOS environment, you can change directories using the cd command. For example, to change from
the current directory to a subdirectory named MyClasses, you type cd MyClasses and press
Enter. Within any directory, you can back up to the root directory by typing cd\ and pressing Enter.
If you receive an error message that the command is not recognized, it might mean one of
the following:
• You misspelled the command javac.
• You misspelled the filename.
• You are not within the correct subfolder or subdirectory on your command line.
• Java was not installed properly. (See Appendix A for information about installation.)
If you receive a programming language error message, it means the source code has one
or more syntax errors. Recall that a syntax error is a programming error that occurs
when you introduce typing errors into your program or use the programming language
incorrectly. For example, if your class name is first (with a lowercase f ) in the source
code but you saved the file as First.java (with an uppercase F ), you will receive an error
message when you compile the application. The error message will be similar to class first
is public, should be declared in a file named first.java because first and First are not the
same in a case-sensitive language. If this error occurs, you must reopen the text file that
contains the source code and make the necessary corrections, and then save the file and
attempt to compile it again.
Appendix A contains information about troubleshooting, including how to change filenames
in a Windows environment.
If you receive no error messages after compiling the code in a file named First.java, the
application compiled successfully. In that case, a file named First.class is created and saved in
the same folder as the text file that holds the source code. After a successful compile, you can
execute the program (run the class file) on any computer that has a Java language interpreter.
Correcting Syntax Errors
Frequently, you might make typing errors as you enter Java statements into your text editor.
When you issue the command to compile a class containing errors, the Java compiler
produces one or more error messages. The exact error message that appears varies
depending on the compiler you are using.
97070_ch01_hr_001-048.indd 23 24/02/18 3:27 pm
24
Creating Java ProgramsC H A P T E R 1
The FirstWithMissingSemicolon class shown in Figure 1-11 contains an error—the
semicolon is missing at the end of the println() statement. (Of course, this class has been
helpfully named to alert you to the error.) When you compile this class, an error message
similar to the one shown in Figure 1-12 is displayed.
Figure 1-11 The FirstWithMissingSemicolon class
public class FirstWithMissingSemicolon
{
public static void main(String[] args)

{
System.out.println("First Java application")
}
}
The statement-ending
semicolon has been
omitted.
Figure 1-12 Error message generated when the FirstWithMissingSemicolon class is compiled
The first line of the error message in Figure 1-12 displays the name of the file in which the
error was found (FirstWithMissingSemicolon.java), the line number in which it was found
(5), and the nature of the error (’;’ expected). The next line of the error message displays
the statement that contains the error, including a caret that points to the exact location
where the error was first discovered. As you will see when you write and compile Java
programs, the place where an error is discovered is not necessarily where the error was
made. For example, sometimes an error is not discovered until the line that follows the line
that contains the error. Fairly frequently, it takes a little detective work to interpret an error
message and determine its cause.
Finally, the message generated in Figure 1-12 includes a count of the number of
errors found—in this case, there is just one error. This error is an example of a
compile-time error, or one in which the compiler detects a violation of language
syntax rules and is unable to translate the source code to machine code.
When you compile a class, the compiler reports as many errors as it can find so that
you can fix as many errors as possible. Sometimes, one error in syntax causes multiple
97070_ch01_hr_001-048.indd 24 24/02/18 3:27 pm
25
Compiling a Java Class and Correcting Syntax Errors
error messages that normally would not be errors if the first syntax error did not exist,
so fixing one error might eliminate multiple error messages. Sometimes, when you fix a
compile-time error and recompile a program, new error messages are generated. That’s
because when you fix the first error, the compiler can proceed beyond that point and
possibly discover new errors. Of course, no programmer intends to type a program
containing syntax errors, but when you do, the compiler finds them all for you.
Compiling a Java Class
You are ready to compile the Hello class that you created in the previous “You Do It”
section.
1. If it is not still open on your screen, open the Hello.java file that you saved in
the previous “You Do It” section.
2. If you are using jGRASP or another similar development environment, you can
compile a program by clicking the Compile button. Otherwise, you can compile a
program from the command prompt. Go to the command-line prompt for the drive
and folder or subdirectory in which you saved Hello.java. At the command line,
type:
javac Hello.java
After a few moments, you should return to the command prompt. If you see error
messages instead, reread the previous section to discover whether you can
determine the source of the error.
You Do It
The false statement is #1. After you write and save an application, you can com-
pile the source code to create bytecode.
TWO TRUTHS & A LIE
Compiling a Java Class and Correcting Syntax Errors
1. After you write and save an application, you can compile the bytecode to
create source code.
2. When you compile a class, you create a new file with the same name as the
original file but with a .class extension.
3. Syntax errors are compile-time errors.
(continues)
97070_ch01_hr_001-048.indd 25 24/02/18 3:27 pm
26
Creating Java ProgramsC H A P T E R 1
If the error message indicates that the command was not recognized, make sure
that you spelled the javac command correctly, including using the correct case.
Also, make sure you are using the correct directory or folder where the Hello.java
file is stored.
If the error message indicates a language error, check your file against
Figure1-10, making sure it matches exactly. Fix any errors, and compile the
application again. If errors persist, read through the next section to see if
you can discover the solution.
Correcting Syntax Errors
In this section, you examine error messages and gain firsthand experience with
syntax errors.
1. If your version of the Hello class did not compile successfully, examine
the syntax error messages. Now that you know the messages contain line
numbers and carets to pinpoint mistakes, it might be easier for you to fix
problems. After you determine the nature of any errors, resave the file and
recompile it.
2. Even if your Hello class compiled successfully, you need to gain experience
with error messages. Your student files contain a file named HelloErrors.java.
Find this file and open it in your text editor. If you do not have access to the
student files that accompany this book, you can type the file yourself, as shown
in Figure 1-13.
3. Save the file as HelloErrors.java in the folder in which you want to work. Then
compile the class using the following command to confirm that it compiles
without error:
javac HelloErrors.java
Figure 1-13 The HelloErrors class
public class HelloErrors
{
public static void main(String[] args)
{
System.out.println("Hello");
System.out.println("This is a test");
}
}
(continued)
(continues)
97070_ch01_hr_001-048.indd 26 24/02/18 3:27 pm
27
Compiling a Java Class and Correcting Syntax Errors
4. In the first line of the file, remove the c from class, making the first line read
public lass HelloErrors. Save the file and compile the program. Error
messages are generated similar to those shown in Figure 1-14. Even though
you changed only one keystroke in the file, four error messages appear. The
first indicates that class, interface, or enum is expected in line 1. You haven’t
learned about the Java keywords enum or interface yet, but you know that
you caused the error by altering the word class. The next three errors in lines
3, 6, and 7 show that the compile is continuing to look for one of the three
keywords, but fails to find them.
5. Repair the program by reinserting the c in class. Save the file and compile it
again. The program should compile successfully. In this case, when you fix one
error, four error messages are removed.
6. Next, remove the word void from the third line of the program. Save the file and
compile it. Figure 1-15 shows the error message, which indicates that a return
type is required. The message does not indicate that void is missing because
Java supports many return types for methods. In this case, however, void is
the correct return type, so reinsert it into the correct place in the program, and
then save and recompile the file.
Figure 1-14 Error messages generated when class is misspelled in the HelloErrors
program
(continued)
(continues)
97070_ch01_hr_001-048.indd 27 24/02/18 3:27 pm
28
Creating Java ProgramsC H A P T E R 1
7. Remove the final closing curly brace from the HelloErrors program. Save
the file and recompile it. Figure 1-16 shows the generated message “reached
end of file while parsing.” Parsing is the process the compiler uses to divide
your source code into meaningful portions; the message means that the
compiler was in the process of analyzing the code when the end of the file was
encountered prematurely. If you repair the error by reinserting the closing curly
brace, saving the file, and recompiling it, you remove the error message.
8. Continue to introduce errors in the program by misspelling words, omitting
punctuation, and adding extraneous keystrokes. Remember to save each
program version before you recompile it; otherwise, you will recompile the
previous version. When error messages are generated, read them carefully
and try to understand their meaning in the context of the error you purposely
caused. Occasionally, even though you inserted an error into the program,
no error messages will be generated. That does not mean your program is
correct. It only means that the program contains no syntax errors. A program
can be free of syntax errors but still not be correct, as you will learn in the
next section.
(continued)
Figure 1-16 Error message generated when the closing curly brace is omitted from the
HelloErrors program
Figure 1-15 Error message generated when void is omitted from the main() method
header in the HelloErrors program
97070_ch01_hr_001-048.indd 28 24/02/18 3:27 pm
29
Running a Java Application and Correcting Logic Errors
Running a Java Application and Correcting Logic Errors
After a program compiles with no syntax errors, you can execute it. Just because a program
compiles and executes, however, does not mean the program is error free.
Running a Java Application
To run an application from jGRASP, you can click the Run button or click the Build menu
and then click Run. To run the First application from the command line, you type the
following:
java First
Figure 1-17 shows the application’s output in the command window. In this example, you
can see that the First class is stored in a folder named Java on the C drive. After you type
the java command to execute the program, the literal string in the call to the println()
method is output, so First Java application appears on the screen. Control then returns to
the command prompt.
The procedure to confirm the storage location of your First.java class varies depending on your
operating system. In a Windows operating system, for example, you can open Windows Explorer, locate
the icon representing the storage device you are using, find the folder in which you have saved the file,
and expand the folder. You should see the First.java file.
When you run a Java application using the java command, do not add the .class extension
to the filename. If you type java First, the interpreter looks for a file named First.class. If
you type java First.class, the interpreter looks for a file named First.class.class.
Modifying a Compiled Java Class
After viewing the application output, you might decide to modify the class to get a different
result. For example, you might decide to change the First application’s output from First
Java application to the following:
My new and improved
Java application
Figure 1-17 Output of the First application
97070_ch01_hr_001-048.indd 29 24/02/18 3:27 pm
30
Creating Java ProgramsC H A P T E R 1
When you recompile a class, the original version of the compiled file with the .class
extension is replaced, and the original version no longer exists. When you modify a class,
you must decide whether you want to retain the original version. If you do, you must give the
new version a new class name and a new filename, or you must save it in a different folder.
To produce the new output, first you must modify the text file that contains the existing
class. You need to change the existing literal string, and then add an output statement for
another text string. Figure 1-18 shows the class that changes the output.
Figure 1-18 First class containing output modified from the original version
public class First
{
public static void main(String[] args)
{
System.out.println("My new and improved");
System.out.println("Java application");
}
}
The changes to the First class include the addition of the statement
System.out.println(“My new and improved”); and the removal of the
word First from the string in the other println() statement.
If you make changes to the file, as shown in Figure 1-18, and save the file without recompiling
it, then when you execute the program by typing java First at the command line, you
will not see the new output—you will see the old output without the added line. Even
though you save a text file that contains the modified source code for a class, the class in the
already-compiled class file executes. After you save the file named First.java, the old compiled
version of the class with the same name is still stored on your computer. Before the new
source code can execute, you must do the following:
1. Save the file with the changes (using the same filename).
2. Recompile the class with the javac command.
3. Interpret the class bytecode and execute the class using the java command.
Figure 1-19 shows the new output.
Figure 1-19 Execution of modified First class
97070_ch01_hr_001-048.indd 30 24/02/18 3:27 pm
31
Running a Java Application and Correcting Logic Errors
Once in a while, when you make a change to a Java class and then recompile and execute it, the old
version still runs. The simplest solution is to delete the .class file and compile again. Programmers call
this creating a clean build.
Correcting Logic Errors
A second kind of error occurs when the syntax of the program is correct and the
program compiles but produces incorrect results when you execute it. This type of
error is a logic error, which is often more difficult to find and resolve. For example,
Figure 1-20 shows the output of the execution of a successfully compiled program
named FirstBadOutput. If you glance at the output too quickly, you might not notice
that Java is misspelled. The compiler does not find spelling errors within a literal string;
it is legitimate to produce any combination of letters as output. Other examples of logic
errors include multiplying two values when you meant to add, printing one copy of a
report when you meant to print five, or forgetting to produce a total at the end of a
business report when a user has requested one. Errors of this type must be detected by
carefully examining the program output. It is the responsibility of the program author
to test programs and find any logic errors.
Figure 1-20 Output of FirstBadOutput program
You have already learned that syntax errors are compile-time errors. A logic error is
a type of run-time error—an error not detected until the program asks the computer
to do something wrong, or even illegal, while executing. Not all run-time errors are
the fault of the programmer. For example, a computer’s hardware might fail while a
program is executing. Good programming practices, however, can help to minimize
run-time errors.
The process of fixing computer errors has been known as debugging since a large moth was found
wedged into the circuitry of a mainframe computer at Harvard University in 1947. You can search the
Web for pictures of the moth.
Watch the video Compiling and Executing a Program.
97070_ch01_hr_001-048.indd 31 24/02/18 3:27 pm
32
Creating Java ProgramsC H A P T E R 1
Adding Comments to a Java Class
As you can see, even the simplest Java class requires several lines of code and
contains somewhat perplexing syntax. Large applications that perform many tasks
include much more code, and as you write larger applications it becomes increasingly
difficult to remember why you included steps or how you intended to use particular
variables. Documenting your program code helps you remember why you wrote lines
of code the way you did. Program comments are nonexecuting statements that you
add to a program for the purpose of documentation. In other words, comments are
designed for people reading the source code and not for the computer executing the
program.
Programmers use comments to leave notes for themselves and for others who might
read their programs in the future. At the very least, your Java class files should include
comments indicating the author, the date, and the class name or function. The best
practice dictates that you also include a brief comment to describe the purpose of each
method you create within a class.
As you work through this book, add comments as the first lines of every file. The comments
should contain the class name and purpose, your name, and the date. Your instructor might
ask you to include additional comments.
Turning some program statements into comments can sometimes be useful when you are
developing an application. If a program is not performing as expected, you can “comment
out” various statements and subsequently run the program to observe the effect. When you
comment out a statement, you turn it into a comment so the compiler does not translate
it, and the JVM does not execute its command. This can help you pinpoint the location of
errant statements in malfunctioning programs.
The false statement is #2. To compile a file named MyProgram.java, you type
javac MyProgram.java, but to execute the program you type the following:
java MyProgram
TWO TRUTHS & A LIE
Running a Java Application and Correcting Logic Errors
1. In Java, if a class is public, you must save the class in a file with exactly the
same name and a .java extension.
2. To compile a file named MyProgram.java, you type java MyProgram, but to
execute the program you type java MyProgram.java.
3. When you compile a program, sometimes one error in syntax causes multiple
error messages.
97070_ch01_hr_001-048.indd 32 24/02/18 3:27 pm
33
Adding Comments to a Java Class
There are three types of comments in Java:
• Line comments start with two forward slashes ( // ) and continue to the end of the
current line. A line comment can appear on a line by itself or at the end (and to the
right) of a line following executable code. Line comments do not require an ending
symbol.
• Block comments start with a forward slash and an asterisk ( /* ) and end with an
asterisk and a forward slash ( */ ). A block comment can appear on a line by itself, on a
line before executable code, or on a line after executable code. Block comments also can
extend across as many lines as needed.
• Javadoc comments are a special case of block comments called documentation
comments because they are used to automatically generate nicely formatted program
documentation with a program named javadoc. Javadoc comments begin with a
forward slash and two asterisks ( /** ) and end with an asterisk and a forward slash ( */ ).
Appendix E teaches you how to create javadoc comments.
The forward slash ( / ) and the backslash ( \ ) characters often are confused, but they are two distinct
characters. You cannot use them interchangeably.
Figure 1-21 shows how comments are used in code. In this example, the only statement that
executes is the println; statement; everything else is a comment.
Figure 1-21 A program segment containing several comments
// Demonstrating comments
/* This shows
that these comments
don’t matter */
System.out.println("Hello"); // This line executes
// up to where the comment started
/* Everything but the println()
is a comment */
The only executable code
in this segment is the part
of this line up to the semicolon.
You might want to create comments simply for aesthetics. For example, you might want
to use a comment that is simply a row of dashes or asterisks to use as a visual dividing line
between parts of a program.
When a program is used in a business setting, the program frequently is modified over time because of
changing business needs. If a programmer changes code but does not change the comments that go
with it, it’s very possible that people who read the program in the future will be confused or misled. When
you modify a program, it’s important to change any relevant comments.
97070_ch01_hr_001-048.indd 33 24/02/18 3:27 pm
34
Creating Java ProgramsC H A P T E R 1
Adding Comments to a Class
In this exercise, you add comments to your Hello.java application and save it as a new
class named Hello2 so that you can retain copies of both the original and modified
classes.
1. Open the Hello.java file you created earlier in this chapter. Enter the following
comments at the top of the file, inserting your name and today’s date where
indicated.
// Filename Hello2.java
// Written by
// Written on
2. Change the class name to Hello2, and then type the following block comment
after the class header:
/* This class demonstrates the use of the println()
method to print the message Hello, world! */
3. Save the file as Hello2.java. The file must be named Hello2.java because the
class name is Hello2.
(continues)
The false statement is #1. Line comments start with two forward slashes ( // )
and continue to the end of the current line; they do not require an ending symbol.
TWO TRUTHS & A LIE
Adding Comments to a Java Class
1. Line comments start with two forward slashes ( // ) and end with two
backslashes ( \\ ); they can extend across as many lines as needed.
2. Block comments start with a forward slash and an asterisk ( /* ) and end
with an asterisk and a forward slash ( */ ); they can extend across as many
lines as needed.
3. Javadoc comments begin with a forward slash and two asterisks ( /** ) and
end with an asterisk and a forward slash ( */ ); they are used to generate
documentation with a program named javadoc.
You Do It
97070_ch01_hr_001-048.indd 34 24/02/18 3:27 pm
35
Creating a Java Application that Produces GUI Output
Creating a Java Application that Produces GUI Output
Besides allowing you to use the System class to produce command window output, Java
provides built-in classes that produce GUI output. For example, Java contains a class
named JOptionPane that allows you to produce dialog boxes. A dialog box is a GUI object
resembling a window in which you can place messages you want to display. Figure 1-22
shows a class named FirstDialog. The FirstDialog class contains many elements that are
familiar to you; only the first and sixth lines are new.
Figure 1-22 The FirstDialog class
Only these two lines are new to you.import javax.swing.JOptionPane;
public class FirstDialog
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "First Java dialog");
}
}
In older versions of Java, any application that used a JOptionPane dialog was required to end with
a System.exit(0); statement or the application would not terminate. You can add this statement
to your programs, and they will work correctly, but it is not necessary. However, you might see this line
when examining programs written by others.
4. Go to the command-line prompt for the drive and folder or subdirectory in
which you saved Hello2.java, and type the following command to compile the
program:
javac Hello2.java
5. When the compile is successful, execute your application by typing java Hello2
at the command line. The comments have no effect on program execution; the
output should appear on the next line.
(continued)
After the application compiles successfully, a file named Hello2.class is created and stored
in the same folder as the Hello2.java file. If your application compiled without error but you
receive an error message, such as Exception in thread ‘main’ java.lang.NoClassDefFoundError,
when you try to execute the application, you probably do not have your class path set
correctly. See Appendix A for details.
97070_ch01_hr_001-048.indd 35 24/02/18 3:27 pm
36
Creating Java ProgramsC H A P T E R 1
The second new statement within the main() method in the FirstDialog class in
Figure 1-22 uses the showMessageDialog() method that is part of the JOptionPane class.
Like the println() method that is used for console output, the showMessageDialog()
method starts with a lowercase letter and is followed by a set of parentheses. However,
whereas the println() method requires only one argument between its parentheses to
produce an output string, the showMessageDialog() method requires two arguments.
Whenever a method requires multiple arguments, they are separated by commas. When
the first argument to showMessageDialog() is null, as it is in the class in Figure 1-22, it
means the output message box should be placed in the center of the screen. (You will learn
more about dialog boxes, including how to position them in different locations and how
to add more options to them, in Chapter 2.) The second argument, after the comma, is the
literal string that is displayed.
You do not need to use an import statement when you use the System class (as with the
System.out.println() method) because the System class is contained in the package
java.lang, which is automatically imported in every Java program. You could include the statement
import java.lang; at the top of any file in which you use the System class, but you are not
required to do so.
Earlier in this chapter, you learned that true, false, and null are all reserved words that
represent values.
Figure 1-23 Output of the FirstDialog application
When a user executes the FirstDialog class, the dialog box in Figure 1-23 is displayed. The
user must click the OK button or the Close button to dismiss the dialog box. If the user has
a touch screen, the user can touch the OK button or the Close button.
In Figure 1-22, the first new statement is an import statement. You use an import statement
when you want to access a built-in Java class that is contained in a group of classes called
a package. To use the JOptionPane class, you must import the package named javax.
swing.JOptionPane. Any import statement you use must be placed outside of any class you
write in a file. You will learn more about import statements in general, and the javax.swing
packages in particular, as you continue to study Java.
97070_ch01_hr_001-048.indd 36 24/02/18 3:27 pm
37
Creating a Java Application that Produces GUI Output
Creating a Dialog Box
Next, you write a Java application that produces output in a dialog box.
1. Open a new file in your text editor. Type comments similar to the following,
inserting your own name and today’s date where indicated.
// Filename HelloDialog.java
// Written by
// Written on
2. Enter the import statement that allows you to use the JOptionPane class:
import javax.swing.JOptionPane;
3. Enter the HelloDialog class:
public class HelloDialog
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "Hello, world!");
}
}
4. Save the file as HelloDialog.java. Compile the class using the following
command:
javac HelloDialog.java
The false statement is #2. You use an import statement when you want to access
a built-in Java class that is contained in a group of classes called a package.
TWO TRUTHS & A LIE
Creating a Java Application that Produces GUI Output
1. A dialog box is a GUI object resembling a window, in which you can place
messages you want to display.
2. You use an append statement when you want to access a built-in Java class
that is contained in a group of classes called a package.
3. Different methods can require different numbers of arguments.
You Do It
(continues)
97070_ch01_hr_001-048.indd 37 24/02/18 3:27 pm
38
Creating Java ProgramsC H A P T E R 1
Finding Help
As you write Java programs, you can consult this book and other Java documentation. A
great wealth of helpful material exists at the Java website, www.oracle.com/technetwork/
java/index.html. Of particular value is the Java application programming interface, more
commonly referred to as the Java API. The Java API is also called the Java class library; it
contains information about how to use every prewritten Java class, including lists of all the
methods you can use with the classes.
Also of interest at the Java website are frequently asked questions (FAQs) that provide brief
answers to many common questions about Java software and products. You can also find
several versions of the Java Development Kit (JDK) that you can download for free. The
JDK is an SDK—a software development kit that includes tools used by programmers.
Versions are available for Windows, Linux, and Solaris operating systems. You can search
and browse documentation online or you can download the documentation file for the
JDK and install it on your computer. After it is installed, you can search and browse
documentation locally.
A downloadable set of lessons titled “The Java Tutorial” with hundreds of complete working
examples is available from http://docs.oracle.com/javase/tutorial/. The tutorial is organized
into trails—groups of lessons on a particular subject. You can start the tutorial at the
5. If necessary, eliminate any syntax errors, resave the file, and recompile. Then
execute the program using the following command:
java HelloDialog
The output appears as shown in Figure 1-24.
6. Click OK to dismiss the dialog box.
(continued)
Instead of clicking the Close button in a Java dialog box, you can press Ctrl + C at the
command prompt to end a program.
Figure 1-24 Output of HelloDialog application
97070_ch01_hr_001-048.indd 38 24/02/18 3:27 pm
39
Don’t Do It
Don’t Do It
At the end of each chapter, a Don’t Do It list will alert you to common mistakes made by
beginning programmers.
• Don’t forget that in Java, a public file’s name must match the name of the class it contains.
For example, if a file is named Program1.java, you can’t simply rename it Program1BackUp.
java and expect it to compile unless you change the class name within the file.
beginning and navigate sequentially to the end, or you can jump from one trail to another.
As you study each chapter in this book, you are encouraged to make good use of these
support materials.
Exploring the Java Website
In this section, you explore some of the material at the Java website.
1. Open an Internet browser and navigate to the following website:
http://download.java.net/java/jdk9/docs/api/overview-summary.html
Oracle could change the layout of its website after this book is published.
However, you should be able to find Java SE9 APIs. (If you are using an older
version of Java, you can select that version instead.)
2. Near the top of the screen, you should see a link to All Classes. Scroll until you
can select the System class. Scroll down until you can see the Field Summary
for the System class.
3. You can see that the System class contains three fields. You are already familiar
with the out field, and you can see that it is an object of type PrintStream.
Click the hypertext for the PrintStream type to be taken to a new page with
details about that class.
4. Scroll through the methods of the PrintStream class. Notice that the class
contains several versions of the print() and println() methods. Find the
version of the println() method that accepts a String argument. Click the link
to the method to read details about it, such as that it “prints a String and then
terminates the line.”
Many parts of the Java documentation won’t mean much to you until you study
data types and methods in more detail in the next few chapters of this book. For
now, you can explore the Java website to get an idea of the wealth of classes
that have been created for you.
You Do It
97070_ch01_hr_001-048.indd 39 24/02/18 3:27 pm
40
Creating Java ProgramsC H A P T E R 1
• Don’t confuse the terms parentheses, braces, brackets, curly braces, square brackets,
and angle brackets. When you are writing a program or performing some other
computerized task and someone tells you, “Now, type some braces,” you might want to
clarify which term is meant. Table 1-5 summarizes these punctuation marks.
• Don’t forget to end a block comment. Every /* must have a corresponding */, even if it
is several lines later. It’s harder to make a mistake with line comments (those that start
with //), but remember that nothing on the line after the // will execute.
• Don’t forget that Java is case sensitive.
• Don’t forget to end every statement with a semicolon, but not to end class or method
headers with a semicolon.
• Don’t forget to recompile a program to which you have made changes. It can be very
frustrating to fix an error, run a program, and not understand why you don’t see
evidence of your changes. The reason might be that the .class file does not contain your
changes because you forgot to recompile.
• Don’t panic when you see a lot of compiler error messages. Often, fixing one will fix
several.
• Don’t think your program is perfect when all compiler errors are eliminated. Only by
running the program multiple times and carefully examining the output can you be
assured that your program is logically correct.
Punctuation Name Typical Use in Java Alternate Names
( ) Parentheses Follows method names as in
print()
Parentheses can be
called round brackets,
but such usage is
unusual
{ } Curly braces A pair surrounds a class body,
a method body, and a block
of code; when you learn about
arrays in Chapter 8, you will find
that curly braces also surround
lists of array values
Curly braces might also
be called curly brackets
[ ] Square brackets A pair signifies an array; arrays
are covered in Chapter 8
Square brackets might
be called box brackets
or square braces
< > Angle brackets Angle brackets are used
with generic arguments in
parameterized classes; you
won’t use them in this book
When angle brackets
appear with nothing
between them, they are
called a chevron
Table 1-5 Braces and brackets used in Java
97070_ch01_hr_001-048.indd 40 24/02/18 3:27 pm
41
Chapter Summary
Key Terms
computer program
hardware
software
application software
system software
logic
high-level programming
language
low-level programming
language
machine language
machine code
syntax
keywords
program statements
commands
compiler
interpreter
executing
at run time
syntax error
debugging
bugs
logic error
semantic errors
procedural programming
variables
procedures
call a procedure
object-oriented programs
computer simulations
graphical user interfaces
(GUIs)
class
class definition
attributes
properties
object
instance
instantiation
state
method
encapsulation
inheritance
polymorphism
Java
architecturally neutral
Java Virtual Machine
(JVM)
source code
development environment
bytecode
Java interpreter
“Write once, run any-
where” (WORA)
console applications
windowed applications
literal string
arguments
passing arguments
standard output device
identifier
Unicode
Pascal casing
upper camel casing
access specifier
class body
whitespace
K & R style
Allman style
public
static
void
compile-time error
parsing
clean build
run-time error
program comments
comment out
line comments
block comments
javadoc
documentation comments
dialog box
import statement
package
Java API
FAQs
JDK
SDK
Chapter Summary
• A computer program is a set of instructions that tells a computer what to do. You can
write a program using a high-level programming language, which has its own syntax,
or rules of the language. After you write a program, you use a compiler or interpreter to
translate the language statements into machine code.
• Writing object-oriented programs involves creating classes, creating objects from those
classes, and creating applications that use those objects. Object-oriented programming
languages support encapsulation, inheritance, and polymorphism.
97070_ch01_hr_001-048.indd 41 24/02/18 3:27 pm
42
Creating Java ProgramsC H A P T E R 1
1. The most basic circuitry-level computer language is ____________.
a. machine language
b. Java
c. high-level language
d. C++
2. Languages that let you use an easily understood vocabulary of descriptive terms,
such as read, write, or add, are known as ____________languages.
a. procedural
b. high-level
c. machine
d. object-oriented
• A program written in Java is run on a standardized hypothetical computer called the
Java Virtual Machine (JVM). When a class is compiled into bytecode, an interpreter
within the JVM subsequently interprets the bytecode and communicates with the
operating system to produce the program results.
• Everything within a Java program must be part of a class and contained within opening
and closing curly braces. Methods within classes hold statements, and every statement
ends with a semicolon. Dots are used to separate classes, objects, and methods in
program code. All Java applications must have a method named main(), and many Java
applications contain additional methods.
• To compile your source code from the command line, type javac followed by the
name of the file that contains the source code. The compiler might issue syntax error
messages that you must correct. When you successfully compile your source code, the
compiler creates a file with a .class extension.
• You can run a compiled .class file on any computer that has a Java language interpreter
by entering the java command followed by the name of the class file. When you modify
a class, you must recompile it for the changes to take effect. After a program executes,
you must examine the output for logic errors.
• Program comments are nonexecuting statements that you add to a file for
documentation. Java provides you with three types of comments: line comments,
block comments, and javadoc comments.
• Java provides you with built-in classes that produce GUI output. For example, Java
contains a class named JOptionPane that allows you to produce dialog boxes.
• A great wealth of helpful material exists online at the Java website.
Review Questions
97070_ch01_hr_001-048.indd 42 24/02/18 3:27 pm
43
Chapter Summary
3. The rules of a programming language constitute its ____________.
a. syntax
b. logic
c. format
d. objects
4. A ____________translates high-level language statements into machine code.
a. programmer
b. syntax detector
c. compiler
d. decipherer
5. Named computer memory locations are called ____________.
a. compilers
b. variables
c. addresses
d. appellations
6. The individual operations used in a computer program are often grouped into
logical units called ____________.
a. procedures
b. variables
c. constants
d. logistics
7. Envisioning program components as objects that are similar to concrete objects
in the real world is the hallmark of ____________.
a. command-line operating systems
b. procedural programming
c. object-oriented programming
d. machine languages
8. The values of an object’s attributes are known as its ____________.
a. state
b. orientation
c. methods
d. condition
9. An instance of a class is a(n) ____________.
a. method
b. procedure
c. object
d. case
10. Java is architecturally ____________.
a. neutral
b. oriented
c. specific
d. abstract
11. You must compile classes written in Java into ____________.
a. bytecode
b. source code
c. javadoc statements
d. object code
12. All Java programming statements must end with a ____________.
a. period
b. comma
c. closing parenthesis
d. semicolon
97070_ch01_hr_001-048.indd 43 24/02/18 3:27 pm
44
Creating Java ProgramsC H A P T E R 1
13. Arguments to methods always appear within ____________.
a. parentheses
b. double quotation marks
c. single quotation marks
d. curly braces
14. In a Java program, you must use ____________to separate classes, objects, and
methods.
a. commas
b. semicolons
c. dots
d. forward slashes
15. All Java applications must have a method named ____________.
a. method()
b. main()
c. java()
d. Hello()
16. Nonexecuting program statements that provide documentation are called
____________.
a. classes
b. notes
c. comments
d. commands
17. Java supports three types of comments: ____________, ____________, and
javadoc.
a. line, block
b. string, literal
c. constant, variable
d. single, multiple
18. Which of the following is not necessary to do before you can run a Java program?
a. coding
b. compiling
c. debugging
d. saving
19. The command to execute a compiled Java application is ____________.
a. run
b. execute
c. javac
d. java
20. You save text files containing Java source code using the file extension
____________.
a. .java
b. .class
c. .txt
d. .src
97070_ch01_hr_001-048.indd 44 24/02/18 3:27 pm
45
Exercises
As you work through the programming exercises in this book, you will create many files. To organize
them, you might want to create a separate folder in which to store the files for each chapter.
Exercises
1. Is each of the following class identifiers (a) legal and conventional, (b) legal but
unconventional, or (c) illegal?
a. myClass
b. void
c. Golden Retriever
d. invoice#
e. 36542ZipCode
f. Apartment
g. Fruit
h. 8888
i. displayTotal()
j. Accounts_Receivable
2. Is each of the following method identifiers (a) legal and conventional, (b) legal
but unconventional, or (c) illegal?
a. associationRules()
b. void()
c. Golden Retriever()
d. invoice#()
e. 36542ZipCode()
f. PayrollApp()
g. getReady()
h. 911()
i. displayTotal()
j. Accounts_Receivable()
3. Name at least three attributes that might be appropriate for each of the following
classes:
a. RealEstateListing
b. Vacation
c. CreditCardBill
4. Name at least three real-life objects that are instances of each of the following
classes:
a. Song
b. CollegeCourse
c. Musician
5. Name at least three classes to which each of these objects might belong:
a. myGrandmothersBrooch
b. eggsBenedict
c. cookieMonster
6. Write, compile, and test a class that displays the first few lines of the lyrics of your
favorite song. Save the class as SongLyrics.java.
Programming Exercises
97070_ch01_hr_001-048.indd 45 24/02/18 3:27 pm
46
Creating Java ProgramsC H A P T E R 1
7. Write, compile, and test a class that displays your favorite movie quote, the movie
it comes from, the character who said it, and the year of the movie. Save the class
as MovieQuoteInfo.java.
8. Write, compile, and test a class that
displays the pattern shown in
Figure 1-25. Save the class as
TableAndChairs.java.
9. Write, compile, and test a class
that displays the pattern shown in
Figure 1-26. Save the class as
Triangle.java.
10. Write, compile, and test a class
that uses the command window to
display the following statement about
comments: Program comments are
nonexecuting statements you add to a
file for documentation.
Also include the same statement in
three different comments in the class;
each comment should use one of the
three different methods of including
comments in a Java class. Save the
class as Comments.java.
11. Modify the Comments.java program
in Exercise 10 so that the statement
about comments is displayed in a
dialog box. Save the class as
CommentsDialog.java.
12. From 1925 through 1963, Burma Shave advertising signs appeared next to
highways all across the United States. There were always four or five signs in
a row containing pieces of a rhyme, followed by a final sign that read “Burma
Shave.” For example, one set of signs that has been preserved by the Smithsonian
Institution reads as follows:
Shaving brushes
You'll soon see 'em
On a shelf
In some museum
Burma Shave
Find a classic Burma Shave rhyme on the Web. Write, compile, and test a class
that produces a series of four dialog boxes so that each displays one line of a
Burma Shave slogan in turn. Save the class as BurmaShave.java.
Figure 1-25 Output of TableAndChairs
program
Figure 1-26 Output of Triangle program
97070_ch01_hr_001-048.indd 46 24/02/18 3:27 pm
47
Exercises
Debugging Exercises
1. Each of the following files in the Chapter01 folder in your downloadable
student files has syntax and/or logic errors. In each case, determine the
problem and fix the errors. After you correct the errors, save each file using
the same filename preceded with Fix. For example, DebugOne1.java will
become FixDebugOne1.java.
a. DebugOne1.java
b. DebugOne2.java
c. DebugOne3.java
d. DebugOne4.java
When you change a filename, remember to change every instance of the class name within the file so
that it matches the new filename. In Java, the filename and class name must always match.
Game Zone
1. In 1952, A. S. Douglas wrote his University of Cambridge Ph.D. dissertation on
human-computer interaction, and created the first graphical computer game—a
version of Tic-Tac-Toe. The game was programmed on an EDSAC vacuum-tube
mainframe computer. The first computer game is generally assumed to be
“Spacewar!”, developed in 1962 at MIT; the first commercially available video
game was “Pong,” introduced by Atari in 1973. In 1980, Atari’s “Asteroids”
and “Lunar Lander” became the first video games to be registered in the U.S.
Copyright Office. Throughout the 1980s, players spent hours with games that
now seem very simple and unglamorous; do you recall playing “Adventure,”
“Oregon Trail,” “Where in the World Is Carmen Sandiego?,” or “Myst”?
Today, commercial computer games are much more complex; they require
many programmers, graphic artists, and testers to develop them, and large
management and marketing staffs are needed to promote them. A game might
cost many millions of dollars to develop and market, but a successful game might
earn hundreds of millions of dollars. Obviously, with the brief introduction
to programming you have had in this chapter, you cannot create a very
sophisticated game. However, you can get started.
For games to hold your interest, they almost always include some random,
unpredictable behavior. For example, a game in which you shoot asteroids loses
some of its fun if the asteroids follow the same, predictable path each time you
play the game. Therefore, generating random values is a key component in
creating most interesting computer games.
97070_ch01_hr_001-048.indd 47 24/02/18 3:27 pm
48
Creating Java ProgramsC H A P T E R 1
Appendix D contains information about generating random numbers. To fully
understand the process, you must learn more about Java classes and methods.
For now, however, you can copy the following statement to generate and use a
dialog box that displays a random number between 1 and 10:
JOptionPane.showMessageDialog(null,"The number is "+
(1 + (int)(Math.random() * 10)));
Write a Java application that displays two dialog boxes in sequence. The first asks
you to think of a number between 1 and 10. The second displays a randomly
generated number; the user can see whether his or her guess was accurate.
(In future chapters, you will improve this game so that the user can enter a
guess and the program can determine whether the user was correct. If you
wish, you also can tell the user how far off the guess was, whether the guess was
high or low, and provide a specific number of repeat attempts.) Save the file as
RandomGuess.java.
Case Problems
The case problems in this section introduce two fictional businesses. Throughout this
book, you will create increasingly complex classes for these businesses that use the newest
concepts you have mastered in each chapter.
1. Carly’s Catering provides meals for parties and special events. Write a program
that displays Carly’s motto, which is “Carly’s makes the food that makes it a
party.” Save the file as CarlysMotto.java. Create a second program that displays
the motto surrounded by a border composed of asterisks. Save the file as
CarlysMotto2.java.
2. Sammy’s Seashore Supplies rents beach equipment such as kayaks, canoes, beach
chairs, and umbrellas to tourists. Write a program that displays Sammy’s motto,
which is “Sammy’s makes it fun in the sun.” Save the file as SammysMotto.java.
Create a second program that displays the motto surrounded by a border
composed of repeated Ss. Save the file as SammysMotto2.java.
97070_ch01_hr_001-048.indd 48 24/02/18 3:27 pm
C h a p t e r 2
Using Data
Upon completion of this chapter, you will be able to:
Declare and use constants and variables
Use integer data types
Use the boolean data type
Use floating-point data types
Use the char data type
Use the Scanner class to accept keyboard input
Use the JOptionPane class to accept GUI input
Perform arithmetic using variables and constants
Describe type conversion
97070_ch02_hr_049-109.indd 49 27/02/18 7:44 pm
50
Using DataC h a p t e r 2
Instead of using constant data, you can set up a data item to be variable. A variable is a named
memory location that can store a value. A variable can hold only one value at a time, but the
value it holds can change. For example, if you create a variable named ovenTemperature, it
might hold 0 when the application starts, later be altered to hold 350, and still later be altered
to hold 400. Whether a data item is variable or constant, in Java it always has a data type. An
item’s data type describes the type of data that can be stored there, how much memory the
item occupies, and what types of operations can be performed on the data. Java provides for
eight primitive types of data. A primitive type is a simple data type. Java’s eight data types are
described in Table 2-1. Later in this
chapter, you will learn more spe-
cific information about several of
these data types.
The eight data types in Table 2-1
are called primitive because they are
simple and uncomplicated.
Primitive types also serve as the
building blocks for more complex
data types, called reference types,
which hold memory addresses. The
classes you will begin creating in
Chapter 3 are examples of reference
types, as are the System class you
used in Chapter 1 and the Scanner
class you will use later in this chapter.
Declaring and Using Constants and Variables
A data item is constant when its value cannot be changed while a program is running. For
example, when you include the following statement in a Java class, the number 459 is a constant:
System.out.println(459);
Every time an application containing the constant 459 is executed, the value 459 is
displayed. Programmers refer to a number such as 459 in several ways:
• It is a literal constant because its value is taken literally at each use.
• It is a numeric constant as opposed to a character or string constant.
• It is an unnamed constant as opposed to a named one, because no identifier
is associated with it.
Keyword Description
byte Byte-length integer
short Short integer
int Integer
long Long integer
float Single-precision floating point
double Double-precision floating point
char A single character
boolean A Boolean value (true or false)
table 2-1 Java primitive data types
A programmer also might say that when a constant value such as 459 appears in a program, it is
hard-coded.
97070_ch02_hr_049-109.indd 50 27/02/18 7:44 pm
51
Declaring and Using Constants and Variables
Declaring Variables
A variable declaration is a statement that reserves a named memory location and includes
the following:
• A data type that identifies the type of data that the variable will store
• An identifier that is the variable’s name
• An optional assignment operator and assigned value, if you want a variable to contain
an initial value
• An ending semicolon
Variable names must be legal Java identifiers. (You learned the requirements for legal
identifiers in Chapter 1.) Basically, a variable name must start with a letter, cannot contain
spaces, and cannot be a reserved keyword. You must declare a variable before you can use
it. You can declare a variable at any point before you use it, but it is common practice to
declare variables first in a method and to place executable statements after the declarations.
Java is a strongly typed language, or one in which each variable has a well-defined data
type that limits the operations you can perform with it; strong typing implies that all
variables must be declared before they can be used.
Variable names conventionally begin with lowercase letters to distinguish them from
class names. However, as with class names, a program can compile without error even if
names are constructed unconventionally. Beginning an identifier with a lowercase letter
and capitalizing subsequent words within the identifier is a style known as camel casing.
An identifier such as lastName resembles a camel because of the uppercase “hump” in
the middle.
For example, the following declaration creates a conventionally named int variable, myAge,
and assigns it an initial value of 25:
int myAge = 25;
This declaration is a complete, executable statement, so it ends with a semicolon. The
equal sign ( = ) is the assignment operator. Any value to the right of the assignment
operator is assigned to the memory location named on the left. An assignment made
when you declare a variable is an initialization; an assignment made later is simply an
assignment. Thus, the first statement that follows is an initialization, and the second is
an assignment:
int myAge = 25;
myAge = 42;
You declare a variable just once in a method, but you might assign new values to it any
number of times. (A compiler error message will be displayed when there is a conflict
between two variables with the same name.)
97070_ch02_hr_049-109.indd 51 27/02/18 7:44 pm
52
Using DataC h a p t e r 2
Note that an expression with a literal to the left of the assignment operator (such as
25 = myAge) is illegal. The assignment operator has right-to-left associativity. associativity
refers to the order in which values are used with operators. The associativity of every
operator is either right-to-left or left-to-right. An identifier that can appear on the left
side of an assignment operator sometimes is referred to as an lvalue, and an item that can
appear only on the right side of an assignment operator is an rvalue. A variable can be used
as an lvalue or an rvalue, but a literal constant can only be an rvalue.
When you declare a variable within a method but do not assign a value to it, it is an
uninitialized variable. For example, the following variable declaration declares a variable
of type int named myAge, but no value is assigned at the time of creation:
int myAge;
An uninitialized variable contains an unknown value called a garbage value. Java protects you
from inadvertently using the garbage value that is stored in an uninitialized variable. For example,
if you attempt to display garbage or use it as part of a calculation, you receive an error message
stating that the variable might not have been initialized, and the program will not compile.
When you learn about creating classes in the chapter “Using Methods, Classes, and Objects,” you
will discover that variables declared in a class, but outside any method, are automatically initialized
for you.
Some programmers prefer to initialize all variables. Others prefer to initialize a variable only if it can
be given a meaningful value at the start of a program. For example, if an age will be entered by the
user, many programmers would not assign the age a value when it is first declared. You should follow
whichever practice your organization prefers.
You can declare multiple variables of the same type in separate statements. You also can
declare two or more variables of the same type in a single statement by separating the
variable declarations with a comma, as shown in the following statement:
int height = 70, weight = 190;
By convention, many programmers declare each variable in its own separate statement, but
some follow the convention of declaring multiple variables in the same statement if their
purposes are closely related. Remember that even if a statement occupies multiple lines, the
statement is not complete until the semicolon is reached.
You can declare as many variables in a statement as you want, as long as the variables are
the same data type. However, if you want to declare variables of different types, you must
use a separate statement for each type.
Declaring Named Constants
A variable is a named memory location for which the contents can change. If a named
location’s value should not change during the execution of a program, you can create it to
be a named constant. A named constant is also known as a symbolic constant. A named
97070_ch02_hr_049-109.indd 52 27/02/18 7:44 pm
53
Declaring and Using Constants and Variables
constant is similar to a variable in that it has a data type, a name, and a value. A named
constant differs from a variable in several ways:
• In its declaration statement, the data type of a named constant is preceded by the
keyword final.
• A named constant can be assigned a value only once, and then it cannot be changed
later in the program. Usually you initialize a named constant when you declare it; if you
do not initialize the constant at declaration, it is known as a blank final, and you can
assign a value later. Either way, you must assign a value to a constant before it is used.
• Although it is not a requirement, named constants conventionally are given identifiers
using all uppercase letters, using underscores as needed to separate words.
For example, each of the following defines a conventionally named constant:
final int NUMBER_OF_DEPTS = 20;
final double PI = 3.14159;
final double TAX_RATE = 0.015;
final string COMPANY = "ABC Manufacturing";
You can use each of these named constants anywhere you use a variable of the same type,
except on the left side of an assignment statement after the first value has been assigned.
In other words, when it receives a value, a named constant is an lvalue, but after the
assignment, a named constant is an rvalue.
A constant always has the same value within a program, so you might wonder why you
should not use the actual, literal value. For example, why not use the unnamed constant 20
when you need the number of departments in a company rather than going to the trouble
of creating the NUMBER_OF_DEPTS named constant? There are several good reasons to use
the named constant rather than the literal one:
• The number 20 is more easily recognized as the number of departments if it is
associated with an identifier. Using named constants makes your programs easier to
read and understand. Some programmers refer to the use of a literal numeric constant,
such as 20, as using a magic number—a value that does not have immediate, intuitive
meaning or a number that cannot be explained without additional knowledge. For
example, you might write a program that uses the value 7 for several purposes, so you
might use constants such as DAYS_IN_WEEK and NUM_RETAIL_OUTLETS that both hold the
value 7 but more clearly describe the purposes. Avoiding magic numbers helps provide
internal documentation for your programs.
• If the number of departments in your organization changes, you would change the
value of NUMBER_OF_DEPTS at one location within your program—where the constant is
defined—rather than searching for every use of 20 to change it to a different number.
Being able to make the change at one location saves you time, and prevents you from
missing a reference to the number of departments.
• Even if you are willing to search for every instance of 20 in a program to change it to
the new department number value, you might inadvertently change the value of one
instance of 20 that is being used for something else, such as a payroll deduction value.
97070_ch02_hr_049-109.indd 53 27/02/18 7:44 pm
54
Using DataC h a p t e r 2
• Using named constants reduces typographical errors. For example, if you must
include 20 at several places within a program, you might inadvertently type 10 or 200
for one of the instances, and the compiler will not recognize the mistake. However,
if you use the identifier NUMBER_OF_DEPTS, the compiler will ensure that you spell it
correctly.
• When you use a named constant in an expression, it stands out as different from a
variable. For example, in the following arithmetic statement, it is easy to see which
elements are variable and which are constant because the constants have been named
conventionally using all uppercase letters and underscores to separate words:
double payAmount = hoursWorked * STD_PAY_RATE -
numDependents * DEDUCTION;
Although many programmers use named constants to stand for most of the constant values
in their programs, many make an exception when using 0 or 1.
The Scope of Variables and Constants
A data item’s scope is the area in which it is visible to a program and in which you can
refer to it using its simple identifier. A variable or constant is in scope from the point it is
declared until the end of the block of code in which the declaration lies. A block of code is
the code contained between a set of curly braces. So, for example, if you declare a variable
or constant within a method, it can be used from its declaration until the end of the method
unless the method contains multiple sets of curly braces. Then, a data item is usable only
until the end of the block that holds the declaration.
In the chapter “Using Methods, Classes, and Objects,” you will start to create classes that contain
multiple sets of curly braces. In the chapter “More Object Concepts,” you will learn some techniques
for using variables that are not currently in scope.
Concatenating Strings to Variables and Constants
As you learned in Chapter 1, you can use a print() or println() statement to create
console output. The only difference between them is that the println() statement starts
a new line after output. You can display a variable or a constant in a print() or println()
statement alone or in combination with a string. For example, the NumbersPrintln class
shown in Figure 2-1 declares an integer billingDate, which is initialized to 5.
In one output statement in Figure 2-1, the value of billingDate is sent alone to the
print() method; in the another, billingDate is combined with, or concatenated to, a
String. In Java, when a numeric variable is concatenated to a String using the plus sign,
97070_ch02_hr_049-109.indd 54 27/02/18 7:44 pm
55
Declaring and Using Constants and Variables
Figure 2-2 Output of NumbersPrintln application
The last output statement in Figure 2-1 is spread across two lines because it is relatively long.
The statement could be written on a single line, or it could break to a new line before or after either
parenthesis or before or after the plus sign. When a line is long and contains a plus sign, this book will
follow the convention of breaking the line following the sign. When you are reading a line, seeing a plus
sign at the end makes it easier for you to recognize that the statement continues on the following line.
Later in this chapter, you will learn that a plus sign ( + ) between two numeric values indicates an addition
operation. However, when you place a string on one or both sides of a plus sign, concatenation occurs.
In Chapter 1, you learned that polymorphism describes the feature of languages that allows the same
word or symbol to be interpreted correctly in different situations based on the context. The plus sign
is polymorphic in that it indicates concatenation when used with strings but addition when used with
numbers.
the entire expression becomes a String. In Figure 2-1, print() and println() method
calls are used to display different data types, including simple Strings, an int, and a
concatenated String. The output appears in Figure 2-2.
When you concatenate Strings with numbers, the entire expression is a String. Therefore,
the expression “A” + 3 + 4 results in the String “A34”. If your intention is to create the
String “A7”, then you could add parentheses to write “A” + (3 + 4) so that the numeric
expression is evaluated first.
public class NumbersPrintln
{
public static void main(String[] args)
{
int billingDate = 5;
System.out.print("Bills are sent on day ");
System.out.print(billingDate);
System.out.println(" of the month");
System.out.println("Next bill: October " +
billingDate);
}
}
Figure 2-1 NumbersPrintln class
billingDate is concatenated with a string
billingDate is used alone
97070_ch02_hr_049-109.indd 55 27/02/18 7:44 pm
56
Using DataC h a p t e r 2
In Java, null means that no value has been assigned. It is not the same as a space or a 0; it literally
is nothing.
The program in Figure 2-1 uses the command line to display output, but you also can use
a dialog box. Recall from Chapter 1 that you can use the showMessageDialog() method
with two arguments: null, which indicates that the box should appear in the center of the
screen, and the String to be displayed in the box. (Recall from Chapter 1 that whenever a
method contains more than one argument, the arguments are separated by commas.)
import javax.swing.JOptionPane;
public class NumbersDialog
{
public static void main(String[] args)
{
int creditDays = 30;
JOptionPane.showMessageDialog(null, "" + creditDays);
JOptionPane.showMessageDialog
(null, "Every bill is due in " + creditDays + " days");
}
}
Figure 2-3 NumbersDialog class
Figure 2-4 First dialog box created by
NumbersDialog application
Figure 2-5 Second dialog box created by
NumbersDialog application
Figure 2-3 shows a NumbersDialog class that uses the showMessageDialog() method twice
to display an integer declared as creditDays and initialized to 30. In each method call, the
numeric variable is concatenated to a String, making the entire second argument a String.
In the first call to showMessageDialog(), the concatenated String is an empty String (or
null String), created by typing a set of quotes with nothing between them. The application
produces the two dialog boxes shown in Figures 2-4 and 2-5. The first dialog box shows just
the value 30; after it is dismissed by clicking OK, the second dialog box appears.
97070_ch02_hr_049-109.indd 56 27/02/18 7:44 pm
57
Declaring and Using Constants and Variables
Watch the video Declaring Variables and Constants.
Pitfall: Forgetting that a Variable Holds One Value
at a Time
Each variable can hold just one value at a time. Suppose you have two variables, x and y,
and x holds 2 and y holds 10. Suppose further that you want to switch their values so that
x holds 10 and y holds 2. You cannot simply make an assignment such as x = y because
then both variables will hold 10, and the 2 will be lost. Similarly, if you make the assignment
y = x, then both variables will hold 2, and the 10 will be lost. The solution is to declare and
use a third variable, as in the following sequence of events:
int x = 2, y = 10, z;
z = x;
x = y;
y = z;
In this example, the third variable, z, is used as a temporary holding spot for one of the
original values. The variable z is assigned the value of x, so z becomes 2. Then the value
of y, 10, is assigned to x. Finally, the 2 held in z is assigned to y. The extra variable is used
because as soon as you assign a value to a variable, any value that was previously in the
memory location is gone.
The false statement is #2. An item’s data type describes the type of data that can
be stored, how much memory the item occupies, and what types of operations
can be performed on the data. The data type does not alter the rules for a legal
identifier, and the data type does not determine whether variables can occupy
memory—all variables occupy memory.
tWO trUthS & a LIe
Declaring and Using Constants and Variables
1. A variable is a named memory location that you can use to store a value; it
can hold only one value at a time, but the value it holds can change.
2. An item’s data type determines what legal identifiers can be used to describe
variables and whether the variables can occupy memory.
3. A variable declaration is a statement that reserves a named memory location
and includes a data type, an identifier, an optional assignment operator and
assigned value, and an ending semicolon.
97070_ch02_hr_049-109.indd 57 27/02/18 7:44 pm
58
Using DataC h a p t e r 2
Declaring and Using a Variable
In this section, you write an application to work with a variable and a constant.
1. Open a new document in your text editor. Create a class header and an opening
and closing curly brace for a new class named DataDemo by typing the following:
public class DataDemo
{
}
2. Between the curly braces, indent a few spaces and type the following main()
method header and its curly braces:
public static void main(String[] args)
{
}
3. Between the main() method’s curly braces, type the following variable
declaration:
int aWholeNumber = 315;
4. Type the following output statements. The first uses the print() method to
display a string that includes a space before the closing quotation mark and
leaves the insertion point for the next output on the same line. The second
statement uses println() to display the value of aWholeNumber and then
advance to a new line.
System.out.print("The number is ");
System.out.println(aWholeNumber);
5. Save the file as DataDemo.java.
6. Up to this point in the book, every print() and println() statement you
have seen has used a String as an argument. When you added the last two
statements to the DataDemo class, you wrote a println() statement that uses
an int as an argument. As a matter of fact, there are many different versions of
print() and println() that use different data types. Go to the Java website
(www.oracle.com/technetwork/java/index.html), select Java APIs, and
then select Java SE 9. Scroll through the list of All Classes, and select
PrintStream; you will recall from Chapter 1 that PrintStream is the data type
for the out object used with the println() method. Scroll down to view the list
of methods in the Method Summary, and notice the many versions of the print()
and println() methods, including ones that accept a String, an int, a long,
and so on. In the last two statements you added to this program, one used a
You Do It
(continues)
97070_ch02_hr_049-109.indd 58 27/02/18 7:44 pm
59
Declaring and Using Constants and Variables
method version that accepts a String and the other used a method version
that accepts an int. Recall that the ability of a method to work appropriately
depending on the context is polymorphism.
7. Compile the file from the command line by
typing javac DataDemo.java. If necessary,
correct any errors, save the file, and then
compile again.
8. Execute the application from the command
line by typing java DataDemo. The command
window output is shown in Figure 2-6.
Trying to Use an Uninitialized Variable
In this section, you see what happens when a variable is uninitialized.
1. In the DataDemo class, remove the assignment operator and the initialization
value of the aWholeNumber variable so the declaration becomes:
int aWholeNumber;
2. Save the class and recompile it. An error message appears as shown in
Figure 2-7. Notice that the declaration statement does not generate an
error because you can declare a variable without initializing it. However, the
println() statement generates the error message because in Java, you
cannot display an uninitialized variable.
3. Modify the aWholeNumber declaration so that the variable is again initialized to
315. Compile the class, and execute it again.
(continues)
(continued)
Figure 2-6 Output of the
DataDemo application
Figure 2-7 Error message generated when a variable is not initialized
97070_ch02_hr_049-109.indd 59 27/02/18 7:44 pm
60
Using DataC h a p t e r 2
Learning About Integer Data Types
In Java, you can use variables of data types byte, short, int, and long to store (or hold)
integers; an integer is a whole number without decimal places. The int data type is the
most commonly used integer type. A variable of type int can hold any whole number value
from –2,147,483,648 to +2,147,483,647. When you assign a value to an int variable, you do
not type any commas or periods. Java does allow underscores in numbers; these typically
are used to make long numbers easier to read, as in the following statement:
corporateBudget = 8_435_000;
However, when you type a number, you usually type only digits and an optional plus or
minus sign to indicate a positive or negative integer.
The data types byte, short, and long are all variations of the integer type. The byte and
short types occupy less memory and can hold only smaller values; the long type occupies
more memory and can hold larger values. Table 2-2 shows the upper and lower value limits
for each of these types. In other programming languages, the format and size of primitive
data types might depend on the platform on which a program is running. By contrast, Java
consistently specifies the size and format of its primitive data types.
Adding a Named Constant to a Program
In this section, you add a named constant to the DataDemo program.
1. After the declaration of the aWholeNumber variable in the DataDemo
class, insert a new line in your program and type the following constant
declaration:
final int STATES_IN_US = 50;
2. Following the last println() statement in the existing program, add a
new statement to display a concatenated string and numeric constant.
The println() method call uses the version that accepts a String
argument.
System.out.println
("The number of states is " +
STATES_IN_US);
3. Save the program, and then compile
and execute it. The output appears in
Figure 2-8.
(continued)
Figure 2-8 Output of DataDemo
program after changes
97070_ch02_hr_049-109.indd 60 27/02/18 7:44 pm
61
Declaring and Using Constants and Variables
It is important to choose appropriate types for the variables you will use in an application. If
you attempt to assign a value that is too large for the data type of the variable, the compiler
issues an error message, and the application does not execute. If you choose a data type that
is larger than you need, you waste memory. For example, a personnel application might use
a byte variable for number of dependents (because a limit of 127 is more than enough), a
short for hours worked in a month (because 127 isn’t enough), and an int for an annual
salary (because even though a limit of 32,000 might be large enough for your salary, it isn’t
enough for the CEO’s).
Some famous glitches have occurred because programmers did not pay attention to the limits of various
data types. For example, a hospital computer system in Washington, D.C., used the equivalent of a
short to count days elapsed since January 1, 1900. The system collapsed on the 32,768th day (which
was in 1989), requiring manual operations for a lengthy period.
type Minimum Value Maximum Value Size in Bytes
byte –128 127 1
short –32,768 32,767 2
int –2,147,483,648 2,147,483,647 4
long –9,223,372,036,854,775,808 9,223,372,036,854,775,807 8
table 2-2 Limits on integer values by type
If an application uses a literal constant integer, such as 932, the number is an int by default.
If you need to use a constant higher than 2,147,483,647, the letter L must follow the number
to indicate long. For example, the following statement stores a number that is greater than
the maximum limit for the int type.
long mosquitosInTheNorthWoods = 2444555888L;
You can type either an uppercase or a lowercase L after the digits to indicate the long type,
but the uppercase L is preferred to avoid confusion with the number 1. You don’t need any
special notation to store a numeric constant in an int, a byte, or a short.
Because integer constants, such as 18, are type int by default, the examples in this book
almost always declare a variable as type int when the variable’s purpose is to hold a whole
number. That is, even if the expected value is less than 128, such as hoursWorkedToday, this
book will declare the variable to be an int. If you are writing an application in which saving
memory is important, you might choose to declare the same variable as a byte. Saving
memory is seldom an issue for an application that runs on a PC. However, when you write
applications for small devices with limited memory, such as phones, conserving memory
becomes more important.
97070_ch02_hr_049-109.indd 61 27/02/18 7:44 pm
62
Using DataC h a p t e r 2
Working with Integers
In this section, you work more with integer values.
1. Open a new file in your text editor, and create a shell for an IntegerDemo class
as follows:
public class IntegerDemo
{
}
2. Between the curly braces, indent a few spaces and write the shell for a main()
method as follows:
public static void main(String[] args)
{
}
3. Within the main() method, create four declarations, one each for the four
integer data types.
int anInt = 12;
byte aByte = 12;
short aShort = 12;
long aLong = 12;
You Do It
The false statement is #3. You use a long if you know you will be working with
very large values; you use a byte or a short if you know a variable will need to
hold only small values.
tWO trUthS & a LIe
Learning About Integer Data Types
1. A variable of type int can hold any whole number value from approximately
negative two billion to positive two billion.
2. When you assign a value to an int variable, you do not type any commas;
you type only digits and an optional plus or minus sign to indicate a positive
or negative integer.
3. You can use the data types byte or short to hold larger values than can be
accommodated by an int.
(continues)
97070_ch02_hr_049-109.indd 62 27/02/18 7:44 pm
63
Declaring and Using Constants and Variables
4. Next, add four output statements that describe and display each of the values.
Extra spaces are included at the ends of the string literals so that the ending
quotation marks align and the values will be aligned vertically when they are
displayed.
System.out.println("The int is " + anInt);
System.out.println("The byte is " + aByte);
System.out.println("The short is " + aShort);
System.out.println("The long is " + aLong);
5. Save the file as IntegerDemo.java. Then
compile and execute it. Figure 2-9 shows
the output. All the values are legal sizes for
each data type, so the program compiles and
executes without error.
6. Change each assigned value in the application
from 12 to 1234, and then save and
recompile the program. Figure 2-10 shows
the error message generated because
1234 is too large to be placed in a byte variable. The message possible
lossy conversion from int to byte means that if the large number had been
inserted into the small space, the accuracy of the number would have been
compromised. A lossy conversion is one in which some data is lost. The
opposite of a lossy conversion is a lossless conversion—one in which no data
is lost. (The error message differs in other development environments and in
some earlier versions of Java.)
7. Change the value of aByte back to 12. Change the value of aShort to
123456. Save and recompile the program. Figure 2-11 shows the result. The
error message “possible lossy conversion” is the same as when the byte value
was invalid, but the error indicates that the problem is now with the short
variable.
(continues)
(continued)
Figure 2-9 Output of the
IntegerDemo program
Figure 2-10 Error message generated when a value that is too large is assigned to a
byte variable
97070_ch02_hr_049-109.indd 63 27/02/18 7:44 pm
64
Using DataC h a p t e r 2
8. Change the value of the short variable to 12345, and then save and compile
the program. Now, the program compiles without error. Execute the program,
and confirm that it runs as expected.
9. At the Java website (www.oracle.com/technetwork/java/index.html),
examine the list of println() methods in the PrintStream class. Although
you can find versions that accept String, int, and long arguments, you
cannot find ones that accept byte or short values. Yet, the println()
statements in the latest version of the program work correctly. The reason has
to do with type conversion, which you will learn about later in this chapter.
10. Replace the value of aLong with 1234567890987654321. Save the
program and compile it. Figure 2-12 shows the error message that indicates
that the integer number is too large. The message does not say that the value
is too big for a long type variable. Instead, it means that the literal constant
was evaluated and found to be too large to be a default int before any
attempt was made to store it in the long variable.
11. Remedy the problem by adding an L to the end of the long numeric
value. Now, the constant is the correct data type that can be assigned to
the long variable. Save, compile, and execute the program; it executes
successfully.
(continues)
(continued)
Figure 2-11 Error message generated when a value that is too large is assigned to
a short variable
Figure 2-12 Error message generated when an integer value is too large
97070_ch02_hr_049-109.indd 64 27/02/18 7:44 pm
65
Using the boolean Data Type
12. Watch out for errors that occur when data values are acceptable for a data
type when used alone, but together might produce arithmetic results that are
out of range. To demonstrate, add the following declaration at the end of the
current list of variable declarations in the IntegerDemo program:
int anotherInt = anInt * 10000000;
13. At the end of the current list of output statements, add another output
statement so that you can see the result of the arithmetic:
System.out.println("Another int is " + anotherInt);
Save, compile, and execute the program. The output appears in Figure 2-13.
Although 1234 and 10000000 are both acceptable int values, their product
is out of range for an int, and the resulting int does not appear to have been
calculated correctly.
Because the arithmetic
result was too large,
some information about
the value has been lost,
including the result’s
sign. If you see such
unreasonable results
in your programs, you
need to consider using
different data types for
your values.
(continued)
Figure 2-13 Output of the modified
IntegerDemo program with an out-of-range
integer
Using the boolean Data type
Boolean logic is based on true or false comparisons. Whereas an int variable can hold
millions of different values (at different times), a variable that is the boolean data type can
hold only one of two values—true or false. The following statements declare and assign
appropriate values to Boolean variables:
boolean isItPayday = false;
boolean areYouBroke = true;
Although you can use any legal identifier for Boolean variables, they are easily identified
as Boolean if you use a form of to be (such as is or are) as part of the variable name, as in
isItPayday.
Besides assigning true and false, you also can assign a value to a Boolean variable based
on the result of a comparison. Java supports six relational operators that are used to
97070_ch02_hr_049-109.indd 65 27/02/18 7:44 pm
66
Using DataC h a p t e r 2
make comparisons. A relational operator compares two items; it is sometimes called a
comparison operator. The value of an expression that contains a relational operator is
always true or false. Table 2-3 describes the relational operators.
When you use Boolean as an adjective, as in Boolean operators, you usually begin with an uppercase B
because the data type is named for Sir George Boole, the founder of symbolic logic, who lived from
1815 to 1864. The Java data type boolean, however, begins with a lowercase b.
Operator Description true example False example
, Less than 3 , 8 8 , 3
. Greater than 4 . 2 2 . 4
55 Equal to 7 55 7 3 55 9
,5 Less than or equal to 5 ,5 5 8 ,5 6
.5 Greater than or equal to 7 .5 3 1 .5 2
!5 Not equal to 5 !5 6 3 !5 3
table 2-3 Relational operators
When you use any of the operators that have two symbols (55, ,5, .5, or !5), you
cannot place any whitespace between the two symbols. You also cannot reverse the order
of the symbols. That is, 5,, 5., and 5! are all invalid operators.
Legal declaration statements, which compare two values directly, might include the
following statements:
boolean isSixBigger = (6 > 5);
// Value stored would be true
boolean isSevenSmallerOrEqual = (7 <= 4);
// Value stored would be false
Boolean expressions are more meaningful when a variable is used for one or both of
the operands in a comparison, as in the following three examples, in which a variable
is compared to a literal constant (40), a variable is compared to a named constant
(HIGH_CUTOFF), and two variables are compared.
boolean isOvertimePay = (hours > 40);
boolean isTaxBracketHigh = (income > HIGH_CUTOFF);
boolean isFirstScoreHigher = (score1 > score2);
Boolean expressions will become far more useful to you when you learn about decision
making and looping in Chapters 5 and 6.
97070_ch02_hr_049-109.indd 66 27/02/18 7:44 pm
67
Learning About Floating-Point Data Types
Learning about Floating-point Data types
A floating-point number contains decimal positions. Java supports two floating-point
data types: float and double. A float data type can hold floating-point values of up to
six or seven significant digits of accuracy. A double data type requires more memory
than a float, and can hold 14 or 15 significant digits of accuracy. The term significant
digits refers to the mathematical accuracy of a value. For example, a float given the value
0.324616777 is displayed as 0.324617 because the value is accurate only to the sixth decimal
position. Table 2-4 shows the minimum and maximum values for each floating-point data
type. Notice that the maximum value for a double is 1.7 * 10 to the 308th power, which
means 1.7 times 10 with 308 trailing zeros—a very large number.
Depending on the environment in which you run your program, a float given the value 324616777
is displayed using a decimal point after the 3 and only six or seven digits followed by e+008 or E8.
This format is called scientific notation, and means that the value is approximately 3.24617 times
10 to the 8th power, or 324617000. When a number is in scientific notation, the value to the left of the
decimal point is always greater than or equal to 1 and less than 10. The e in the displayed value stands
for exponent; the 8 means the true decimal point is eight positions to the right of where it is displayed,
indicating a very large number. (A negative number following the e would mean that the true decimal
point belongs to the left, indicating a very small number.)
A programmer might choose to store a value as a float instead of a double to save memory.
However, if high levels of accuracy are needed, such as in graphics-intensive software, the programmer
might choose to use a double, opting for high accuracy over saved memory.
The false statement is #2. The six relational operators used to make comparisons
are 55 (two equal signs), ,, ., ,5 (the less-than sign precedes the equal sign),
.5 (the greater-than sign precedes the equal sign), and !5 (the exclamation point
precedes the equal sign).
tWO trUthS & a LIe
Using the boolean Data type
1. A Boolean variable can hold only one of two values—true or false.
2. Java supports six relational operators that are used to make comparisons:
5, ,, ., 5,, 5., and 5!.
3. An expression that contains a relational operator has a Boolean value.
97070_ch02_hr_049-109.indd 67 27/02/18 7:44 pm
68
Using DataC h a p t e r 2
A value stored in a double is a double-precision floating-point number; a value in a float is a
single-precision floating-point number.
The false statement is #2. A floating-point constant, such as 5.6, is a double by
default.
tWO trUthS & a LIe
Learning About Floating-Point Data Types
1. Java supports two floating-point data types: float and double. The double
data type requires more memory and can hold more significant digits.
2. A floating-point constant, such as 5.6, is a float by default.
3. As with integers, you can perform the mathematical operations of addition,
subtraction, multiplication, and division with floating-point numbers.
type Minimum Maximum Size in Bytes
float –3.4 * 1038 3.4 * 1038 4
double –1.7 * 10308 1.7 * 10308 8
table 2-4 Limits on floating-point values
Just as an integer constant, such as 18, is a value of type int by default, a floating-point
constant, such as 18.23, is a double by default. To indicate that a floating-point numeric
constant is a float, you can type the letter F after the number, as in the following:
float pocketChange = 4.87F;
You can type either a lowercase or an uppercase F. You also can type D (or d) after a floating-
point constant to indicate it is a double, but even without the D, the value will be stored as a
double by default. Floating-point numbers can be imprecise, as you will see later in this chapter.
Using the char Data type
You use the char data type to hold any single character. You place constant character
values within single quotation marks because the computer stores characters and integers
differently. For example, the following are typical character declarations:
char middleInitial = 'M';
char gradeInChemistry = 'A';
char aStar = '*';
97070_ch02_hr_049-109.indd 68 27/02/18 7:44 pm
69
Using the char Data Type
A character can be any letter—uppercase or lowercase. It also might be a punctuation mark
or digit. A character that is a digit is represented in computer memory differently from a
numeric value represented by the same digit. For example, the following two statements are
legal:
char aCharValue = '9';
int aNumValue = 9;
If you display each of these values using a println() statement, you see a 9. However,
only the numeric value, aNumValue, can be used to represent the value 9 in arithmetic
statements.
A numeric constant can be stored in a character variable, and a character that represents
a number can be stored in a numeric variable. For example, the following two statements
are legal, but unless you understand their meanings, they might produce undesirable
results:
char aCharValue = 9;
int aNumValue = '9';
If these variables are displayed using println() statements, then the resulting output is
a blank for aCharValue and the number 57 for aNumValue. The unexpected values are
Unicode values. Every computer stores every character it uses as a number; every character
is assigned a unique numeric code using Unicode. Table 2-5 shows some Unicode decimal
values and their character equivalents. For example, the character A is stored using the
value 65, and the character B is stored using the value 66. Appendix B contains more
information on Unicode.
A variable of type char can hold only one character. To store a string of characters, such as
a person’s name, you must use a data structure called a String. In Java, String is a built-in
class that provides you with the means for storing and manipulating character strings.
Unlike single characters, which use single quotation marks, string constants are written
between double quotation marks. For example, the expression that stores the name Audrey
as a string in a variable named firstName is as follows:
String firstName = "Audrey";
Some programmers prefer to pronounce char as care because it represents the first syllable in the word
character. Others prefer to pronounce the word as char to rhyme with car. You should use the preferred
pronunciation in your organization.
You will learn more about strings and the String class in the chapter “Characters, Strings, and the
StringBuilder.”
97070_ch02_hr_049-109.indd 69 27/02/18 7:44 pm
70
Using DataC h a p t e r 2
Dec Char Dec Char Dec Char Dec Char
0 nul 32 64 @ 96 `
1 soh^A 33 ! 65 A 97 a
2 stx^B 34 “ 66 B 98 b
3 etx^C 35 # 67 C 99 c
4 eot^D 36 $ 68 D 100 d
5 enq^E 37 % 69 E 101 e
6 ask^F 38 & 70 F 102 f
7 bel^G 39 ‘ 71 G 103 g
8 bs^H 40 ( 72 H 104 h
9 ht^I 41 ) 73 I 105 i
10 If^J 42 * 74 J 106 j
11 vt^K 43 1 75 K 107 k
12 ff^L 44 , 76 L 108 l
13 cr^M 45 - 77 M 109 m
14 so^N 46 . 78 N 110 n
15 si^O 47 / 79 O 111 o
16 dle^P 48 0 80 P 112 p
17 dcl^Q 49 1 81 Q 113 q
18 dc2^R 50 2 82 R 114 r
19 dc3^S 51 3 83 S 115 s
20 dc4^T 52 4 84 T 116 t
21 nak^U 53 5 85 U 117 u
22 syn^V 54 6 86 V 118 v
23 etb^W 55 7 87 W 119 w
24 can^X 56 8 88 X 120 x
25 em^Y 57 9 89 Y 121 y
26 sub^Z 58 : 90 Z 122 z
27 esc 59 ; 91 [ 123 {
28 fs 60 , 92 \ 124 |
29 gs 61 5 93 ] 125 }
30 rs 62 . 94 ^ 126 ~
31 us 63 ? 95 _ 127 del
table 2-5 Unicode values 0 through 127 and their character equivalents
97070_ch02_hr_049-109.indd 70 27/02/18 7:44 pm
71
When you display values within JOptionPane dialog boxes rather than in a command window, the
escape sequences '\n' (newline), '\"' (double quote), and '\\' (backslash) operate as expected
within a JOptionPane object, but '\t', '\b', and '\r' do not work in the GUI environment.
When you want to produce console output on multiple lines in the command window, you
have two options: You can use the newline escape sequence, or you can use the println()
method multiple times. For example, Figures 2-14 and 2-15 both show classes that produce
the same output: Hello on one line and there on another. The version you choose to use
is up to you. The example in Figure 2-14 is more efficient—from a typist’s point of view
because the text System.out.println appears only once, and from the compiler’s point
of view because the println() method is called only once. The example in Figure 2-15,
however, might be easier to read and understand. When programming in Java, you will find
occasions when each of these approaches makes sense.
You can store any character—including nonprinting characters such as a backspace or
a tab—in a char variable. To store these characters, you can use an escape sequence,
which always begins with a backslash followed by a character—the pair represents a single
character. For example, the following code stores a newline character and a tab character in
the char variables aNewLine and aTabChar:
char aNewLine = '\n';
char aTabChar = '\t';
In the declarations of aNewLine and aTabChar, the backslash and character pair acts as a
single character; the escape sequence serves to give a new meaning to the character. That is,
the literal characters in the preceding code have different values from the “plain” characters
‘n’ or ‘t’. Table 2-6 describes some common escape sequences that you can use with
command window output in Java.
escape
Sequence Description
\b Backspace; moves the cursor one space to the left
\t Tab; moves the cursor to the next tab stop
\n Newline or linefeed; moves the cursor to the beginning of the next line
\r Carriage return; moves the cursor to the beginning of the current line
\" Double quotation mark; displays a double quotation mark
\' Single quotation mark; displays a single quotation mark
\\ Backslash; displays a backslash character
table 2-6 Common escape sequences
Using the char Data Type
97070_ch02_hr_049-109.indd 71 27/02/18 7:44 pm
72
Using DataC h a p t e r 2
The println() method uses the local platform’s line terminator character, which might or might not
be the newline character ‘\n’.
The false statement is #2. To store a string of characters, you use a data struc-
ture called a String; string constants are written between double quotation
marks.
tWO trUthS & a LIe
Using the char Data Type
1. You use the char data type to hold any single character; you place constant
character values within single quotation marks.
2. To store a string of characters, you use a data structure called a Text; string
constants are written between parentheses.
3. An escape sequence always begins with a backslash followed by a character;
the pair represents a single character.
public class HelloThereNewLine
{
public static void main(String[] args)
{
System.out.println("Hello\nthere");
}
}
Figure 2-14 HelloThereNewLine class
public class HelloTherePrintlnTwice
{
public static void main(String[] args)
{
System.out.println("Hello");
System.out.println("there");
}
}
Figure 2-15 HelloTherePrintlnTwice class
97070_ch02_hr_049-109.indd 72 27/02/18 7:44 pm
73
Working with the char Data Type
In the steps in this section, you create an application that demonstrates some
features of the char data type.
1. Create the shells for a class named CharDemo and its main() method as follows:
public class CharDemo
{
public static void main(String[] args)
{
}
}
2. Between the curly braces for the main() method, declare a char variable, and
provide an initialization value:
char initial = 'A';
3. Add two statements. The first displays the variable, and the second
demonstrates some escape sequence characters.
System.out.println(initial);
System.out.print("\t\"abc\\def\bghi\n\njkl");
4. Save the file as CharDemo.java, and then compile and execute it. Figure 2-16
shows the output. The first line of output contains the value of the char variable.
The next line starts with a tab created by the escape sequence \t. The tab is
followed by a quotation mark produced by the
escape sequence \”. Then abc is displayed,
followed by the next escape sequence that
produces a backslash. The next series of
characters to display is def, but because those
letters are followed by a backspace escape
sequence, the f is overridden by ghi. After ghi,
two newline escape sequences provide a double-
spaced effect. Finally, the last three characters
jkl are displayed.
5. Modify, recompile, and execute the CharDemo program as many times as you
like until you can accurately predict what will be displayed when you use various
combinations of characters and escape sequences.
You Do It
Figure 2-16 Output of the
CharDemo program
Using the char Data Type
97070_ch02_hr_049-109.indd 73 27/02/18 7:44 pm
74
Using DataC h a p t e r 2
Using the Scanner Class to accept Keyboard Input
Although you can assign values to variables you declare, programs typically become more
useful when a user can supply different values for variables each time a program executes.
In Chapter 1, you learned how to display output on the monitor using the System.out
property. System.out refers to the standard output device, which usually is the monitor. To
create interactive programs that accept input from a user, you can use System.in, which
refers to the standard input device (normally the keyboard).
You have learned that you can use the print() and println() methods to display many data
types; for example, you can use them to display a double, int, or String. The System.in
object is not as flexible; it is designed to read only bytes. That’s a problem, because you often
want to accept data of other types. Fortunately, the designers of Java have created a class
named Scanner that makes System.in more flexible.
To create a Scanner object and connect it to the System.in object, you write a statement
similar to the following:
Scanner inputDevice = new Scanner(System.in);
The portion of the statement to the left of the assignment operator, Scanner  inputDevice,
declares an object of type Scanner with the programmer-chosen name inputDevice, in
exactly the same way that int x; declares an integer with the programmer-chosen name x.
The portion of the statement to the right of the assignment operator,
new Scanner(System.in), creates a Scanner object that is connected to the System.in
property. In other words, the created Scanner object is connected to the default input
device. The keyword new is required by Java; you will use it whenever you create objects
that are more complex than the primitive data types.
In the chapter “More Object Concepts,” you will learn that the second part of the Scanner declaration
calls a special method called a constructor that is part of the prewritten Scanner class. You also will
learn more about the Java keyword new in the next two chapters.
The assignment operator in the Scanner declaration statement assigns the value of the new
object—that is, its memory address—to the inputDevice object in the program.
The Scanner class contains methods that retrieve values from an input device. Each
retrieved value is a token, which is a set of characters that is separated from the next set by
whitespace. Most often, this means that data is accepted when a user presses the Enter key,
but it also could mean that a token is accepted after a space or tab. Table 2-7 summarizes
some of the most useful methods that read different data types from the default input
device. Each retrieves a value from the keyboard and returns it if the next token is the
correct data type.
97070_ch02_hr_049-109.indd 74 27/02/18 7:44 pm
75
Using the Scanner Class to Accept Keyboard Input
The Scanner class does not contain a nextChar() method. To retrieve a single character from the
keyboard, you can use the nextLine() method and then use the charAt() method. The chapter
“Characters, Strings, and the StringBuilder” provides more details about the charAt() method.
Method Description
nextDouble() Retrieves input as a double
nextInt() Retrieves input as an int
nextLine() Retrieves the next line of data and returns it as a String
next() Retrieves the next complete token as a String
nextShort() Retrieves input as a short
nextByte() Retrieves input as a byte
nextFloat() Retrieves input as a float. Note that when you enter an input value that
will be stored as a float, you do not type an F. The F is used only with
constants coded within a program.
nextLong() Retrieves input as a long. Note that when you enter an input value that
will be stored as a long, you do not type an L. The L is used only with
constants coded within a program.
table 2-7 Selected Scanner class methods
Figure 2-17 contains a program that uses two of the Scanner class methods, and
Figure 2-18 shows a typical execution. The program reads a string and an integer from the
keyboard and displays them. The Scanner class is used in four statements in the figure.
• The first statement in the figure imports the package necessary to use the Scanner class.
• A Scanner object named inputDevice is declared.
• The nextLine() method is used with inputDevice to retrieve a line of text from the
keyboard and store it in the name variable.
• The nextInt() method is used with inputDevice to retrieve an integer from the
keyboard and store it in the age variable.
Java programmers would say that the Scanner methods return the appropriate value. That also means
that the value of the method is the appropriate value, and that you can assign the returned value to
a variable, display it, or use it in other legal statements. In the chapter “Using Methods, Classes, and
Objects,” you will learn how to write your own methods that return values.
97070_ch02_hr_049-109.indd 75 27/02/18 7:44 pm
76
Using DataC h a p t e r 2
Repeating as output the values a user has entered is sometimes called echoing the input.
If you use any of the Scanner methods and the next token cannot be converted to the right
data type, you receive an error message. For example, the program in Figure 2-17 uses
nextInt() to retrieve age, so if the user entered a noninteger value for age, such as the
double 19.5 or the String "nineteen", an error would occur. You will learn how to recover
from this type of error in the chapter “Exception Handling,” but for now, you will have to
trust the user to enter the correct data type.
The literal Strings contained in the print() statements that appear before each input
statement in Figure 2-17 are examples of prompts. A prompt is a message displayed for the
user that requests and describes input. Interactive programs would work without prompts,
but they would not be as user-friendly. Each prompt in the GetUserInfo class ends with
two greater-than signs and a space. This punctuation is not required; it just separates the
words in the prompt from the user’s input value on the screen, improving readability. You
might prefer to use a series of periods, several dashes, or just a few spaces.
Figure 2-17 The GetUserInfo class
import java.util.Scanner;
public class GetUserInfo
{
public static void main(String[] args)
{
String name;
int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter your name >> ");
name = inputDevice.nextLine();
System.out.print("Please enter your age >> ");
age = inputDevice.nextInt();
System.out.println("Your name is " + name +
" and you are " + age + " years old.");
}
}
The Scanner class
is imported, and
used to create an
object.
The Scanner
object is used with
the nextLine()
method.
Figure 2-18 Typical execution of the GetUserInfo program
97070_ch02_hr_049-109.indd 76 27/02/18 7:44 pm
77
It is legal to write a single prompt that requests multiple input values—for example,
Please enter your age, area code, and zip code >>. The user could then enter the three
values separated with spaces, tabs, or Enter key presses. The values would be interpreted
as separate tokens and could be retrieved with three separate nextInt() method calls.
However, asking a user to enter multiple values is more likely to lead to mistakes. For
example, if a program asks a user to enter a name, address, and birthdate all at once, the
user is likely to forget one of the values or to enter them in the wrong order. This book will
follow the practice of using a separate prompt for each input value required.
Pitfall: Using nextLine() Following One of the Other Scanner
Input Methods
You can encounter a problem when you use one of the numeric Scanner class retrieval
methods or the next() method before you use the nextLine() method. Consider the
program in Figure 2-19. It is identical to the one in Figure 2-17, except that the user is
asked for an age before being asked for a name. Figure 2-20 shows a typical execution.
Figure 2-19 The GetUserInfo2 class
import java.util.Scanner;
public class GetUserInfo2
{
public static void main(String[] args)
{
String name;
int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter your age >> ");
age = inputDevice.nextInt();
System.out.print("Please enter your name >> ");
name = inputDevice.nextLine();
System.out.println("Your name is " + name +
" and you are " + age + " years old.");
}
}
If you accept numeric input
prior to string input, the
string input is ignored
unless you take special
action.
Don’t Do It
Figure 2-20 Typical execution of the GetUserInfo2 program
Using the Scanner Class to Accept Keyboard Input
97070_ch02_hr_049-109.indd 77 27/02/18 7:45 pm
78
Using DataC h a p t e r 2
In Figure 2-20, the user is prompted correctly for an age. However, after the user enters an
age and the prompt for the name is displayed, the program does not pause to let the user
enter a name. Instead, the program proceeds directly to the output statement, which does
not contain a valid name.
When you type characters using the keyboard, they are stored temporarily in a location in
memory called the keyboard buffer or the type-ahead buffer. All keystrokes are stored
in the keyboard buffer, including the Enter key. The problem occurs because of a difference
in the way the nextLine() method and the other Scanner retrieval methods work:
• The Scanner methods next(), nextInt(), and nextDouble() retrieve the next token in
the buffer up to the next whitespace, which might be a space, tab, or Enter key.
• The nextLine() method reads all data up to the Enter key character.
So, in the execution of the program in Figure 2-20, the user is prompted for an age, types 28,
and presses Enter. The call to the nextInt() method retrieves the 28 and leaves the Enter
key press in the input buffer. Then, the name prompt is displayed and the call to nextLine()
retrieves the waiting Enter key before the user has time to type a name.
The solution to the problem is simple. After any next(), nextInt(), or nextDouble() call,
you can add an extra nextLine() method call that will retrieve the abandoned Enter key
character. Then, no matter what type of input follows, the program will execute smoothly.
Figure 2-21 shows a program that contains just one change from Figure 2-19—the addition
of the statement that retrieves the abandoned Enter key character from the input buffer.
Figure 2-21 shows that the call to nextInt() accepts the integer, the first call to nextLine()
consumes the Enter key that follows the integer entry, and the second nextLine() call
accepts both the entered name and the Enter key that follows it. Figure 2-22 shows that the
revised program executes correctly.
Figure 2-21 The GetUserInfo3 class
import java.util.Scanner;
public class GetUserInfo3
{
public static void main(String[] args)
{
String name;
int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter your age >> ");
age = inputDevice.nextInt();
inputDevice.nextLine();
System.out.print("Please enter your name >> ");
name = inputDevice.nextLine();
System.out.println("Your name is " + name +
" and you are " + age + " years old.");
}
}
This statement gets
the integer.
This statement gets
the name and
discards the Enter
key that follows the
name.
This statement
consumes the Enter
key that follows the
integer.
97070_ch02_hr_049-109.indd 78 27/02/18 7:45 pm
79
Figure 2-22 Typical execution of the GetUserInfo3 program
The false statement is #2. System.in is not as flexible as System.out. System.out
can display various data types, but System.in is designed to read only bytes.
tWO trUthS & a LIe
Using the Scanner Class to Accept Keyboard Input
1. System.in refers to the standard input device, which normally is the keyboard.
2. System.in is more flexible than System.out because it can read all the
basic Java data types.
3. When a user types data followed by the Enter key, the Enter key character
is left in the keyboard buffer after Scanner class methods retrieve the other
keystrokes.
Accepting User Input
In the next steps, you create a program that accepts user input.
1. Open the IntegerDemo.java file you created in a “You Do It” section earlier in
this chapter. Change the class name to IntegerDemoInteractive, and save the
file as IntegerDemoInteractive.java.
You Do It
Although you could assign the Enter key value to a character variable in the program in Figure 2-21,
there is no need to do so. When you accept an entry and discard it without using it, programmers say
that the entry is consumed.
When you write programs that accept user input, there is a risk that the user will enter the wrong type
of data. For example, if you include a nextInt() method call in your program, but the user types an
alphabetic character, an error will occur, and your program will stop running. You will learn to handle this
type of error later in this book.
(continues)
Using the Scanner Class to Accept Keyboard Input
97070_ch02_hr_049-109.indd 79 27/02/18 7:45 pm
80
Using DataC h a p t e r 2
2. As the first line in the file, insert an import statement that will allow you to use
the Scanner class:
import java.util.Scanner;
3. Remove the assignment operator and the assigned values from each of the four
numeric variable declarations.
4. Following the numeric variable declarations, insert a Scanner object declaration:
Scanner input = new Scanner(System.in);
5. Following the variable declarations, insert a prompt for the integer value, and an
input statement that accepts the value, as follows:
System.out.print("Please enter an integer >> ");
anInt = input.nextInt();
6. Then add similar statements for the other three variables:
System.out.print("Please enter a byte integer >> ");
aByte = input.nextByte();
System.out.print("Please enter a short integer >> ");
aShort = input.nextShort();
System.out.print("Please enter a long integer >> ");
aLong = input.nextLong();
7. Save the file, and then compile and execute it. Figure 2-23 shows a typical
execution. Execute the program a few more times, using different values each
time and confirming that the correct values have been accepted from the
keyboard.
(continues)
(continued)
Figure 2-23 Typical execution of the
IntegerDemoInteractive program
97070_ch02_hr_049-109.indd 80 27/02/18 7:45 pm
81
Adding String Input
Next, you add String input to the IntegerDemoInteractive program.
1. Change the class name of the IntegerDemoInteractive program to
IntegerDemoInteractiveWithName, and immediately save the file as
IntegerDemoInteractiveWithName.java.
2. Add a new variable with the other variable declarations as follows:
String name;
3. After the last input statement (that gets the value for aLong), add three
statements that prompt the user for a name, accept the name, and use the
name as follows:
System.out.print("Please enter your name >> ");
name = input.nextLine();
System.out.println("Thank you, " + name);
4. Save the file, and compile and execute it. Figure 2-24 shows a typical execution.
You can enter the numbers, but when the prompt for the name appears, you
are not given the opportunity to respond. Instead, the string "Thank you, ",
including the ending comma and space, is output immediately, and the program
ends. This output is incorrect because the input statement that should retrieve
the name from the keyboard instead retrieves the Enter key that was still in the
keyboard buffer after the last numeric entry.
(continues)
(continued)
Figure 2-24 Typical execution of incomplete
IntegerDemoInteractiveWithName application that does
not accept a name
Using the Scanner Class to Accept Keyboard Input
97070_ch02_hr_049-109.indd 81 27/02/18 7:45 pm
82
Using DataC h a p t e r 2
5. To fix the problem, insert an extra call to the nextLine() method just before
the statement that accepts the name. This call will consume the Enter key. You
do not need an assignment operator with this statement, because there is no
need to store the Enter key character.
input.nextLine();
6. Save, compile, and execute the program. Figure 2-25 shows a typical
successful execution.
(continued)
Figure 2-25 Typical successful execution of
IntegerDemoInteractiveWithName application
Using the JOptionPane Class to accept GUI Input
In Chapter 1, you learned how to display output at the command line and how to create
GUI message boxes to display String objects. Earlier in this chapter, you learned to accept
input from the keyboard at the command line. You also can accept input in a GUI dialog
box using the JOptionPane class.
Two dialog boxes that can be used to accept user input are as follows:
• InputDialog—Prompts the user for text input
• ConfirmDialog—Asks the user a question, providing buttons that the user can click for
Yes, No, and Cancel responses
97070_ch02_hr_049-109.indd 82 27/02/18 7:45 pm
83
Using the JOptionPane Class to Accept GUI Input
Using Input Dialog Boxes
An input dialog box asks a question and provides a text field in which the user can enter
a response. You can create an input dialog box using the showInputDialog() method. Six
versions of this method are available, but the simplest version uses a single argument that
is the prompt you want to display within the dialog box. The showInputDialog() method
returns a String that represents a user’s response; this means that you can assign the
showInputDialog() method to a String variable and the variable will hold the value that
the user enters.
For example, Figure 2-26 shows an application that creates an input dialog box containing a
prompt for a first name. When the user executes the application, types William, then clicks
the OK button or presses Enter on the keyboard, the result String will contain William.
In the application in Figure 2-26, the response is concatenated with a welcoming message
and displayed in a message dialog box. Figure 2-27 shows the dialog box containing a user’s
response, and Figure 2-28 shows the resulting output message box.
Figure 2-28 Output of the HelloNameDialog
application
Figure 2-27 Input dialog box of the
HelloNameDialog application
import javax.swing.JOptionPane;
public class HelloNameDialog
{
public static void main(String[] args)
{
String result;
result = JOptionPane.showInputDialog(null, "What is your name?");
JOptionPane.showMessageDialog(null, "Hello, " + result + "!");
}
}
Figure 2-26 The HelloNameDialog class
When a computer has a touch screen, you might want the user to be able to use the operating system’s
virtual keyboard to enter data. You will learn how to display the virtual keyboard after you learn about
exception handling in Chapter 12.
97070_ch02_hr_049-109.indd 83 27/02/18 7:45 pm
84
Using DataC h a p t e r 2
A different version of the showInputDialog() method requires four arguments that allow
the programmer flexibility in controlling the appearance of the input dialog box. The four
arguments to showInputDialog() include the following:
• The parent component, which is the screen component, such as a frame, in front of
which the dialog box will appear. If this argument is null, the dialog box is centered on
the screen.
• The message the user will see before entering a value. Usually this message is a String,
but it actually can be any type of object.
• The title to be displayed in the title bar of the input dialog box.
• A class field describing the type of dialog box; it can be one of the following:
ERROR_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE,
or WARNING_MESSAGE.
For example, when the following statement executes, it displays the input dialog box shown
in Figure 2-29.
JOptionPane.showInputDialog(null,
"What is your area code?",
"Area code information",
JOptionPane.QUESTION_MESSAGE);
Note that the title bar displays Area code information, and the dialog box shows a question
mark icon.
The showInputDialog() method
returns a String object that holds the
combination of keystrokes a user types
into the dialog box. If the value that the
user enters is intended to be used as a
number, as in an arithmetic statement,
the returned String must be converted
to the correct numeric type. Later in this
chapter, you will learn how to change
primitive data from one data type to
another. However, the techniques you
will learn work only with primitive data
types—double, int, char, and so on—not with class objects (that are reference types) such
as a String. To convert a String to an int or double, you must use methods from the
built-in Java classes Integer and Double. Each primitive type in Java has a corresponding
class contained in the java.lang package; like most classes, the names of these classes
begin with uppercase letters. These classes are called type-wrapper classes. They include
methods that can process primitive type values.
Figure 2-29 An input dialog box with a String
in the title bar and a question mark icon
97070_ch02_hr_049-109.indd 84 27/02/18 7:45 pm
85
Figure 2-30 shows a SalaryDialog application that contains two String objects—
wageString and dependentsString. Two showInputDialog() methods are called, and the
answers are stored in the declared Strings. Figure 2-30 shows the Strings being converted
to numeric values using the Double.parseDouble() and the Integer.parseInt() method.
The methods are, respectively, from the type-wrapper classes Double and Integer.
Figure 2-31 shows a typical execution of the application.
The term parse means to break into component parts. Grammarians talk about “parsing a sentence”—
deconstructing it so as to describe its grammatical components. Parsing a String converts it to its
numeric equivalent.
Remember that in Java, the reserved keyword static means that a method is accessible and usable
even though no objects of the class exist. You can tell that the method Double.parseDouble()
is a static method, because the method name is used with the class name Double—no object is
needed. Similarly, you can tell that Integer.parseInt() is also a static method.
import javax.swing.JOptionPane;
public class SalaryDialog
{
public static void main(String[] args)
{
String wageString, dependentsString;
double wage, weeklyPay;
int dependents;
final double HOURS_IN_WEEK = 37.5;
wageString = JOptionPane.showInputDialog(null,
"Enter employee's hourly wage", "Salary dialog 1",
JOptionPane.INFORMATION_MESSAGE);
weeklyPay = Double.parseDouble(wageString) *
HOURS_IN_WEEK;
dependentsString = JOptionPane.showInputDialog(null,
"How many dependents?", "Salary dialog 2",
JOptionPane.QUESTION_MESSAGE);
dependents = Integer.parseInt(dependentsString);
JOptionPane.showMessageDialog(null, "Weekly salary is $" +
weeklyPay + "\nDeductions will be made for " +
dependents + " dependents");
}
}
Figure 2-30 The SalaryDialog class
Statement uses
parseDouble() to
convert String.
Statement uses parseInt()
to convert String.
Using the JOptionPane Class to Accept GUI Input
97070_ch02_hr_049-109.indd 85 27/02/18 7:45 pm
86
Using DataC h a p t e r 2
Using Confirm Dialog Boxes
Sometimes, the input you want from a user does not have to be typed from the keyboard. When
you present simple options to a user, you can offer buttons that the user can click to confirm a
choice. A confirm dialog box that displays the options Yes, No, and Cancel can be created using
the showConfirmDialog() method in the JOptionPane class. Four versions of the method are
available; the simplest requires a parent component (which can be null) and the String prompt
that is displayed in the box. The showConfirmDialog() method returns an integer containing
one of three possible values: JOptionPane.YES_OPTION, JOptionPane.NO_OPTION, or JOption
Pane.CANCEL_OPTION. Figure 2-32 shows an application that uses a dialog box to ask a user a
question and to store the user’s response in the integer variable named selection.
Figure 2-31 Sample execution of the SalaryDialog application
import javax.swing.JOptionPane;
public class AirlineDialog
{
public static void main(String[] args)
{
int selection;
boolean isYes;
selection = JOptionPane.showConfirmDialog(null,
"Do you want to upgrade to first class?");
isYes = (selection == JOptionPane.YES_OPTION);
JOptionPane.showMessageDialog(null,
"You responded " + isYes);
}
}
Figure 2-32 The AirlineDialog class
97070_ch02_hr_049-109.indd 86 27/02/18 7:45 pm
87
Figure 2-33 shows the dialog box created by the program in Figure 2-32. After a value is
stored in selection, a Boolean variable named isYes is set to the result when selection
and JOptionPane.YES_OPTION are compared. If the user has selected the Yes button in
the dialog box, this variable is set to true; otherwise, the variable is set to false. Finally,
the true or false result is displayed; Figure 2-34 shows the result when a user clicks the Yes
button in the dialog box.
Figure 2-33 The confirm dialog box displayed
by the AirlineDialog application
Figure 2-34 Output of AirlineDialog
application when user clicks Yes
You can also create a confirm dialog box with five arguments, as follows:
• The parent component, which can be null
• The prompt message
• The title to be displayed in the title bar
• An integer that indicates which option button will be shown; it should be one of the
constants YES_NO_CANCEL_OPTION or YES_NO_OPTION
• An integer that describes the kind of dialog box; it should be one of the constants
ERROR_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE, or
WARNING_MESSAGE
For example, when the following statement is executed, it displays a confirm dialog box, as
shown in Figure 2-35:
JOptionPane.showConfirmDialog(null,
"A data input error has occurred. Continue?",
"Data input error", JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE);
Figure 2-35 Confirm dialog box with title, Yes and No buttons, and error icon
Using the JOptionPane Class to Accept GUI Input
97070_ch02_hr_049-109.indd 87 27/02/18 7:45 pm
88
Using DataC h a p t e r 2
performing arithmetic Using Variables and Constants
Table 2-8 describes the five standard arithmetic operators that you use to perform calcula-
tions with values in your programs. A value used on either side of an operator is an operand.
For example, in the expression 45 + 2, the numbers 45 and 2 are operands. The arithmetic
operators are examples of binary operators, so named because they require two operands.
Confirm dialog boxes provide more practical uses when your applications can make decisions based on the
users’ responses. In the chapter “Making Decisions,” you will learn how to make decisions within programs.
The false statement is #3. A confirm dialog box displays the options Yes, No, and
Cancel.
tWO trUthS & a LIe
Using the JOptionPane Class to Accept GUI Input
1. You can create an input dialog box using the showInputDialog() method;
the method returns a String that represents a user’s response.
2. You can use methods from the Java classes Integer and Double when you
want to convert a dialog box’s returned values to numbers.
3. A confirm dialog box can be created using the showConfirmDialog()
method in the JOptionPane class; a confirm dialog box displays the options
Accept, Reject, and Escape.
Watch the video Getting Input.
You will learn about the Java shortcut arithmetic operators in the chapter “Looping.”
The operators / and % deserve special consideration. Java supports two types of division:
• Floating-point division occurs when either or both of the operands are floating-point
values. For example, 45.0 / 2 is 22.5.
• Integer division occurs when both of the operands are integers. The result is an inte-
ger, and any fractional part of the result is lost. For example, the result of 45 / 2 is 22. As
another example, 39 / 5 is 7 because 5 goes into 39 seven whole times; 38 / 5, 37 / 5, 36 / 5,
and 35 / 5 all evaluate to 7.
97070_ch02_hr_049-109.indd 88 27/02/18 7:45 pm
89
Performing Arithmetic Using Variables and Constants
The percent sign is the remainder operator. The remainder operator is most often
used with two integers, and the result is an integer with the value of the remainder
after division takes place. For example, the result of 45 % 2 is 1 because 2 “goes into” 45
twenty-two times with a remainder of 1. Other examples of remainder operations include
the following:
• 39 % 5 is 4 because 5 goes into 39 seven times with a remainder of 4.
• 20 % 3 is 2 because when 20 is divided by 3, the remainder is 2.
• 36 % 4 is 0 because there is no remainder when 4 is divided into 36.
Note that when you perform paper-and-pencil division, you divide first to determine a
remainder. In Java, you do not need to perform a division operation before you can perform
a remainder operation. A remainder operation can stand alone.
Although the remainder operator is most often used with integers, it is legal but less often
useful to use the operator with floating-point values. In Java, when you use the % operator
with floating-point values, the result is the remainder from a rounded division.
The remainder operator is also called the modulus operator, or sometimes just mod. Mathematicians
would argue that remainder is the better term because in Java, the result of using the remainder
operator can be negative, but in mathematics, the result of a modulus operation can never be negative.
Operator Description example
+ Addition 45 + 2, the result is 47
– Subtraction 45 – 2, the result is 43
* Multiplication 45 * 2, the result is 90
/ Division 45.0 / 2, the result is 22.5
45 / 2, the result is 22 (not 22.5)
% Remainder (modulus) 45 % 2, the result is 1 (that is, 45/2 225 with a
remainder of 1)
table 2-8 Arithmetic operators
Associativity and Precedence
When you combine mathematical operations in a single statement, you must understand
both associativity and precedence. The associativity of arithmetic operators with the same
precedence is left to right. In a statement such as answer = x + y + z;, the x and y are
added first, producing a temporary result, and then z is added to the temporary sum. After
the sum is computed, the result is assigned to answer.
97070_ch02_hr_049-109.indd 89 27/02/18 7:45 pm
90
Using DataC h a p t e r 2
Operator precedence refers to the rules for the order in which parts of a mathematical
expression are evaluated. The multiplication, division, and remainder operators have the
same precedence, and it is higher than the precedence of the addition and subtraction
operators. In other words, an arithmetic expression is evaluated from left to right, and
any multiplication, division, and remainder operations take place. Then, the expression is
evaluated from left to right again, and any addition and subtraction operations execute.
Table 2-9 summarizes the precedence of the arithmetic operators.
You will learn more about operator precedence in the chapter “Making Decisions.”
Operators Descriptions relative precedence
* / % Multiplication, division, remainder Higher
+ – Addition, subtraction Lower
table 2-9 Relative precedence of arithmetic operators
For example, the following statement assigns 14 to result:
int result = 2 + 3 * 4;
The multiplication operation (3 * 4) occurs before adding 2. You can override normal
operator precedence by putting the operation to perform first in parentheses. The following
statement assigns 20 to result:
int result = (2 + 3) * 4;
The addition within the parentheses takes place first, and then the intermediate result (5) is
multiplied by 4. When multiple pairs of parentheses are used in a statement, the innermost
expression surrounded by parentheses is evaluated first. For example, the value of the
following expression is 46:
2 * (3 + (4 * 5))
First, 4 * 5 evaluates to 20, and then 3 is added, giving 23. Finally, the value is multiplied
by 2, giving 46.
Remembering that *, /, and % have the same precedence is important in arithmetic
calculations. These operations are performed from left to right, regardless of the order
in which they appear. For example, the value of the following expression is 9:
25 / 8 * 3
First, 25 is divided by 8. The result is 3 because with integer division, you lose any
remainder. Then 3 is multiplied by 3, giving 9. If you assumed that multiplication was
performed before division, you would calculate an incorrect answer.
97070_ch02_hr_049-109.indd 90 27/02/18 7:45 pm
91
Performing Arithmetic Using Variables and Constants
Writing Arithmetic Statements Efficiently
You can make your programs operate more efficiently if you avoid unnecessary repetition
of arithmetic statements. For example, suppose you know the values for an employee’s
hourly pay and pay rate and you want to compute state and federal withholding tax based
on known rates. You could write two statements as follows:
stateWithholding = hours * rate * STATE_RATE;
federalWithholding = hours * rate * FED_RATE;
With this approach, you perform the multiplication of hours * rate twice. It is more
efficient to perform the calculation once, as follows:
grossPay = hours * rate;
stateWithholding = grossPay * STATE_RATE;
federalWithholding = grossPay * FED_RATE;
The time saved is very small, but these savings would be more important if the calculation
was more complicated or if it was repeated many times in a program. As you think about
the programs you write, remain on the lookout for ways to improve efficiency by avoiding
duplication of operations.
Pitfall: Not Understanding Imprecision in Floating-Point
Numbers
Integer values are exact, but floating-point numbers frequently are only approximations.
For example, when you divide 1.0 by 3.0, the mathematical result is 0.3333333…, with the 3s
continuing infinitely. No matter how many decimal places you can store, the result is only
an approximation. Even values that don’t repeat indefinitely in our usual numbering system,
such as 0.1, cannot be represented precisely in the binary format used by computers.
Imprecision leads to several problems:
• When you produce floating-point output, it might not look like what you expect
or want.
• When you make comparisons with floating-point numbers, the comparisons might
not be what you expect or want.
Appendix B provides a more thorough explanation of numbering systems and why fractional values
cannot be represented accurately.
For example, Figure 2-36 shows a class in which an answer is computed as 2.20 – 2.00.
97070_ch02_hr_049-109.indd 91 27/02/18 7:45 pm
92
Using DataC h a p t e r 2
For now, you might choose to accept the slight imprecisions generated when you use
floating-point numbers. However, if you want to eliminate the imprecisions, you can use
one of several techniques to round values. Appendix C contains directions on how to round
numbers and how to format a floating-point number so it displays the desired number of
decimal positions.
public class ImprecisionDemo
{
public static void main(String[] args)
{
double answer = 2.20 - 2.00;
boolean isEqual = answer == 0.20;
System.out.println("answer is " + answer);
System.out.println("isEqual is " + isEqual);
}
}
Figure 2-36 The ImprecisionDemo program
Figure 2-37 Execution of the ImprecisionDemo
program
Watch the video Arithmetic.
Several movies have used the fact that floating-point numbers are not precise as a plot element. For
example, in the movies Superman III and Office Space, thieves round currency values and divert the
remaining fractions of cents to their own accounts.
Mathematically, the result in the program in Figure 2-36 should be 0.20. But, as the output
in Figure 2-37 shows, the result is calculated as a value that is slightly more than 0.20, and
when answer is compared to 0.20, the result is false.
97070_ch02_hr_049-109.indd 92 27/02/18 7:45 pm
93
Performing Arithmetic Using Variables and Constants
The false statement is #1. The arithmetic operators are examples of binary opera-
tors, which are so named because they require two operands.
tWO trUthS & a LIe
Performing Arithmetic Using Variables and Constants
1. The arithmetic operators are examples of unary operators, which are so
named because they perform one operation at a time.
2. In Java, operator precedence dictates that multiplication, division, and
remainder always take place prior to addition or subtraction in an expression.
3. Floating-point arithmetic might produce imprecise results.
Using Arithmetic Operators
In these steps, you create a program that uses arithmetic operators.
1. Open a new file in your text editor, and type the import statement needed for
interactive input with the Scanner class:
import java.util.Scanner;
2. Type the class header and its curly braces for a class named ArithmeticDemo.
Within the class’s curly braces, enter the main() method header and its braces.
public class ArithmeticDemo
{
public static void main(String[] args)
{
}
}
3. Within the main() method, declare five int variables that will be used to hold
two input values and their sum, difference, and average:
int firstNumber;
int secondNumber;
int sum;
int difference;
int average;
You Do It
(continues)
97070_ch02_hr_049-109.indd 93 27/02/18 7:45 pm
94
Using DataC h a p t e r 2
4. Also declare a Scanner object so that keyboard input can be accepted.
Scanner input = new Scanner(System.in);
5. Prompt the user for and accept two integers:
System.out.print("Please enter an integer >> ");
firstNumber = input.nextInt();
System.out.print("Please enter another integer >> ");
secondNumber = input.nextInt();
6. Add statements to perform the necessary arithmetic operations:
sum = firstNumber + secondNumber;
difference = firstNumber - secondNumber;
average = sum / 2;
7. Display the three calculated values:
System.out.println(firstNumber + " + " +
secondNumber + " is " + sum);
System.out.println(firstNumber + " - " +
secondNumber + " is " + difference);
System.out.println("The average of " + firstNumber +
" and " + secondNumber + " is " + average);
8. Save the file as arithmeticDemo.java, and then compile and execute it.
Enter values of your choice. Figure 2-38 shows a typical execution. Notice that
because integer division was used to compute the average, the answer is an
integer.
9. Execute the program multiple times using various integer values, and confirm
that the results are accurate.
(continues)
(continued)
Figure 2-38 Typical execution of ArithmeticDemo
application
97070_ch02_hr_049-109.indd 94 27/02/18 7:45 pm
95
Performing Arithmetic Using Variables and Constants
Performing Floating-Point Arithmetic
Next, you will modify the ArithmeticDemo application to work with floating-point
values instead of integers.
1. Within the ArithmeticDemo application, change the class name to Arithmetic
Demo2, and immediately save the file as arithmeticDemo2.java. Change all
the variables’ data types to double. Change the two prompts to request double
values, and change the two calls to the nextInt() method to nextDouble().
Save, compile, and execute the program again. Figure 2-39 shows a typical
execution. Notice that the average calculation now includes decimal places.
2. Rerun the program, experimenting with various input values. Some of your
output might appear with imprecisions similar to those shown in Figure 2-40.
If you are not satisfied with the slight imprecisions created when using floating-
point arithmetic, you can round or change the display of the values, as
discussed in Appendix C.
(continued)
Figure 2-39 Typical execution of the
ArithmeticDemo2 application
Figure 2-40 Another typical execution of the
ArithmeticDemo2 application
97070_ch02_hr_049-109.indd 95 27/02/18 7:45 pm
96
Using DataC h a p t e r 2
Understanding type Conversion
When you perform arithmetic with variables or constants of the same type, the result of the
operation retains the same type. For example, when you divide two ints, the result is an int,
and when you subtract two doubles, the result is a double. Often, however, you might want to
perform mathematical operations on operands with unlike types. The process of converting one
data type to another is type conversion. Java performs some conversions for you automatically
or implicitly, but other conversions must be requested explicitly by the programmer.
Automatic Type Conversion
When you perform arithmetic operations with operands of unlike types, Java chooses
a unifying type for the result. The unifying type is the type to which all operands in an
expression are converted so that they are compatible with each other. Java performs an
implicit conversion; that is, it automatically converts nonconforming operands to the
unifying type. Implicit conversions also are called promotions. Figure 2-41 shows the
order for establishing unifying types between values.
Boolean values cannot be converted to another type. In some languages, such as C++, Boolean values
are actually numbers. However, this is not the case in Java.
When two unlike types are used in an expression, the unifying type is the one that is higher
in the list in Figure 2-41. In other words, when an operand that is a type lower on the list is
combined with a type that is higher, the lower-type operand is converted to the higher one.
For example, the addition of a double and an int results in a double, and the subtraction of
a long from a float results in a float.
Figure 2-41 Order for establishing unifying data types
double Highest
float
long
int Lowest
(short and byte are automatically converted to int when used in
expressions.)
For example, assume that an int, hoursWorked, and a double, payRate, are defined and
then multiplied as follows:
int hoursWorked = 37;
double payRate = 16.73;
double grossPay = hoursWorked * payRate;
97070_ch02_hr_049-109.indd 96 27/02/18 7:45 pm
97
Understanding Type Conversion
The result of the multiplication is a double because when a double and an int are
multiplied, the int is promoted to the higher-ranking unifying type double—the type that
is higher in the list in Figure 2-41. Therefore, assigning the result to grossPay is legal.
The following code will not compile because hoursWorked times payRate is a double, and
Java does not allow the loss of precision that occurs if you try to store the calculated double
result in an int.
int hoursWorked = 37;
double payRate = 16.73;
int grossPay = hoursWorked * payRate;
The data types char, short, and byte all are promoted to int when used in statements with
unlike types. If you perform a calculation with any combination of char, short, and byte
values, the result is an int by default. For example, if you add two bytes, the result is an
int, not a byte.
Explicit Type Conversions
You can purposely override the unifying type imposed by Java by performing a type cast.
type casting forces a value of one data type to be used as a value of another type. To
perform a type cast, you use a cast operator, which is created by placing the desired result
type in parentheses. Using a cast operator is an explicit conversion. The cast operator is
followed by the variable or constant to be cast. For example, a type cast is performed in the
following code:
double bankBalance = 189.66;
float weeklyBudget = (float) (bankBalance / 4);
// weeklyBudget is 47.415, one-fourth of bankBalance
The cast operator is more completely called the unary cast operator. Unlike a binary operator that
requires two operands, a unary operator uses only one operand. The unary cast operator is followed
by its operand.
In this example, the double value bankBalance is divided by the integer 4, and the
result is a double. Then, the double result is converted to a float before it is stored
in weeklyBudget. Without the conversion, the statement that assigns the result to
weeklyBudget would not compile. Similarly, a cast from a float to an int occurs in
this code segment:
float myMoney = 47.82f;
int dollars = (int) myMoney;
// dollars is 47, the integer part of myMoney
In this example, the float value myMoney is converted to an int before it is stored in the
integer variable named dollars. When the float value is converted to an int, the decimal
place values are lost. The cast operator does not permanently alter any variable’s data type;
97070_ch02_hr_049-109.indd 97 27/02/18 7:45 pm
98
Using DataC h a p t e r 2
It is easy to lose data when performing a cast. For example, the largest byte value is 127 and the
largest int value is 2,147,483,647, so the following statements produce distorted results:
int anOkayInt 5 200;
byte aBadByte 5 (byte)anOkayInt;
A byte is constructed from eight 1s and 0s, or binary digits. The first binary digit, or bit, holds a 0 or 1
to represent positive or negative. The remaining seven bits store the actual value. When the integer value
200 is stored in the byte variable, its large value consumes the eighth bit, turning it to a 1, and forcing
the aBadByte variable to appear to hold the value –72, which is inaccurate and misleading.
the alteration is only for the duration of the current operation. In other words, if myMoney
was used again in the previous example, it would still be a float and its value would still
be 47.82.
The false statement is #1. When you perform arithmetic operations with operands
of unlike types, Java performs an implicit conversion to a unifying type.
tWO trUthS & a LIe
Understanding Type Conversion
1. When you perform arithmetic operations with operands of unlike types, you
must make an explicit conversion to a unifying type.
2. Summing a double, int, and float results in a double.
3. You can explicitly override the unifying type imposed by Java by performing a
type cast; type casting forces a value of one data type to be used as a value
of another type.
You do not need to perform a cast when assigning a value to a higher unifying type. For
example, when you write a statement such as the following, Java automatically promotes
the integer constant 10 to be a double so that it can be stored in the payRate variable:
double payRate = 10;
However, for clarity, if you want to assign 10 to payRate, you might prefer to write the
following:
double payRate = 10.0;
The result is identical whether you assign the literal double 10.0 or the literal int 10 to the
double variable.
The word cast is used in a similar fashion when referring to molding metal, as in cast iron. In a Java
arithmetic cast, a value is “molded” into a different type.
97070_ch02_hr_049-109.indd 98 27/02/18 7:45 pm
99
Understanding Type Conversion
Implicit and Explicit Casting
In this section, you explore the concepts of the unifying types and casting.
1. Open the arithmeticDemo.java file that uses integer values to calculate a sum,
difference, and average. Change the class name to ArithmeticDemo3, and
immediately save the file as arithmeticDemo3.java.
2. In the previous version of the program, the average was calculated without
decimal places because when two integers are divided, the result is an integer.
To compute a more accurate average, change the data type for the average
variable from int to double.
3. Save, compile, and execute the program. As the sample execution in
Figure 2-42 shows, the program compiles and executes, but the average is
still not accurate. The average of 20 and 19 is calculated to be just 19.0
because when two integers are divided, the decimal portion of the arithmetic
result is lost.
4. Change the statement that computes the average to include a cast as
follows:
average = (double) sum / 2;
5. Save, compile, and execute the program. As shown in Figure 2-43, now the
program displays a more accurate average. The integer sum has been cast to a
double, and when the double is divided by the integer, the result is a double,
which is then assigned to average.
You Do It
(continues)
Figure 2-42 Typical execution of ArithmeticDemo3
application
97070_ch02_hr_049-109.indd 99 27/02/18 7:45 pm
100
Using DataC h a p t e r 2
6. Change the statement that computes the average to include a second set of
parentheses, as follows:
average = (double) (sum / 2);
7. Save, compile, and execute the program. Now, the fractional portion of the
result is omitted again. That’s because the result of sum / 2 is calculated first,
and the result is an integer. Then, the whole-number result is cast to a double
and assigned to a double—but the fractional part of the answer was already
lost and casting is too late. Remove the newly added parentheses, save the
program, compile it, and execute it again to confirm that the fractional part of
the answer is reinstated.
8. As an alternative to the explicit cast in the division statement in the
ArithmeticDemo program, you could write the average calculation as follows:
average = sum / 2.0;
In this calculation, when the integer sum is divided by the double constant 2.0,
the result is a double. The result then does not require any cast to be assigned
to the double average without loss of data. Try this in your program.
9. Go to the Java website (www.oracle.com/technetwork/java/index.html),
select Java apIs, and then select Java Se 9. Scroll through the list of all
Classes, and select printStream, which is the data type for the out object
used with the println() method. Scroll down to view the list of methods
in the Method Summary. As you did in a previous exercise, notice the many
versions of the print() and println() methods, including ones that accept a
String, an int, and a long. Notice, however, that no versions accept a byte
or a short. That’s because when a byte or short is sent to the print() or
println() method, it is automatically promoted to an int, so that version of
the method is used.
(continued)
Figure 2-43 Typical execution of ArithmeticDemo3
application after addition of a cast operation for the average
97070_ch02_hr_049-109.indd 100 27/02/18 7:45 pm
101
Don’t Do It
Don’t Do It
• Don’t mispronounce integer. People who are unfamiliar with the term often say
“interger,” inserting an extra r.
• Don’t attempt to assign a literal constant floating-point number, such as 2.5, to a float
without following the constant with an uppercase or lowercase F. By default, constant
floating-point values are doubles.
• Don’t try to use a Java keyword as an identifier for a variable or constant. Table 1-1 in
Chapter 1 contains a list of Java keywords.
• Don’t attempt to assign a constant value less than –2,147,483,648 or greater than
+2,147,483,647 to a long variable without following the constant with an uppercase or
lowercase L. By default, constant integers are ints, and a value less than –2,147,483,648
or greater than 2,147,483,647 is too large to be an int.
• Don’t assume that you must divide numbers as a step to determining a remainder; the
remainder operator ( % ) is all that’s needed.
• Don’t try to use a variable or named constant that has not yet been assigned a value.
• Don’t forget to consume the Enter key after numeric input using the Scanner class when
a nextLine() method call follows.
• Don’t forget to use the appropriate import statement when using the Scanner or
JOptionPane class.
• Don’t forget precedence rules when you write statements that contain multiple
arithmetic operations. For example, score1 + score2 / 2 does not compute the
average of two scores. Instead, it adds half of score2 to score1. To compute the
average, you would write (score1 + score2) / 2.
• Don’t forget that integer division results in an integer, dropping any fractional part.
For example, 1/2 is not equal to 0.5; it is equal to 0.
• Don’t forget that extra parentheses can change the result of an operation that includes casting.
• Don’t forget that floating-point numbers are imprecise.
• Don’t attempt to assign a constant decimal value to an integer using a leading 0. For
example, if you declare int num = 021; and then display num, you will see 17. The
leading 0 indicates that the value is in base 8 (octal), so its value is two 8s plus one 1. In
the decimal system, 21 and 021 mean the same thing, but not in Java.
• Don’t use a single equal sign ( 5 ) in a Boolean comparison for equality. The operator
used for equivalency is composed of two equal signs ( 55 ).
• Don’t try to store a string of characters, such as a name, in a char variable. A char
variable can hold only a single character.
• Don’t forget that when a String and a numeric value are concatenated, the resulting
expression is a string. For example, “X” + 2 + 4 results in “X24”, not “X6”. If you want
the result to be “X6”, you can use the expression “X” + (2 + 4).
97070_ch02_hr_049-109.indd 101 27/02/18 7:45 pm
102
Using DataC h a p t e r 2
constant
literal constant
numeric constant
unnamed constant
variable
data type
primitive type
reference types
variable declaration
strongly typed language
camel casing
assignment operator
initialization
assignment
associativity
lvalue
rvalue
uninitialized variable
garbage value
named constant
symbolic constant
final
blank final
magic number
scope
block of code
concatenated
null String
integer
int
byte
short
long
lossy conversion
lossless conversion
Boolean
relational operator
comparison operator
floating-point
float
double
significant digits
scientific notation
double-precision floating-
point number
single-precision floating-
point number
char
String
escape sequence
standard input device
token
prompt
keyboard buffer
type-ahead buffer
input dialog box
type-wrapper classes
parse
confirm dialog box
standard arithmetic
operators
operand
binary operators
floating-point division
integer division
remainder operator
modulus operator
(mod)
operator precedence
type conversion
unifying type
implicit conversion
promotion
type casting
cast operator
explicit conversion
unary cast operator
unary operator
Key terms
Chapter Summary
• Variables are named memory locations in which programs store values; the value of
a variable can change. You must declare all variables you want to use in a program
by providing a data type and a name. Java provides for eight primitive types of data:
boolean, byte, char, double, float, int, long, and short. A named constant is a
memory location that holds a value that cannot be changed after it is assigned; it is
preceded by the keyword final.
• A variable of type int can hold any whole number value from –2,147,483,648 to
+2,147,483,647. The types byte, short, and long are all variations of the integer type.
• A boolean type variable can hold a true or false value. Java supports six relational
operators: ., ,, 55, .5, ,5, and !5.
97070_ch02_hr_049-109.indd 102 27/02/18 7:45 pm
103
Chapter Summary
• A floating-point number contains decimal positions. Java supports two floating-point
data types: float and double.
• You use the char data type to hold any single character. You type constant character
values between single quotation marks and String constants between double quotation
marks. You can store some characters using an escape sequence, which always begins
with a backslash.
• You can use the Scanner class and the System.in object to accept user input from
the keyboard. Several methods are available to convert input to usable data, including
nextDouble(), nextInt(), and nextLine().
• You can accept input using the JOptionPane class. The showInputDialog() method
returns a String, which must be converted to a number using a type-wrapper class
before you can use it as a numeric value.
• There are five standard arithmetic operators: +, –, *, /, and %. Operator precedence is
the order in which parts of a mathematical expression are evaluated. Multiplication,
division, and remainder always take place prior to addition or subtraction in an
expression, but parentheses can be added to an expression to change precedence.
When you perform mathematical operations on unlike types, Java implicitly converts
the variables to a unifying type. You can perform a type cast to explicitly override the
unifying type imposed by Java.
Review Questions
1. When data cannot be changed after a class is compiled, the data is _____________.
a. variable
b. constant
c. volatile
d. mutable
2. Which of the following is not a primitive data type in Java?
a. boolean
b. byte
c. sector
d. int
3. Which of the following elements is not required in a variable declaration?
a. a type
b. an identifier
c. an assigned value
d. a semicolon
4. The assignment operator in Java is _____________.
a. 5
b. 55
c. :5
d. ::
97070_ch02_hr_049-109.indd 103 27/02/18 7:45 pm
104
Using DataC h a p t e r 2
5. Assuming you have declared shoeSize to be a variable of type int, which of the
following is a valid assignment statement in Java?
a. shoeSize = 9;
b. shoeSize = 9.5;
c. shoeSize = ”nine”;
d. Two of the above are valid.
6. Which of the following data types can store the value 0 using the least amount of
memory?
a. short
b. long
c. int
d. byte
7. A boolean variable can hold _____________.
a. any character
b. any whole number
c. any decimal number
d. the value true or false
8. The value 137.68 can be held by a variable of type _____________.
a. int
b. float
c. double
d. Two of these are correct.
9. An escape sequence always begins with a(n) _____________.
a. e
b. forward slash
c. backslash
d. equal sign
10. Which Java statement produces w on one line and xyz on the next line?
a. System.out.println(“wxyz”);
b. System.out.println(“w” + “xyz”);
c. System.out.println(“w\nxyz”);
d. System.out.println(“w\nx\ny\nz”);
11. The remainder operator _____________.
a. is represented by a forward slash
b. must follow a division operation
c. provides the quotient of integer division
d. is none of the above
12. According to the rules of operator precedence, when division occurs in the same
arithmetic statement as _____________, the division operation always takes place
first.
a. multiplication
b. remainder
c. subtraction
d. Answers a and b are correct.
13. The equal to relational operator is _____________.
a. 5
b. 55
c. !5
d. !!
97070_ch02_hr_049-109.indd 104 27/02/18 7:45 pm
105
Exercises
14. When you perform arithmetic with values of diverse types, Java _____________.
a. issues an error message
b. implicitly converts the values to a unifying type
c. requires you to explicitly convert the values to a unifying type
d. implicitly converts the values to the type of the first operand
15. If you attempt to add a float, an int, and a byte, the result will be a(n) _____________.
a. float
b. int
c. byte
d. error message
16. You use a _____________ to explicitly override an implicit type.
a. mistake
b. type cast
c. format
d. type set
17. In Java, what is the value of 3 + 7 * 4 + 2?
a. 21
b. 33
c. 42
d. 48
18. Which assignment is correct in Java?
a. int value = (float) 4.5;
b. float value = 4 (double);
c. double value = 2.12;
d. char value = 5c;
19. Which assignment is correct in Java?
a. double money = 12;
b. double money = 12.0;
c. double money = 12.0d;
d. All of the above are correct.
20. Which assignment is correct in Java?
a. char aChar = 5.5;
b. char aChar = “W”;
c. char aChar = '*';
d. Two of these are correct.
exercises
Programming Exercises
1. What is the numeric value of each of the following expressions as evaluated by
Java?
a. 4 + 6 * 2
b. 10 / 5 + 8
c. 12 / 4 + 16 / 2
d. 17 / 2
e. 22 / 5
f. 39 / 10
g. 19 % (2 + 3)
h. 3 + 4 * 20 / 3
i. 36 % (6 + 2)
j. 8 % 2 * 0
97070_ch02_hr_049-109.indd 105 27/02/18 7:45 pm
106
Using DataC h a p t e r 2
2. What is the value of each of the following Boolean expressions?
a. 15 , 13
b. 8 ,5 (2 + 6)
c. 15 55 15
d. 3 .5 3
e. 4 * 2 55 2 * 4
f. 5 , 8 – 3
g. 7 !5 7
h. 8 !5 (2 + 5)
i. 10 – 20 55 –10
j. 3 + 2 * 6 55 30
3. Choose the best data type for each of the following so that any reasonable
value is accommodated but no memory storage is wasted. Give an example of a
typical value that would be held by the variable, and explain why you chose the
type you did.
a. the number of siblings you have
b. your final grade in this class
c. the population of Earth
d. the population of a U.S. county
e. the number of passengers on a bus
f. one player’s score in a Scrabble game
g. one team’s score in a Major League Baseball game
h. the year an historical event occurred
i. the number of legs on an animal
j. the price of an automobile
4. Write a program that declares a named constant to hold the number of quarts in
a gallon (4). Also declare a variable to represent the number of quarts needed for
a painting job, and assign an appropriate value—for example, 18. Compute and
display the number of gallons and quarts needed for the job. Display explanatory
text with the values—for example, A job that needs 18 quarts requires 4 gallons
plus 2 quarts. Save the program as QuartsToGallons.java.
5. Convert the QuartsToGallons program to an interactive application. Instead
of assigning a value to the number of quarts, accept the value from the user as
input. Save the revised program as QuartsToGallonsInteractive.java.
6. Write a program that declares named constants to represent the number of
inches, feet, and yards in a mile. Also declare a variable to represent a number
of miles and assign a value to it. Compute and display, with explanatory text, the
value in inches, feet, and yards. Save the program as MileConversions.java.
7. Convert the MileConversions program to an interactive application. Instead of
assigning a value to the miles variable, accept it from the user as input. Save the
revised program as MileConversionsInteractive.java.
97070_ch02_hr_049-109.indd 106 27/02/18 7:45 pm
107
Exercises
8. Write a program that declares a variable named inches, which holds a length
in inches, and assign a value. Display the value in feet and inches; for example,
86 inches becomes 7 feet and 2 inches. Be sure to use a named constant where
appropriate. Save the program as InchesToFeet.java.
9. Write an interactive version of the InchesToFeet class that accepts the inches
value from a user. Save the class as InchesToFeetInteractive.java.
10. Write a program that declares variables to hold your three initials. Display the
three initials with a period following each one, as in J.M.F. Save the program as
Initials.java.
11. Meadowdale Dairy Farm sells organic brown eggs to local customers. It charges
$3.25 for a dozen eggs, or 45 cents for individual eggs that are not part of a
dozen. Write a program that prompts a user for the number of eggs in the
order and then display the amount owed with a full explanation. For example,
typical output might be, You ordered 27 eggs. That’s 2 dozen at $3.25 per
dozen and 3 loose eggs at 45 cents each for a total of $7.85. Save the program
as Eggs.java.
12. The Huntington Boys and Girls Club is conducting a fundraiser by selling chili
dinners to go. The price is $7 for an adult meal and $4 for a child’s meal. Write a
program that accepts the number of each type of meal ordered and display the
total money collected for adult meals, children’s meals, and all meals. Save the
program as ChiliToGo.java.
13. In the ChiliToGo program in Exercise 12, the costs to produce an adult meal and
a child’s meal are $4.35 and $3.10, respectively. Modify the ChiliToGo program to
display the total profit for each type of meal as well as the grand total profit. Save
the program as ChiliToGoProfit.java.
14. Write a program that calculates and displays the conversion of an entered number
of dollars into currency denominations—20s, 10s, 5s, and 1s. Save the program as
Dollars.java.
15. Write a program that accepts a number of minutes and converts it both to hours
and days. For example, 6,000 minutes equals 100 hours and equals 4.167 days.
Save the program as MinutesConversion.java.
16. Write a program that accepts the names of three political parties and the number
of votes each received in the last mayoral election. Display the percentage of the
vote each party received. Save the program as ElectionStatistics.java.
97070_ch02_hr_049-109.indd 107 27/02/18 7:45 pm
108
Using DataC h a p t e r 2
Debugging Exercises
1. Each of the following files in the Chapter02 folder of your downloadable student
files has syntax and/or logic errors. In each case, determine the problem
and fix the application. After you correct the errors, save each file using the
same filename preceded with Fix. For example, DebugTwo1.java will become
FixDebugTwo1.java.
a. DebugTwo1.java
b. DebugTwo2.java
c. DebugTwo3.java
d. DebugTwo4.java
Game Zone
1. Mad Libs is a children’s game in which they provide a few words that are then
incorporated into a silly story. The game helps children understand different
parts of speech because they are asked to provide specific types of words. For
example, you might ask a child for a noun, another noun, an adjective, and a
past-tense verb. The child might reply with such answers as table, book, silly,
and studied. The newly created Mad Lib might be:
Mary had a little table
Its book was silly as snow
And everywhere that Mary studied
The table was sure to go.
2. Create a Mad Libs program that asks the user to provide at least four or five
words, and then create and display a short story or nursery rhyme that uses them.
Save the file as MadLib.java.
When you change a filename, remember to change every instance of the class name within the file so
that it matches the new filename. In Java, the filename and class name must always match.
97070_ch02_hr_049-109.indd 108 27/02/18 7:45 pm
109
Exercises
Case Problems
1. Carly’s Catering provides meals for parties and special events. Write a program
that prompts the user for the number of guests attending an event and then
computes the total price, which is $35 per person. Display the company motto
with the border that you created in the CarlysMotto2 class in Chapter 1,
and then display the number of guests, price per guest, and total price. Also
display a message that indicates true or false depending on whether the job
is classified as a large event—an event with 50 or more guests. Save the file as
CarlysEventPrice.java.
2. Sammy’s Seashore Supplies rents beach equipment such as kayaks, canoes, beach
chairs, and umbrellas to tourists. Write a program that prompts the user for the
number of minutes he rented a piece of sports equipment. Compute the rental
cost as $40 per hour plus $1 per additional minute. (You might have surmised
already that this rate has a logical flaw, but for now, calculate rates as described
here. You can fix the problem after you read the chapter on decision making.)
Display Sammy’s motto with the border that you created in the SammysMotto2
class in Chapter 1. Then display the hours, minutes, and total price. Save the file
as SammysRentalPrice.java.
3. In the “Game Zone” section in Chapter 1, you learned how to obtain a random
number. For example, the following statement generates a random number
between the constants MIN and MAX inclusive and assigns it to a variable named
random:
random = MIN + (int)(Math.random() * MAX);
Write a program that selects a random number between 1 and 5 and asks
the user to guess the number. Display a message that indicates the difference
between the random number and the user’s guess. Display another message that
displays the random number and the Boolean value true or false depending
on whether the user’s guess equals the random number. Save the file as
RandomGuessMatch.java.
97070_ch02_hr_049-109.indd 109 27/02/18 7:45 pm
C h a p t e r 3
Using Methods,
Classes, and Objects
Upon completion of this chapter, you will be able to:
Describe method calls and placement
Identify the parts of a method
Add parameters to methods
Create methods that return values
Describe classes and objects
Create a class
Create instance methods in a class
Declare objects and use their methods
Create constructors
Appreciate classes as data types
97070_ch03_hr_110-169.indd 110 24/02/18 3:52 pm
111
Understanding Method Calls and Placement
Instead of adding the three println() statements to the application in Figure 3-1, you
might prefer to call a method that executes the three statements. Then the program would
look like the one in Figure 3-2 that calls the displayAddress() method.
Understanding Method Calls and placement
A method is a program module that contains a series of statements that carry out a task. You
have already seen Java classes that contain a main() method, which executes automatically
when you run a program. A program’s main() method can execute additional methods, and
those methods can execute others. Any class can contain an unlimited number of methods,
and each method can be called an unlimited number of times.
To execute a method, you invoke or call it. In other words, a calling method (also known
as a client method) invokes a called method.
Consider the simple First class that you saw in Chapter 1; it displayed a single line of
output, First Java application. Suppose that you want to add three lines of output to this
application to display your company’s name and address. One approach would be to simply
add three new println() statements, as shown in Figure 3-1.
public class First
{
public static void main(String[] args)
{
System.out.println("XYZ Company");
System.out.println("8900 U.S. Hwy 14");
System.out.println("Crystal Lake, IL 60014");
System.out.println("First Java application");
}
}
Figure 3-1 The First class
public class First
{
public static void main(String[] args)
{
displayAddress();
System.out.println("First Java application");
}
}
Figure 3-2 The First class with a call to the displayAddress() method
97070_ch03_hr_110-169.indd 111 24/02/18 3:52 pm
112
Using Methods, Classes, and ObjectsC h a p t e r 3
The order in which methods appear in a class has no bearing on the order in which the
methods are called or execute. No matter where you place it, the main() method is always
executed first in any Java application, and it might call any other methods in any order and
any number of times. The order in which you call methods, not their physical placement, is
what makes a difference in how an application executes.
A main() method executes automatically when you run a program, but other methods do
not execute simply because you place them within a class—they must be called. A class
might contain methods that are never called from a particular application, just as some
electronic devices might contain features you never use. For example, you might use a DVR
to play movies but never to record TV programs, or you might use your microwave oven
for popcorn but never to defrost.
Figure 3-4 shows the First class with two methods: the main() method and the
displayAddress() method, which is placed after main() in this example.
There are two major advantages to creating a separate method to display the three address
lines:
• By including a method call, the main() method remains short and easy to follow
because it does not contain the three separate println() statements.
• A method is easily reusable. After you create the displayAddress() method, you can
use it in any application that needs the company’s name and address. In other words,
you do the work once, and then you can use the method many times.
Besides adding a call to the method in the First class, you must actually write the method.
You place a method within a class, but it must be outside of any other methods. In other
words, you cannot place a method within another method. Figure 3-3 shows the two
locations where you can place additional methods within the First class—within the curly
braces of the class, but outside of (either before or after) any other methods. Methods can
never overlap.
public class First
{
// You can place additional methods here, before main()
public static void main(String[] args)
{
displayAddress();
System.out.println("First Java application");
}
// You can place additional methods here, after main()
}
Figure 3-3 Placement of methods within a class
97070_ch03_hr_110-169.indd 112 24/02/18 3:52 pm
113
Understanding Method Calls and Placement
Using a method name to contain or encapsulate a series of statements is an example of the feature that
programmers call abstraction. Consider abstract art, in which the artist tries to capture the essence of
an object without focusing on the details. Similarly, when programmers employ abstraction, they use a
general method name in a module rather than list all the detailed activities that will be carried out by the
method.
Figure 3-4 First class with main() calling displayAddress()
public class First
{
public static void main(String[] args)
{
displayAddress();
System.out.println("First Java application");
}
public static void displayAddress()
{
System.out.println("XYZ Company");
System.out.println("8900 U.S. Hwy 14");
System.out.println("Crystal Lake, IL 60014");
}
}
The main() method in
this class contains two
statements. The first
one is a call to the
displayAddress()
method.
Figure 3-5 shows the output from the execution of the program in Figure 3-4. The main()
method first calls the displayAddress() method, which displays three lines of output.
Then main() displays the phrase First Java application.
Figure 3-5 Output of the First application, including
the displayAddress() method
The main() method in Figure 3-4 calls a method that resides in its own class. Later in this chapter, you
will learn how to call a method that resides in a different class.
Watch the video Methods.
97070_ch03_hr_110-169.indd 113 24/02/18 3:52 pm
114
Using Methods, Classes, and ObjectsC h a p t e r 3
Understanding Method Construction
Every method must include the two parts featured in Figure 3-6:
• A method header—A method’s header provides information about how other methods
can interact with it. A method header is also called a declaration.
• A method body between a pair of curly braces—The method body contains the state-
ments that carry out the work of the method. In Figure 3-6, the main() method contains
two statements, and the displayAddress() method body contains three statements.
A method’s body is called its implementation. Technically, a method is not required to
contain any statements in its body, but you usually would have no reason to create an
empty method in a class. (Sometimes, while developing a program, the programmer
creates an empty method as a placeholder and fills in the implementation later.
An empty method is called a stub.)
The false statement is #3. A method is written within a class, but not within any
other methods.
tWO trUthS & a LIe
Understanding Method Calls and Placement
1. Any class can contain an unlimited number of methods.
2. During one program execution, a method might be called any number
of times.
3. A method is usually written within another method.
Figure 3-6 The headers and bodies of the methods in the First class
public class First
{
public static void main(String[] args)
{
displayAddress();
System.out.println("First Java application");
}
public static void displayAddress()
{
System.out.println("XYZ Company");
System.out.println("8900 U.S. Hwy 14");
System.out.println("Crystal Lake, IL 60014");
}
}
Method
headers
Method
bodies
97070_ch03_hr_110-169.indd 114 24/02/18 3:52 pm
115
Understanding Method Construction
In addition, any method that can be used without instantiating an object requires the
keyword modifier static. The main() method in an application must use the keyword
static, but other methods, like displayAddress(), can use it too. You will learn about
nonstatic methods later in this chapter.
The method header is the first line of a method. It contains the following:
• Optional access specifiers
• A return type
• An identifier
• Parentheses
The next few figures compare these parts of a method header for the main() method and
the displayAddress() method in the First class.
Access Specifiers
Figure 3-7 highlights the optional access specifiers for the two methods in the First class.
The access specifier for a Java method can be any of the following modifiers: public,
private, protected, or, if left unspecified, package by default. Most often, methods are
given public access; this book will cover the other modifiers later. Endowing a method
with public access means that any other class can use it, not just the class in which the
method resides.
You first learned the term access specifier in Chapter 1. Access specifiers are sometimes called access
modifiers.
Figure 3-7 Access specifiers for two methods
public static void displayAddress()
public static void main(String[] args)
The main() method in an application
must specify public access.
The displayAddress() method
is not required to specify public
access. However, if access is
public, the method can be used
by other, outside classes.
The static modifier means that
these methods do not require an
object to be created.
97070_ch03_hr_110-169.indd 115 24/02/18 3:52 pm
116
Using Methods, Classes, and ObjectsC h a p t e r 3
Method Name
Figure 3-9 highlights the names of the two methods in the First class. A method’s name can
be any legal identifier. That is, like identifiers for classes and variables, a method’s identifier
must be one word with no embedded spaces, and cannot be a Java keyword. The method
that executes first when you run an application must be named main(), but you have a lot of
leeway in naming other methods that you create. Technically, you could even name another
method main() as long as you did not include String[] within the parentheses, but doing
so would be confusing and is not recommended. Because methods “do” something—that is,
perform an action—their names frequently contain a verb, such as print or compute.
Return Type
Figure 3-8 features the return types for the main() and displayAddress() methods in the
First class. A return type describes the type of data the method sends back to its calling
method. Not all methods return a value to their calling methods; a method that returns
no data has a return type of void. The main() method in an application must have a
return type of void; in this example, displayAddress() also has a void return type. Other
methods that you will see later in this chapter have different return types. The phrases void
method and method of type void both refer to a method that has a void return type.
Figure 3-8 Return types for two methods
public static void displayAddress()
public static void main(String[] args)
The main() method in an application must
have a void return type.
The displayAddress() method does not send any information
back to the method that calls it, so its return type is void. Later in
this chapter you will write methods with other return types.
Figure 3-9 Identifiers for two methods
public static void displayAddress()
public static void main(String[] args)
The method that executes first when you run
an application must be named main().
Other methods you write in a class
can have any legal identifier.
97070_ch03_hr_110-169.indd 116 24/02/18 3:52 pm
117
Understanding Method Construction
The full name of the displayAddress() method is First.displayAddress(), which
includes the class name (First), a dot, and the method name, which is displayAddress().
(The name does not include an object because displayAddress() is a static method.)
A complete name that includes the class is a fully-qualified identifier. When you use a
method within its own class, you do not need to use the fully qualified name (although you
can); the simple method name alone is enough. However, if you want to use a method in
another class, the compiler does not recognize the method unless you use the full name.
You have used similar syntax (including a class name, dot, and method name) when calling
the JOptionPane.showMessageDialog() method.
Each of two different classes can have its own method named displayAddress(). Such a
method in the second class would be entirely distinct from the identically named method
in the first class. You could use both methods in a third class by using their fully qualified
identifiers. Two classes in an application cannot have the same name.
Parentheses
As Figure 3-10 shows, every method header contains a set of parentheses that follow the
identifier. The parentheses might contain data to be sent to the method. For example,
when you write a main() method in a class, the parentheses in its header surround
String[] args. The displayAddress() method in the First class requires no outside
data, so its parentheses are empty. Later in this chapter, you will see several methods that
accept data.
Figure 3-10 Parentheses and their contents for two methods
public static void displayAddress()
public static void main(String[] args)
The main() method in an application must contain String[]
and an identifier (args is traditional) within its parentheses.
Other methods you write might accept data
within their parentheses, but
displayAddress()does not.
Think of the class name as the family name. Within your own family, you might refer to an activity as the
family reunion, but outside the family people need to use a surname as well, as in the Anderson family
reunion. Similarly, a method name alone is sufficient within a class, but outside the class you need to use
the fully qualified name.
97070_ch03_hr_110-169.indd 117 24/02/18 3:52 pm
118
Using Methods, Classes, and ObjectsC h a p t e r 3
The false statement is #1. A method header is a declaration; a method body is its
implementation.
tWO trUthS & a LIe
Understanding Method Construction
1. A method header is also called an implementation.
2. When a method is declared with public access, methods in other classes
can call it.
3. Not all methods return a value, but every method requires a return type.
Creating a static Method that Requires No Arguments and Returns No Values
Paradise Day Spa provides many personal services such as haircuts, manicures, and
facials. In this section, you create a new class named ParadiseInfo, which contains
a main() method that calls a displayInfo() method.
1. Open a new document in your text editor, and type the following shell for the
class:
public class ParadiseInfo
{
}
2. Between the curly braces of the class, indent a few spaces and create the shell
for the main() method:
public static void main(String[] args)
{
}
You Do It
(continues)
97070_ch03_hr_110-169.indd 118 24/02/18 3:52 pm
119
Understanding Method Construction
3. Between the braces of the main() method, insert a call to the displayInfo()
method:
displayInfo();
4. Place the displayInfo() method outside the main() method, just before the
closing curly brace for the ParadiseInfo class:
public static void displayInfo()
{
System.out.println("Paradise Day Spa wants to pamper you.");
System.out.println("We will make you look good.");
}
5. Save the file as paradiseInfo.java.
6. Compile the class, and then execute it. The output should look like Figure 3-11.
Calling a static Method from Another Class
Next, you see how to call the displayInfo() method from a method within another
class.
1. Open a new document in your text editor, and then enter the following class in
which the main() method calls the displayInfo() method that resides in the
ParadiseInfo class:
public class TestInfo
{
public static void main(String[] args)
{
System.out.println("Calling method from another class:");
ParadiseInfo.displayInfo();
}
}
(continues)
(continued)
Figure 3-11 Output of the ParadiseInfo application
97070_ch03_hr_110-169.indd 119 24/02/18 3:52 pm
120
Using Methods, Classes, and ObjectsC h a p t e r 3
2. Save the file as testInfo.java in the same folder as the ParadiseInfo class.
If the files are not saved in the same folder and you try to compile the calling
class, your compiler issues the error message cannot find symbol; the symbol
named is the missing class you tried to call.
3. Compile the application and execute it. Your output should look like Figure 3-12.
The TestInfo class does not contain the displayInfo() method; it uses the
method from the ParadiseInfo class. It’s important that the displayInfo()
method is public. If you had omitted the keyword public from the definition of the
displayInfo() method in the ParadiseInfo class, then the TestInfo class would
not have been able to use it.
Examining the Details of a Prewritten static Method
Recall that in Chapter 2, you used the JOptionPane class to create statements
such as the following:
JOptionPane.showMessageDialog
(null, "Every bill is due in " + creditDays + " days");
In the next steps, you examine the Java API documentation for the
showMessageDialog() method so that you can better understand how
prewritten methods are similar to ones that you write.
1. Using a browser, go to the Java Platform Version 9 API Specification web page
(https://docs.oracle.com/javase/9/docs/api/overview-summary.html), and
select all Classes. In the alphabetical list of classes, find the JOptionPane
class and select it. (Because web page addresses might change after this book
is published, you might have to search for Java Version 9 API Specifications
instead of following the link provided here.)
(continued)
Figure 3-12 Output of the TestInfo application
(continues)
If you were to change the println() call to print() in the TestInfo class, the first
output line of the displayInfo() information would appear on the same line as Calling
method from another class:.
97070_ch03_hr_110-169.indd 120 24/02/18 3:52 pm
121
Adding Parameters to Methods
adding parameters to Methods
Some methods require that data items be sent to them when they are called. Data items you
use in a call to a method are called arguments. When the method receives the data items,
they are called parameters. Methods that receive data are flexible because they can pro-
duce different results depending on what data they receive.
As a real-life example, when you make a restaurant reservation, you do not need to employ
a different method for every date of the year at every possible time of day. Rather, you can
supply the date and time as information to the person who carries out the method. The
method, recording the reservation, is then carried out in the same manner, no matter what
date and time are supplied.
In a program, if you design a method to square numeric values, it makes sense to
design a square() method that you can supply with an argument that represents
the value to be squared, rather than having to develop a square1() method (that
squares the value 1), a square2() method (that squares the value 2), and so on. To
call a square() method that takes an argument, you might write a statement like
square(17); or square(86);. Similarly, any time it is called, the println() method
can receive any one of an infinite number of arguments—for example, “Hello”,
“Goodbye”, or any other String. No matter what message is sent to println(), the
message is displayed correctly. If the println() method could not accept arguments,
it would not be practical to use.
In everyday life, you use many methods without understanding how they work. For
example, when you make a real-life restaurant reservation, you do not need to know
how the reservation is actually recorded at the restaurant—perhaps it is written in a
book, marked on a large chalkboard, or entered into a computerized database. The
implementation details don’t concern you as a client, and if the restaurant changes its
methods from one year to the next, the change does not affect your use of the reservation
method—you still call and provide your name, a date, and a time.
2. Scroll through the class documentation until you find the Method Summary.
Then, find the first listed version of the showMessageDialog() method. To
the left, notice that the method is defined as a static void method, just like
the main() and displayInfo() methods discussed earlier in this “You Do
It” section. You can use the static showMessageDialog() method in your
classes by using its class name, a dot, and the method name, in the same way
that you used the ParadiseInfo.displayInfo() method in the outside class
named TestInfo.
(continued)
97070_ch03_hr_110-169.indd 121 24/02/18 3:52 pm
122
Using Methods, Classes, and ObjectsC h a p t e r 3
Creating a Method that Receives a Single Parameter
Whether or not a method can receive a parameter, its declaration contains the same
elements as one that does not accept a parameter—optional access specifiers, the return
type for the method, the method name, and a set of parentheses. However, if a method
receives a parameter, two additional items are required within the parentheses:
• The parameter type
• A local name for the parameter
For example, you might want to create a method to compute gross pay based on a standard
hourly pay rate; gross pay is the number of hours an employee worked multiplied by the
hourly pay rate before any deductions such as payroll taxes are taken. The declaration for
a public method named calculateGross() that accepts a value for an employee’s hours
worked could be written as follows:
public static void calculateGross(double hours)
You can think of the parentheses in a method declaration as a funnel into the method—
parameters listed there contain data that is “dropped into” the method. A parameter
accepted by a method can be any data type, including the primitive types, such as int,
double, and char; it also can be a built-in class type such as String or PrintStream, or a
class type you create.
In the method header for calculateGross(), the parameter double hours within the
parentheses indicates that the method will receive a value of type double, and that within
the method, the passed value will be known as hours. Figure 3-13 shows a complete
method that uses an hourly pay rate of $13.75.
The calculateGross() method is a void method because it does not need to return a
value to any other method that calls it—its only function is to receive the hours value,
multiply it by the STD_RATE constant, and then display the result.
Hidden implementation methods are often referred to as existing in a black box. Many everyday devices
are black boxes—that is, you can use them without understanding how they work. For example, most
of us use phones, television sets, and automobiles without understanding much about their internal
mechanisms.
Similarly, object-oriented programs use implementation hiding, which describes the encap-
sulation of method details. It means that a client does not have to know how a method works
internally, but only needs to know the name of the called method and what type of informa-
tion to send. (Usually, you also want to know about any data returned by the method; you
will learn about returned data later in this chapter.) In other words, the calling method needs
to understand only the interface to the called method. The interface is the only part of a
method that the method’s client sees or with which it interacts. In addition, if you substitute
a new or revised method implementation, as long as the interface to the method does not
change, you won’t need to make any changes in any methods that call the altered method.
97070_ch03_hr_110-169.indd 122 24/02/18 3:52 pm
123
Adding Parameters to Methods
The calculateGross() method’s parameter is a double, so you call it using any argument
that can be promoted to a double. In other words, it can accept a variable, constant, or
expression that is a double, float, long, int, short, or byte. (See Figure 2-41 in Chapter
2 to review the order for establishing unifying data types.) For example, all of the following
method calls are valid:
• calculateGross(10);—This call uses an unnamed int constant that is promoted to a
double.
• calculateGross(28.5);—This call uses an unnamed double constant.
• calculateGross(7.5 * 5);—This call uses an arithmetic expression.
• calculateGross(STANDARD_WORK_WEEK);—This call uses a named constant that might
be a double, float, long, int, short, or byte.
• calculateGross(myHours);—This call uses a variable that might be a double, float,
long, int, short, or byte.
• calculateGross(getGross());—This call assumes that the getGross() method
returns a double, float, long, int, short, or byte. You learn about methods that return
data later in this chapter.
You can call the calculateGross() method any number of times, with a different
argument each time. Each of these arguments becomes known as hours within the
method. The identifier hours represents a variable that holds a copy of the value
of any double value passed into the method.
It is interesting to note that if the value used as an argument in the method call to
calculateGross() is a variable, it might possess the same identifier as hours or a
different one, such as timeWorked. The code in Figure 3-14 shows three calls to the
calculateGross() method, and Figure 3-15 shows the output.
public static void calculateGross(double hours)
{
final double STD_RATE = 13.75;
double gross;
gross = hours * STD_RATE;
System.out.println(hours + " hours at $" +
STD_RATE + " per hour is $" + gross);
}
Figure 3-13 The calculateGross() method with a parameter
Parameter
data type
Parameter
identifier
97070_ch03_hr_110-169.indd 123 24/02/18 3:52 pm
124
Using Methods, Classes, and ObjectsC h a p t e r 3
In Figure 3-14, the identifier hours in the main() method that is used as an argument in one
of the method calls refers to a different memory location than hours in calculateGross()
method. The parameter hours is simply a placeholder while it is being used within the
method, no matter what name its value “goes by” in the calling method. The parameter
hours is a local variable to the calculateGross() method; that is, it is known only within
the boundaries of the method. The variable and constant declared within the method are
also local to the method.
Figure 3-15 Output of the DemoGrossPay application
Recall that the final modifier makes STD_RATE constant. Because hours is not altered within
the calculateGross() method in Figure 3-14, you also could make the method’s parameter
constant by declaring the method header as public static void calculateGross(final
double hours). There would be no difference in the program’s execution, but declaring a parameter
as final means it cannot be altered within the method. Someone reading your program would be able
to see more easily that the parameter is not intended to change.
Figure 3-14 The DemoGrossPay class with a main() method that calls the calculateGross()
method three times
public class DemoGrossPay
{
public static void main(String[] args)
{
double hours = 25;
double yourHoursWorked = 37.5;
calculateGross(10);
calculateGross(hours);
calculateGross(yourHoursWorked);
}
public static void calculateGross(double hours)
{
final double STD_RATE = 13.75;
double gross;
gross = hours * STD_RATE;
System.out.println(hours + “ hours at $” +
STD_RATE + “ per hour is $” + gross);
}
}
The calculateGross()
method is called three times
using three different arguments.
Each time the method
is called, the parameter
hours receives a copy of
the value that was passed.
97070_ch03_hr_110-169.indd 124 24/02/18 3:52 pm
125
Adding Parameters to Methods
Creating a Method that Requires Multiple Parameters
A method can require more than one parameter. For example, rather than creating a
calculateGross() method that uses a standard hourly rate of $13.75 for every employee,
you might prefer to create a method to which you can pass two values—the hours worked
as well as an hourly rate. Figure 3-16 shows a method that uses two such parameters.
Each time the calculateGross() method in Figure 3-14 executes, an hours variable is
redeclared—that is, a new memory location large enough to hold a double is set up and
named hours. Within the method, hours holds a copy of whatever value is passed into the
method by the main() method. When the calculateGross() method ends at the closing
curly brace, the local hours variable ceases to exist. That is, if you change the value of
hours after you have used it in the calculation within calculateGross(), it affects nothing
else. The memory location that holds hours is released at the end of the method, and any
changes to its value within the method do not affect any value in the calling method. In
particular, don’t think there would be any change in the variable named hours in the main()
method; that variable, even though it has the same name as the locally declared parameter
in the calculateGross() method, is a different variable with its own memory address.
When a variable ceases to exist at the end of a method, programmers say the variable goes out of
scope. A variable’s scope is the part of a program in which a variable exists and can be accessed using
its unqualified name. Chapter 4 discusses scope in greater detail.
Figure 3-16 The calculateGross() method that accepts two parameters
public static void calculateGross(double hours, double rate)
{
double gross;
gross = hours * rate;
System.out.println(hours + " hours at $" +
rate + " per hour is $" + gross);
}
Each parameter requires a data
type and an identifier.
The parameters are
separated with a comma.
In Figure 3-16, two parameters (double hours and double rate) appear within the
parentheses in the method header. A comma separates each parameter, and each parameter
requires its own declared type (in this case, both are double) as well as its own identifier.
Note that a declaration for a method that receives two or more parameters must list the
type for each parameter separately, even if the parameters have the same type.
You can pass multiple arguments to a method by listing the arguments within the call to the
method and separating them with commas.
97070_ch03_hr_110-169.indd 125 24/02/18 3:52 pm
126
Using Methods, Classes, and ObjectsC h a p t e r 3
You can write a method so that it takes any number of parameters in any order. However,
when you call a method, the arguments you send to a method must match in order—both
in number and in type—the parameters listed in the method declaration. Although the
calculated gross pay is the same either way, the call calculateGross(10, 20); results in
output describing 10 hours worked at $20 per hour, but calculateGross(20, 10); results
in output describing 20 hours worked at $10 per hour.
If arguments to a method are passed in the wrong order, the result is one of the following:
• If the method can still accept all the arguments, the result is a logical error; that is, the
program compiles and executes, but it probably produces incorrect results.
• If the method cannot accept the arguments, passing arguments in the wrong order con-
stitutes a syntax error, and the program does not compile. For example, if you try to pass
a double value to a method that accepts an int parameter, the program fails to compile.
A method’s signature is the combination of the method name and the number, types,
and order of arguments. Therefore, you can say that a method call must match the called
method’s signature.
The arguments in a method call are often referred to as actual parameters. The variables in the
method declaration that accept the values from the actual parameters are formal parameters.
The false statement is #3. A method header always contains a return type, an
identifier, and parentheses, but the parameter list might be empty.
tWO trUthS & a LIe
Adding Parameters to Methods
1. A class can contain any number of methods, and each method can be called
any number of times.
2. Arguments are used in method calls; they are passed to parameters in
method headers.
3. A method header always contains a return type, an identifier, and a param-
eter list within parentheses.
When you look at Java applications, you might see methods that appear to be callable in multiple ways.
For example, you can use System.out.println() with no arguments to display a blank line, or with
a String argument to display the String. You can use the method with different argument lists only
because multiple versions of the method have been written, each taking a specific set of arguments. The
ability to execute different method implementations by altering the argument used with the method name
is known as method overloading, a concept you will learn about in Chapter 4.
97070_ch03_hr_110-169.indd 126 24/02/18 3:52 pm
127
Creating Methods that Return Values
Creating Methods that return Values
A method ends when any of the following events takes place:
• The method completes all of its statements. You saw methods like this in the last section.
• The method throws an exception. Exceptions are errors; you will learn about them in
the chapter “Exception Handling.”
• The method reaches a return statement. A return statement causes a method to
end and the program’s logic to return to the calling method. Also, a return statement
frequently sends a value back to the calling method.
The return type for a method can be any type used in Java, which includes the primitive
types int, double, char, and so on, as well as class types (including class types you create).
Of course, as you have seen in several examples so far, a method also can return nothing, in
which case the return type is void.
A method’s return type is known more succinctly as a method’s type. For example, the
declaration for the displayAddress() method shown earlier in Figure 3-4 is written as follows:
public static void displayAddress()
This method returns no value, so it is type void.
A method that prompts a user for an age and returns the age to the calling method might
be declared as:
public static int getAge()
The method returns an int, so it is type int.
As another example, a method that returns true or false depending on whether an
employee worked overtime hours might be declared as:
public static boolean didWorkOvertime()
This method returns a Boolean value, so it is type boolean.
The calculateGross() method shown earlier produces output, but does not return any
value, so its return type is void. If you want to create a method to return the new, calculated
salary value rather than display it, the header would be written as shown Figure 3-17.
The method’s return type
The value that is returned
public static double calculateGross(double hours, double rate)
{
double gross;
gross = hours * rate;
return gross;
}
Figure 3-17 A version of the calculateGross() method that returns a double
97070_ch03_hr_110-169.indd 127 24/02/18 3:52 pm
128
Using Methods, Classes, and ObjectsC h a p t e r 3
You cannot place any statements after a method’s return statement. Such statements
are unreachable statements because the logical flow leaves the method at the return
statement. An unreachable statement can never execute, and it causes a compiler error.
Unreachable statements are also called dead code.
Notice the return type double that precedes the method name in the calculateGross()
method header in Figure 3-17. Also notice the last statement in the method; it returns
the value of the calculated gross back to the calling method. A method’s declared return
type must be compatible with the type of the value used in the return statement. In other
words, the return value must match the return type or be promotable to the return type.
If the returned value is not compatible with the method’s return type, the class does not
compile.
For example, a method with a double return type might have a return statement that looks
like either of the following:
return 1;
return 1.0;
Additionally, if the types are compatible, a method might return a variable, a named constant,
a call to another method, or the result of a calculation, as in the following examples:
return myHoursWorked;
return MAXIMUM_PAY;
return getHours();
return myRate * 1.2;
All methods except void methods require a return statement that returns a value of the appropriate
type. You can place a return statement in a void method that is simply the word return followed
by a semicolon. However, most Java programmers do not include a return statement in a method
when nothing is returned.
A method can contain multiple return clauses if they are embedded in a decision, although this
practice is not recommended because it can lead to errors that are difficult to detect. However, no
other statements can be placed after the last return clause in a method. You will learn about decision
making in the chapter “Making Decisions.”
If a method returns a value, then when you call the method, you normally use the
returned value, although you are not required to do so. For example, when you invoke the
calculateGross() method, you might want to assign the returned value (also called the
method’s value) to a double variable named myPay, as in the following statement:
myPay = calculateGross(myHoursWorked, myRate);
Alternatively, you can choose to use a method’s returned value directly, without storing it
in any variable. When you use a method’s value, you use it in the same way you would use
any variable of the same type. For example, you can display a method’s returned value from
within a println() method call as in the following:
System.out.println("My pay is " + calculateGross(myHoursWorked, myRate));
97070_ch03_hr_110-169.indd 128 24/02/18 3:52 pm
129
Creating Methods that Return Values
When you look at the call to the calculateWithholding() method from the
calculateNetPay() method, you do not know how calculateWithholding() works. You
only know that the method accepts a double as a parameter (because gross is passed into
it) and that it must return either a double or a type that can automatically be promoted to
a double (because the result is stored in the double variable withholding). In other words,
the method acts as a black box.
As examples, the calculateWithholding() method might subtract a fixed amount
from the gross pay, might calculate a percentage of the gross pay, or might use a series
of decisions to reduce gross pay by different amounts depending on its value. (You will
learn to make decisions in Chapter 5.) The calculateWithholding() method might even
contain calls to more methods to get more information, for example, one that determines
number of dependents or state of residence.
You also can chain method calls in a single statement. If you create methods named
getHours() and getRate(), and each return a double, then you might want to call
calculateNetPay() as follows:
double net = calculateNetPay(getHours(), getRate());
Because calculateGross() returns a double, you can use the method call in the same way
that you would use any simple double value. Notice the two closing parentheses at the end
of the statement. The first one completes the call to the calculateGross() method, and
the second one completes the call to the println() method.
You also might use a method’s return value directly in an arithmetic expression, as in the
following statement:
double spendingMoney = calculateGross(myHoursWorked, myRate) - expenses;
Chaining Method Calls
Any method might call any number of other methods. For example, a main() method
might call a calculateNetPay() method, and the calculateNetPay() method might call
both calculateGross() and calculateWithholding(), as shown in Figure 3-18.
public static double calculateNetPay(double hours, double rate)
{
double gross;
double withholding;
double net;
gross = calculateGross(hours, rate);
withholding = calculateWithholding(gross);
net = gross - withholding;
return net;
}
Figure 3-18 The calculateNetPay() method calling two other methods
Call to calculateWithholding()
Call to calculateGross()
97070_ch03_hr_110-169.indd 129 24/02/18 3:52 pm
130
Using Methods, Classes, and ObjectsC h a p t e r 3
Watch the video Methods and Parameters.
The false statement is #2. A method’s declared return type must match the type
of the value used in the return statement.
tWO trUthS & a LIe
Creating Methods that Return Values
1. The return type for a method can be any type used in Java, including int,
double, and void.
2. A method’s declared return type must match the type of the value used in the
parameter list.
3. You cannot place a method within another method, but you can call a method
from within another method.
Creating static Methods that Accept Arguments and Return a Value
In this section, you add a method to the ParadiseInfo class you started in the last
“You Do It” section. The new method receives two parameters and returns a value.
The purpose of the method is to accept a minimum price for the current week’s
featured discount and the percentage discount, and to return the minimum amount
the customer will save.
1. Open the paradiseInfo.java file in your text editor, and then change the class
name to ParadiseInfo2. Immediately save the file as paradiseInfo2.java.
2. As the first line of the file, add the import statement that allows user input:
import java.util.Scanner;
3. Add four declarations as the first statements following the opening curly brace
of the main() method. One holds the minimum price for which a discount
will be allowed, and another holds the discount rate. The third variable is the
You Do It
(continues)
97070_ch03_hr_110-169.indd 130 24/02/18 3:52 pm
131
Creating Methods that Return Values
minimum savings, which is calculated by multiplying the minimum price for a
discount and the discount rate. The fourth variable is a Scanner object to use
for keyboard input.
double price;
double discount;
double savings;
Scanner keyboard = new Scanner(System.in);
Instead of importing the Scanner class to provide console input, you could substitute
JOptionPane and include program statements that provide GUI input. The input
process can use other techniques too, such as getting data from a storage device—
you will learn about file input in the chapter “File Input and Output.” The concept of
input (getting data into memory from the outside) is the same, no matter what specific
technique or type of hardware device you use.
4. Following the declarations, prompt the user for the minimum discount price, and
accept a value from the keyboard:
System.out.print("Enter cutoff price for discount >> ");
price = keyboard.nextDouble();
5. Prompt the user for the discount rate, and accept it.
System.out.print("Enter discount rate as a whole number >> ");
discount = keyboard.nextDouble();
6. After the call to displayInfo(), insert a call to computeDiscountInfo().
You will pass the price and discount values to the method, and the
method returns the minimum that a consumer will save, which is stored in
savings:
savings = computeDiscountInfo(price, discount);
7. Just before the closing curly brace for the main() method, display the savings
information:
System.out.println("Special this week on any service over " +
price);
System.out.println("Discount of " + discount + " percent");
System.out.println("That’s a savings of at least $" + savings);
(continues)
(continued)
97070_ch03_hr_110-169.indd 131 24/02/18 3:52 pm
132
Using Methods, Classes, and ObjectsC h a p t e r 3
8. After the displayInfo() method implementation, but before the closing curly
brace for the class, add the computeDiscountInfo() method. It accepts two
doubles and returns a double.
public static double computeDiscountInfo(double price, double
discountRate)
{
double savings;
savings = price * discountRate / 100;
return savings;
}
9. Save the file, and then compile and execute it. Figure 3-19 shows a typical
execution. After the user is prompted for the cutoff price for the week’s sale
and the discount to be applied, the program executes the displayInfo()
method. Then the program executes the computeDiscountInfo() method,
which returns a value to store in the savings variable. Finally, the discount
information is displayed.
Understanding that Methods Can Be Used as Black Boxes
In this chapter, you have learned that methods can be used without knowing the
details of their implementation. As an example of how professional programmers
use implementation hiding, you can visit the Java website to see the interfaces for
thousands of prewritten methods that reside in the Java prewritten classes. You are
not allowed to see the code inside these methods; you see only their interfaces,
which is all you need to be able to use the methods.
1. Open a browser, go to the Java website, and navigate to the documentation
for the classes for Java SE 9 (https://docs.oracle.com/javase/9/docs/api/
allclasses-noframe.html).
(continued)
(continues)
Figure 3-19 Typical execution of the ParadiseInfo2 program
97070_ch03_hr_110-169.indd 132 24/02/18 3:52 pm
133
Learning About Classes and Objects
Learning about Classes and Objects
When you think in an object-oriented manner, everything is an object, and every object
is a member of a class. You can think of any inanimate physical item as an object—your
desk, your computer, and the building in which you live are all called objects in everyday
conversation. You also can think of living things as objects—your houseplant, your pet
fish, and your sister are objects. Events are also objects—the stock purchase you made,
the mortgage closing you attended, and a graduation party that was held in your honor
are all objects.
Everything is an object, and every object is a member of a more general class. Your desk is
a member of the class that includes all desks, and your pet fish is a member of the class that
contains all fish. An object-oriented programmer would say that your desk is an instance
of the Desk class and your fish is an instance of the Fish class. These statements represent
is-a relationships—that is, relationships in which the object “is a” concrete example of the
class. Expressing an is-a relationship is correct only when you refer to the object and the
class in the proper order. You can say, “My oak desk with the scratch on top is a Desk, and
my goldfish named Moby is a Fish.” You don’t define a Desk by saying, “A Desk is an oak
desk with a scratch on top,” or explain what a Fish is by saying, “A Fish is a goldfish named
Moby,” because both a Desk and a Fish are much more general. The difference between a
class and an object parallels the difference between abstract and concrete. An object is an
instantiation of a class, or one tangible example of a class. Your goldfish, my guppy, and the
zoo’s shark each constitute one instantiation of the Fish class.
2. From the alphabetical list of classes, select printStream.
3. At the PrintStream page, read the descriptions of several methods for the
class. Note that for each method, you can see the return type, method name,
and parameter list, but you do not see the implementation for any of the
existing methods.
4. Examine other classes. Again, note that the Java documentation provides
you with method interfaces but not implementations. When you develop your
own classes in the future, you might choose to provide your users with similar
documentation and compiled classes so that they cannot see, modify, or steal
the code you have worked hard to develop.
(continued)
Objects can be members of more than one class. For example, your goldfish is not just a Fish, but
also a Vertebrate, and also an Animal. You will study this concept in greater depth in the chapter
“Introduction to Inheritance.”
97070_ch03_hr_110-169.indd 133 24/02/18 3:52 pm
134
Using Methods, Classes, and ObjectsC h a p t e r 3
The concept of a class is useful because of its reusability. Objects gain their attributes from
their classes, and all objects have predictable attributes because they are members of certain
classes. For example, if you are invited to a graduation party, you automatically know many
things about it. You assume there will be a starting time, a certain number of guests, and
some quantity of food. You understand what a party object entails because of your previous
knowledge of the Party class. You don’t know the number of guests or what food will be
served at this particular party, but you understand that because all parties have guests and
refreshments, this one must too. Because you understand the general characteristics of a
Party, you anticipate different attributes than if you plan to attend a TheaterPerformance
object or a DentalAppointment object.
In addition to their attributes, objects have methods associated with them, and every object
that is an instance of a class is assumed to possess the same methods. For example, for all
Party objects, a date and time are set at some point. In a program, you might name these
methods setDate() and setTime(). Party guests need to know the date and time and
might use methods named getDate() and getTime() to find out the date and time of any
Party object. Method names that begin with get and set are very typical. You will learn
more about get and set methods in the next section.
Your graduation party, then, might have the identifier myGraduationParty. As a member
of the Party class, myGraduationParty, like all Party objects, might have data methods
setDate() and setTime(). When you use them, the setDate() and setTime() methods
require arguments, or information passed to them. For example, statements such as
myGraduationParty.setDate("May 12") and myGraduationParty.setTime("6 P.M.")
invoke methods that are available for the myGraduationParty object. When you use an
object and its methods, think of being able to send a message to the object to direct it to
accomplish some task—you can tell the Party object named myGraduationParty to set the
date and time you request. Even though yourAnniversaryParty is also a member of the
Party class, and even though it also has access to setDate() and setTime() methods,
the arguments you send to yourAnniversaryParty methods will be different from those
you send to myGraduationParty methods. Within any object-oriented program, you are
continuously making requests to objects’ methods and often including arguments as part
of those requests.
In addition, some methods used in an application must return a message or value. If one
of your party guests uses the getDate() method, the guest hopes that the method will
respond with the desired information. Similarly, within object-oriented programs, methods
are often called upon to return a piece of information to the source of the request. For
example, a method within a Payroll class that calculates federal withholding tax might
return a tax amount in dollars and cents, and a method within an Inventory class might
Programmers also use the phrase is-a when talking about inheritance relationships. You will learn more
about inheritance in the chapters “Introduction to Inheritance” and “Advanced Inheritance Concepts.”
97070_ch03_hr_110-169.indd 134 24/02/18 3:52 pm
135
Learning About Classes and Objects
return true or false, depending on the method’s determination of whether an item is at
the reorder point.
With object-oriented programming, sometimes you create classes so that you can
instantiate objects from them, and other times you create classes to run as applications.
Application classes frequently instantiate objects that use the objects of other classes (and
their data and methods). Sometimes you write classes that do both. The same programmer
does not need to write every class he or she uses. Often, you will write programs that use
classes created by others. For example, many programs you have seen so far in this book
have used the System class. You did not have to create it or its println() method; both
were provided for you by Java’s creators. Similarly, you might create a class that others will
use to instantiate objects within their own applications. You can call an application or class
that instantiates objects of another class a class client or class user.
You can identify a class that is an application because it contains a public static void
main() method. The main() method is the starting point for any application. You will write and use
many classes that do not contain a main() method—these classes can be used by other classes that
are applications.
A Java application can contain only one method with the header public static void
main(String[] args). If you write a class that imports another class, and both classes have a
public main() method, your application will not compile.
So far, you’ve learned that object-oriented programming involves objects that send
messages to other objects requesting they perform tasks, and that every object belongs
to a class. Understanding classes and how objects are instantiated from them is the heart
of object-oriented thinking.
The false statement is #1. An object is one instantiation of a class.
tWO trUthS & a LIe
Learning About Classes and Objects
1. A class is an instantiation of many objects.
2. Objects gain their attributes and methods from their classes.
3. An application or class that instantiates objects of another prewritten class is
a class client.
97070_ch03_hr_110-169.indd 135 24/02/18 3:52 pm
136
Using Methods, Classes, and ObjectsC h a p t e r 3
Creating a Class
When you create a class, you must assign a name to the class, and you must determine
what data and methods will be part of the class. Suppose you decide to create a class named
Employee. One instance variable of Employee might be an employee number, and two
necessary methods might be a method to set (or provide a value for) the employee number
and another method to get (or retrieve) that employee number. To begin, you create a class
header with three parts:
• An optional access specifier
• The keyword class
• Any legal identifier you choose for the name of your class—starting with an uppercase
letter is conventional
For example, a header for a class that represents an employee might be:
public class Employee
The most liberal form of access is public. The keyword public is a class modifier. Classes
that are public are accessible by all objects. Public classes also can be extended, or used as
a basis for any other class. Making access public means that if you develop a good Employee
class, and someday you want to develop two classes that are more specific, SalariedEmployee
and HourlyEmployee, then you do not have to start from scratch. Each new class can become
an extension of the original Employee class, inheriting its data and methods. Although other
specifiers exist, you will use the public specifier for most of your classes.
You will learn about extended classes in the chapter “Introduction to Inheritance.”
After writing the class header public class Employee, you write the body of the Employee
class between a set of curly braces. The body contains the data and methods for the class. The
data components of a class are often referred to as data fields to help distinguish them from
other variables you might use. Figure 3-20 shows an Employee class that contains one data field
named empNum. Data fields are variables you declare within a class but outside of any method.
public class Employee
{
private int empNum;
}
Figure 3-20 The Employee class with one field
In Figure 3-20, the data field empNum is not preceded by the keyword static. If the keyword
static had been inserted there, only one empNum value would be shared by all Employee
objects that are eventually instantiated. Because the empNum field in Figure 3-20 is not
97070_ch03_hr_110-169.indd 136 24/02/18 3:52 pm
137
Creating a Class
preceded by static, when you eventually create, or instantiate, objects from the class, each
Employee can have its own unique empNum. Each object gets its own copy of each nonstatic
data field in its class. A nonstatic field like empNum is an instance variable for the class
because one copy exists for each object instantiation.
You already have learned that the access specifier for most Java methods is public. How-
ever, most fields, such as empNum in the Employee class, are private, which provides the
highest level of security. Assigning private access to a field means that no other classes
can access the field’s values, and only methods of the same class are allowed to set, get, or
otherwise use private variables. The principle used in creating private access is sometimes
called information hiding and is an important component of object-oriented programs. A
class’s private data can be changed or manipulated only by a class’s own methods and not
by methods that belong to other classes.
In contrast to fields, which are usually private, most class methods are public. The resulting
private data/public method arrangement provides a means for you to control outside access
to your data—only a class’s nonprivate methods can be used to access a class’s private data.
The situation is similar to hiring a public receptionist to sit in front of your private office and
control which messages you receive (perhaps deflecting trivial or hostile ones) and which
messages you send (perhaps checking your spelling, grammar, and any legal implications).
The way in which the nonprivate methods are written controls how you use the private data.
The first release of Java (1.0) supported five access levels—the four listed previously plus private
protected. The private protected access level is not supported in versions of Java higher
than 1.0; you should not use it in your Java programs.
In summary, a class’s data fields are most often private and not static. The exception occurs
when you want to use a nonchanging value without being required to create an object—in
that case you make the field both static and final. For example, the Java Math class
contains a final, public, static field named PI that you can use without instantiating a
Math object. You will learn about the Math class in Chapter 4.
The false statement is #2. When you instantiate objects, each has its own copy of
each nonstatic data field in the class.
tWO trUthS & a LIe
Creating a Class
1. A class header contains an optional access specifier, the keyword class,
and an identifier.
2. When you instantiate objects, each has its own copy of each static data
field in the class.
3. Most fields in a class are private, and most methods are public.
97070_ch03_hr_110-169.indd 137 24/02/18 3:52 pm
138
Using Methods, Classes, and ObjectsC h a p t e r 3
Creating Instance Methods in a Class
Besides data, classes contain methods. For example, one method you need for an Employee
class that contains an empNum is the method to retrieve (or return) any Employee’s empNum
for use by another class. A reasonable name for this method is getEmpNum(), and its
declaration is public int getEmpNum() because it will have public access, return an
integer (the employee number), and possess the identifier getEmpNum().
Similarly, you need a method with which to set the empNum field. A reasonable name for this
method is setEmpNum(), and its declaration is public void setEmpNum(int emp) because
it will have public access, return nothing, possess the identifier setEmpNum(), and require a
parameter that represents the employee’s ID number, which is type int.
Methods that set or change field values are called mutator methods; methods that retrieve
values are called accessor methods. In Java, mutator methods are often called setters, and
they conventionally start with the prefix set. Accessor methods are called getters, and they
conventionally start with the prefix get. Using these three-letter prefixes with your method
names is not required, but it is conventional. Figure 3-21 shows the get and set methods for
the empNum field for the Employee class.
Notice that, unlike the methods you created earlier in this chapter, the getEmpNum() and
setEmpNum() methods do not employ the static modifier. The keyword static is used
for classwide methods, but not for methods that “belong” to objects. If you are creating
a program with a main() method that you will execute to perform some task, many of
your methods will be static so you can call them from within main() without creating
objects. However, if you are creating a class from which objects will be instantiated,
most methods probably will be nonstatic because you will associate the methods with
individual objects. For example, the getEmpNum() method must be nonstatic because it
returns a different empNum value for every Employee object you ever create. Nonstatic
methods, those methods used with object instantiations, are called instance methods.
You can use either a static or nonstatic method with an object, but only nonstatic
methods behave uniquely for each object. You cannot use a nonstatic method without
an object.
public void setEmpNum(int emp)
{
empNum = emp;
}
public int getEmpNum()
{
return empNum;
}
Figure 3-21 The setEmpNum() and getEmpNum() methods
97070_ch03_hr_110-169.indd 138 24/02/18 3:52 pm
139
Creating Instance Methods in a Class
Understanding when to declare fields and methods as static and nonstatic is a challenge
for new programmers. To help you determine whether a data field should be static, you
can ask yourself how many times it occurs. If it occurs once per class, it is static, but if it
occurs once per object, it is not static. Table 3-1 provides a summary.
Figure 3-22 provides examples of how public, private, static, and nonstatic class
members can be used by another class. The figure shows a class named MyClass that
contains four methods that are public static, private static, public nonstatic, and
private nonstatic. The figure also shows a TestClass that instantiates a MyClass object.
Table 3-1 mentions the this reference. You will learn about the this reference in the next chapter.
Static Nonstatic
In Java, static is a keyword. It also can be
used as an adjective.
There is no keyword for nonstatic items. When
you do not explicitly declare a field or method to
be static, it is nonstatic by default.
Static fields in a class are called class fields. Nonstatic fields in a class are called instance
variables.
Static methods in a class are called class
methods.
Nonstatic methods in a class are called instance
methods.
When you use a static field or method, you
do not need to use an object; for example:
JOptionPane.showDialog();
When you use a nonstatic field or method,
you must use an object; for example:
System.out.println();
When you create a class with a static field and
instantiate 100 objects, only one copy of that
field exists in memory.
When you create a class with a nonstatic field
and instantiate 100 objects, then 100 copies of
that field exist in memory.
When you create a static method in a class and
instantiate 100 objects, only one copy of the
method exists in memory and the method does
not receive a this reference.
When you create a nonstatic method in a class
and instantiate 100 objects, only one copy of
the method exists in memory, but the method
receives a this reference that contains the
address of the object currently using it.
Static class variables are not instance variables.
The system allocates memory to hold class
variables once per class, no matter how many
instances of the class you instantiate. The
system allocates memory for class variables
the first time it encounters a class, and every
instance of a class shares the same copy of any
static class variables.
Instance fields and methods are nonstatic. The
system allocates a separate memory location for
each nonstatic field in each instance.
table 3-1 Comparison of static and nonstatic
97070_ch03_hr_110-169.indd 139 24/02/18 3:52 pm
140
Using Methods, Classes, and ObjectsC h a p t e r 3
The TestClass contains eight method calls. The three valid calls are all to public methods.
The call to the nonstatic method uses an object, and the two calls to the static method can
use an object or not. The rest of the TestClass code after the comment is invalid. Private
methods cannot be called from outside the class, and nonstatic methods require an object.
Figure 3-22 Examples of legal and illegal method calls based on combinations of method modifiers
public class MyClass
{
public static pubStatMethod()
private static privStatMethod()
public pubNonstatMethod()
private privNonstatMethod()
}
public class TestClass
{
MyClass object = new MyClass();
object.pubNonstatMethod();
object.pubStatMethod();
MyClass.pubStatMethod();
// None of the following work
MyClass.privStatMethod();
MyClass.pubNonstatMethod();
object.privStatMethod();
object.privNonstatMethod();
MyClass.privNonstatMethod();
}
The nonstatic method must be
used with a MyClass object.
An object can use a static or
nonstatic method, but these
methods are private and
cannot be used here.
This is wrong on two counts—the
method is nonstatic, so it needs an
object, and in any event, the
method is private.
TestClass doesn’t have
access to the private
method.
The public nonstatic method
can be used from TestClass
with a MyClass object.
The public static
method can be
used from
TestClass with
or without an
object.
Figure 3-23 shows a typical class that would be used to declare an Employee class
containing one private data field and two public methods, all of which are nonstatic. This
class becomes the model for a new data type named Employee; when Employee objects
eventually are created, each will have its own empNum field, and each will have access to two
methods—one that provides a value for its empNum field and another that retrieves the value
stored there.
97070_ch03_hr_110-169.indd 140 24/02/18 3:52 pm
141
Creating Instance Methods in a Class
When you create a class such as Employee, you can compile it, but you cannot execute the
class because it does not contain a main() method. A class such as Employee is intended to
be used as a data type for objects within other applications, as you will see in the next section.
Organizing Classes
Most classes that you create have multiple data fields and methods. For example, in
addition to requiring an employee number, an Employee needs a last name, a first name,
and a salary, as well as methods to set and get those fields. Figure 3-24 shows one way you
could arrange the data fields for the Employee class.
public class Employee
{
private int empNum;
public int getEmpNum()
{
return empNum;
}
public void setEmpNum(int emp)
{
empNum = emp;
}
}
Figure 3-23 The Employee class with one field and two methods
public class Employee
{
private int empNum;
private String empLastName;
private String empFirstName;
private double empSalary;
//Methods will go here
}
Figure 3-24 An Employee class with several data fields
Although there is no requirement to do so, most programmers place data fields in some
logical order at the beginning of a class. For example, empNum is most likely used as a unique
identifier for each employee (what database users often call a primary key), so it makes
sense to list the employee number first in the class. An employee’s last name and first name
“go together,” so it makes sense to store these two Employee components adjacently. Despite
these commonsense rules, you have a lot of flexibility in how you position your data fields
within any class.
97070_ch03_hr_110-169.indd 141 24/02/18 3:52 pm
142
Using Methods, Classes, and ObjectsC h a p t e r 3
A unique identifier is one that should have no duplicates within an application. For example, an
organization might have many employees with the last name Johnson or a weekly salary of $400.00,
but there is only one employee with employee number 128.
Because the current Employee class has two String components, they might be declared
within the same statement, such as the following:
private String empLastName, empFirstName;
However, it is usually easier to identify each Employee field at a glance if the fields are listed
vertically.
You can place a class’s data fields and methods in any order within a class. For example,
you could place all the methods first, followed by all the data fields, or you could organize
the class so that several data fields are followed by methods that use them, and then
several more data fields are followed by the methods that use them. This book follows the
convention of placing all data fields first so that you can see their names and data types
before reading the methods that use them.
The Employee class started in Figure 3-24 contains only four fields. Even if only one set
method and one get method are needed for each, eight methods are required. Consider an
employee record for most organizations, and you will realize that many more fields often
are required (such as address, phone number, hire date, number of dependents, and so on),
as well as many more methods. Finding your way through the list can become a formidable
task. For ease in locating class methods, many programmers store them in alphabetical
order. Other programmers arrange values in pairs of get and set methods, an order that also
results in functional groupings. Figure 3-25 shows how the complete class definition for an
Employee might appear.
public class Employee
{
private int empNum;
private String empLastName;
private String empFirstName;
private double empSalary;
public int getEmpNum()
{
return empNum;
}
public void setEmpNum(int emp)
{
empNum = emp;
}
public String getEmpLastName()
{
return empLastName;
}
Figure 3-25 The Employee class with several data fields and corresponding methods (continues)
97070_ch03_hr_110-169.indd 142 24/02/18 3:52 pm
143
Creating Instance Methods in a Class
The Employee class is still not a particularly large class, and each of its methods is very
short, but it is already becoming quite difficult to manage. It certainly can support some
well-placed comments. For example, the purpose of the class and the programmer’s
name might appear in comments at the top of the file, and comments might be used to
separate the data and method sections of the class. Your organization might have specific
recommendations or requirements for placing comments within a class.
public void setEmpLastName(String name)
{
empLastName = name;
}
public String getEmpFirstName()
{
return empFirstName;
}
public void setEmpFirstName(String name)
{
empFirstName = name;
}
public double getEmpSalary()
{
return empSalary;
}
public void setEmpSalary(double sal)
{
empSalary = sal;
}
}
Figure 3-25 The Employee class with several data fields and corresponding methods
The false statement is #3. Nonstatic methods are instance methods; static
methods are class methods.
tWO trUthS & a LIe
Creating Instance Methods in a Class
1. The keyword static is used with classwide methods, but not for methods
that “belong” to objects.
2. When you create a class from which objects will be instantiated, most
methods are nonstatic because they are associated with individual objects.
3. Static methods are instance methods.
(continued)
97070_ch03_hr_110-169.indd 143 24/02/18 3:52 pm
144
Using Methods, Classes, and ObjectsC h a p t e r 3
Creating a Class that Contains Instance Fields and Methods
Next, you create a class to store information about event services offered at
Paradise Day Spa.
1. Open a new document in your text editor, and type the following class header
and the curly braces to surround the class body:
public class SpaService
{
}
2. Between the curly braces for the class, insert two private data fields that will
hold data about a spa service:
private String serviceDescription;
private double price;
3. Within the class’s curly braces and after the field declarations, enter the following
two methods that set the field values. The setServiceDescription() method
accepts a String parameter and assigns it to the serviceDescription field for
each object that eventually will be instantiated. Similarly, the setPrice() method
accepts a double parameter and assigns it to the price field. Note that neither
of these methods is static.
public void setServiceDescription(String service)
{
serviceDescription = service;
}
public void setPrice(double servicePrice)
{
price = servicePrice;
}
4. Next, add two methods that retrieve the field values as follows:
public String getServiceDescription()
{
return serviceDescription;
}
public double getPrice()
{
return price;
}
You Do It
(continues)
97070_ch03_hr_110-169.indd 144 24/02/18 3:52 pm
145
Declaring Objects and Using Their Methods
Declaring Objects and Using their Methods
Declaring a class does not create any actual objects. A class is just an abstract description
of what an object will be like if any objects are ever actually instantiated. Just as you might
understand all the characteristics of an item you intend to manufacture long before the first
item rolls off the assembly line, you can create a class with fields and methods long before
you instantiate any objects that are members of that class.
A two-step process creates an object that is an instance of a class. First, you supply a type
and an identifier—just as when you declare any variable—and then you allocate computer
memory for that object. For example, you might declare an integer as int someValue; and
you might declare an Employee as follows:
Employee someEmployee;
In this statement, someEmployee can be any legal identifier, but objects conventionally start
with a lowercase letter.
When you declare an integer as int someValue;, you notify the compiler that an integer
named someValue will exist, and you reserve computer memory for it at the same time.
When you declare the someEmployee instance of the Employee class, you are notifying the
compiler that you will use the identifier someEmployee. However, you are not yet setting
aside computer memory in which the Employee named someEmployee might be stored—
that is done automatically only for primitive type variables. To allocate the needed memory
for an object, you must use the new operator. Two statements that actually complete the
process by setting aside enough memory to hold an Employee are as follows:
Employee someEmployee;
someEmployee = new Employee();
You first learned about the new operator when you created a Scanner object in Chapter 2.
Instead of using two statements, you can declare and reserve memory for someEmployee
in one statement, as in the following:
Employee someEmployee = new Employee();
5. Save the file as SpaService.java, compile it, and then correct any syntax
errors. Remember, you cannot run this file as a program because it does not
contain a public static main() method. After you read the next section, you
will use this class to create objects.
(continued)
97070_ch03_hr_110-169.indd 145 24/02/18 3:52 pm
146
Using Methods, Classes, and ObjectsC h a p t e r 3
In this statement, Employee is the object’s type (as well as its class), and someEmployee is the
name of the object. Also, someEmployee becomes a reference to the object—the name for
a memory address where the object is held. Every object name is also a reference—that is,
a computer memory location. In Chapter 2, you learned that a class such as Employee is a
reference type.
The equal sign is the assignment operator, so a value is being assigned to someEmployee in
the declaration. The new operator is allocating a new, unused portion of computer memory
for someEmployee. The value that the statement is assigning to someEmployee is a memory
address at which someEmployee is to be located. You do not need to be concerned with
what the actual memory address is—when you refer to someEmployee, the compiler locates
it at the appropriate address for you.
The final portion of the statement after the new operator, Employee(), with its parentheses,
looks suspiciously like a method name. In fact, it is the name of a method that constructs an
Employee object. The Employee() method is a constructor, a special type of method that
creates and initializes objects. You can write your own constructor for a class, and you will
learn how later in this chapter. However, when you don’t write a constructor for a class, Java
writes one for you. Whether you write your own constructor or use the one automatically
created by Java, the name of the constructor is always the same as the name of the class
whose objects it constructs.
After an object has been instantiated, its methods can be accessed using the object’s
identifier, a dot, and a method call. For example, Figure 3-26 shows an application that
instantiates two Employee objects. The two objects, clerk and driver, each use the
setEmpNum() and getEmpNum() method one time. The DeclareTwoEmployees application can
use these methods because they are public, and it must use each of them with an Employee
object because the methods are not static. Figure 3-27 shows the output of the application.
public class DeclareTwoEmployees
{
public static void main(String[] args)
{
Employee clerk = new Employee();
Employee driver = new Employee();
clerk.setEmpNum(345);
driver.setEmpNum(567);
System.out.println("The clerk's number is " +
clerk.getEmpNum() + " and the driver's number is " +
driver.getEmpNum());
}
}
Figure 3-26 The DeclareTwoEmployees class
97070_ch03_hr_110-169.indd 146 24/02/18 3:52 pm
147
Declaring Objects and Using Their Methods
The program in Figure 3-26 assumes that the Employee.java file is stored in the same folder as the
application. If the Employee.java file was stored in a different folder, you would need an import statement
at the top of the file, similar to the ones you use for the Scanner and JOptionPane classes.
Watch the video Classes and Objects.
Figure 3-27 Output of the DeclareTwoEmployees application
Understanding Data Hiding
Within the DeclareTwoEmployees class, you must use the public methods setEmpNum() and
getEmpNum() to be able to set and retrieve the value of the empNum field for each Employee
because you cannot access the private empNum field directly. For example, the following
statement would not be allowed:
clerk.empNum = 789;
This statement generates the error message empNum has private access in Employee,
meaning you cannot access empNum from the DeclareTwoEmployees class. If you made
empNum public instead of private, a direct assignment statement would work, but you
would violate an important principle of object-oriented programming—that of data hiding
using encapsulation. Data fields usually should be private, and a client application should
be able to access them only through the public interfaces—that is, through the class’s public
methods. However, you might reasonably ask, “When I write an application, if I can’t set an
object’s data field directly, but I can set it using a public method, what’s the difference? The
field value is set either way!” Actually, the setEmpNum() method in the Employee class in
Figure 3-25 does accept any integer value you send into it. However, you could rewrite the
setEmpNum() method to prevent invalid data from being assigned to an object’s data fields.
For example, perhaps your organization has rules for valid employee ID numbers—they
must be no fewer than five digits, or they must start with a 9, for instance. The statements
that enforce these requirements would be part of the setEmpNum() method. Checking a value
for validity requires decision making. You will learn more in the chapter “Making Decisions.”
Similarly, a get method might control how a value is retrieved. Perhaps you do not want
clients to have access to part of an employee’s ID number, or perhaps you always want to add
a company code to every ID before it is returned to the client. Even when a field has no data
value requirements or restrictions, making data private and providing public set and get
methods establishes a framework that makes such modifications easier in the future. You
will not necessarily write set and get methods for every field in a class; there are some fields
that clients will not be allowed to alter. Some fields will simply be assigned values, and some
field values might not be set directly, but might be calculated from the values of others.
97070_ch03_hr_110-169.indd 147 24/02/18 3:52 pm
148
Using Methods, Classes, and ObjectsC h a p t e r 3
The false statement is #1. When you declare an object, you are not yet setting
aside computer memory in which the object is stored; to allocate the needed
memory for an object, you must use the new operator.
tWO trUthS & a LIe
Declaring Objects and Using Their Methods
1. When you declare an object, you give it a name and set aside enough
memory for the object to be stored.
2. An object name is a reference; it holds a memory address.
3. When you don’t write a constructor for a class, Java creates one for you; the
name of the constructor is always the same as the name of its class.
Declaring and Using Objects
In the last “You Do It” section, you created a class named SpaService. Now you
create an application that instantiates and uses SpaService objects.
1. Open a new file in your text editor, and type the import statement needed for an
interactive program that accepts user keyboard input:
import java.util.Scanner;
2. Create the shell for a class named CreateSpaServices:
public class CreateSpaServices
{
}
3. Between the curly braces of the CreateSpaServices class, create the shell for
a main() method for the application:
public static void main(String[] args)
{
}
You Do It
(continues)
97070_ch03_hr_110-169.indd 148 24/02/18 3:52 pm
149
Declaring Objects and Using Their Methods
4. Within the main() method, declare variables to hold a service description and
price that a user can enter from the keyboard:
String service;
double price;
5. Next, declare three objects. Two are SpaService objects that use the class you
created in the last set of “You Do It” steps. The third object uses the built-in Java
Scanner class. Both classes use the new operator to allocate memory for their
objects, and both call a constructor that has the same name as the class. The
difference is that the Scanner constructor requires an argument (System.in),
but the SpaService class does not.
SpaService firstService = new SpaService();
SpaService secondService = new SpaService();
Scanner keyboard = new Scanner(System.in);
6. In the next statements, you prompt the user for a service, accept it from the
keyboard, prompt the user for a price, and accept it from the keyboard.
System.out.print("Enter service >> ");
service = keyboard.nextLine();
System.out.print("Enter price >> ");
price = keyboard.nextDouble();
7. Recall that the setServiceDescription() method in the SpaService class
is nonstatic, meaning it is used with an object, and that it requires a String
argument. Write the statement that sends the service the user entered to the
setServiceDescription() method for the firstService object:
firstService.setServiceDescription(service);
8. Similarly, send the price the user entered to the setPrice() method for
the firstService object. Recall that this method is nonstatic and requires
a double argument.
firstService.setPrice(price);
9. Make a call to the nextLine() method to remove the Enter key that remains
in the input buffer after the last numeric entry. Then repeat the prompts, and
accept data for the second SpaService object.
keyboard.nextLine();
System.out.print("Enter service >> ");
service = keyboard.nextLine();
(continues)
(continued)
97070_ch03_hr_110-169.indd 149 24/02/18 3:52 pm
150
Using Methods, Classes, and ObjectsC h a p t e r 3
System.out.print("Enter price >> ");
price = keyboard.nextDouble();
secondService.setServiceDescription(service);
secondService.setPrice(price);
10. Display the details for the firstService object.
System.out.println("First service details:");
System.out.println(firstService.getServiceDescription() +
" $" + firstService.getPrice());
11. Display the details for the secondService object.
System.out.println("Second service details:");
System.out.println(secondService.getServiceDescription() +
" $" + secondService.getPrice());
12. Save the file as CreateSpaServices.
java. Compile and execute the program.
Figure 3-28 shows a typical execution.
Make sure you understand how the
user’s entered values are assigned to
and retrieved from the two SpaService
objects.
(continued)
Figure 3-28 Typical execution of
the CreateSpaServices program
an Introduction to Using Constructors
When you create a class, such as Employee, and instantiate an object with a statement such
as the following, you actually are calling the Employee class constructor that is provided by
default by the Java compiler:
Employee chauffeur = new Employee();
A constructor establishes an object; a default constructor is one that requires no
arguments. A default constructor is created automatically by the Java compiler for
any class you create whenever you do not write your own constructor.
97070_ch03_hr_110-169.indd 150 24/02/18 3:52 pm
151
An Introduction to Using Constructors
When the prewritten, default constructor for the Employee class is called, it establishes
one Employee object with the identifier provided. The automatically supplied default
constructor provides the following specific initial values to an object’s data fields:
• Numeric fields are set to 0 (zero).
• Character fields are set to Unicode ‘\u0000’.
• Boolean fields are set to false.
• Fields that are object references (for example, String fields) are set to null
(or empty).
If you do not want each field in an object to hold these default values, or if you want
to perform additional tasks when you create an instance of a class, you can write your
own constructor. Any constructor you write must have the same name as the class it
constructs, and constructors cannot have a return type—not even void. Normally, you
declare constructors to be public so that other classes can instantiate objects that belong
to the class. When you write a constructor for a class, you no longer have access to the
automatically created version.
For example, if you want every Employee object to have
a default starting salary of $300.00 per week, you could
write the constructor for the Employee class that appears
in Figure 3-29. Any Employee object instantiated will have
an empSalary field value equal to 300.00, and the other
Employee data fields will contain the automatically supplied
default values. Even though you might want a field to hold
the default value for its data type, you still might prefer to
explicitly initialize the field for clarity.
public Employee()
{
empSalary = 300.00;
}
Figure 3-29 The Employee
class constructor that assigns a
salary
You can write any Java statement in a constructor. Although you usually have no reason to
do so, you could display a message from within a constructor or perform any other task.
You can place the constructor anywhere inside the class, outside of any other method.
Typically, a constructor is placed with the other methods. Often, programmers list the
constructor first because it is the first method used when an object is created.
You never are required to write a constructor for a class to make a class that compiles
without error; Java provides you with a default version if the class contains no explicit
constructor.
The Employee class constructor in Figure 3-29 takes no parameters; in other words, it is a
default constructor. You will learn about nondefault constructors that take parameters in the next
chapter.
97070_ch03_hr_110-169.indd 151 24/02/18 3:52 pm
152
Using Methods, Classes, and ObjectsC h a p t e r 3
Watch the video Constructors.
The false statement is #1. A default constructor is one that takes no parameters.
If you do not create a constructor for a class, Java creates a default constructor
for you. However, you can create a default constructor that replaces the
automatically supplied one.
tWO trUthS & a LIe
An Introduction to Using Constructors
1. In Java, you cannot write a default constructor; it must be supplied for you
automatically.
2. The automatically supplied default constructor sets all numeric fields to 0,
character fields to Unicode ‘ \u0000’, Boolean fields to false, and fields that
are object references to null.
3. When you write a constructor, it must have the same name as the class it
constructs, and it cannot have a return type.
A class can contain multiple constructors. You will learn how to overload constructors in
Chapter 4.
Adding a Constructor to a Class
1. Open the SpaService.java file that you created in a “You Do It” section earlier
in this chapter.
2. After the field declarations, and before the method declarations, insert an
explicit default constructor that sets serviceDescription to XXX and price
to 0. Because numeric fields in objects are set to 0 by default, the last
assignment is not really necessary. However, programmers sometimes
You Do It
(continues)
97070_ch03_hr_110-169.indd 152 24/02/18 3:52 pm
153
An Introduction to Using Constructors
code a statement like the one that sets price to 0 so that their intentions are
clear to people reading their programs.
public SpaService()
{
serviceDescription = "XXX";
price = 0;
}
3. Save the class and compile it.
4. Open the CreateSpaServices.java file. Comment out the seven statements
that prompt for, receive, and set the values for the secondService object
by placing double slashes at the start of their lines, as shown below. By
commenting out these lines, you change the program so that the user does not
enter values for the secondService object. Instead, the values assigned by the
constructor are the final values for the object.
// keyboard.nextLine();
// System.out.print("Enter service >> ");
// service = keyboard.nextLine();
// System.out.print("Enter price >> ");
// price = keyboard.nextDouble();
// secondService.setServiceDescription(service);
// secondService.setPrice(price);
5. Save the file, and then compile and execute it. Figure 3-30 shows a typical
execution. The firstService object contains values supplied by the user,
but the secondService object shows the values assigned during the object’s
construction.
(continued)
Figure 3-30 Typical execution of
CreateSpaServices program that uses
constructor values for the second object
97070_ch03_hr_110-169.indd 153 24/02/18 3:52 pm
154
Using Methods, Classes, and ObjectsC h a p t e r 3
Understanding that Classes are Data types
The classes that you create become data types. Programmers sometimes refer to classes
as abstract data types, or aDts. An abstract data type is a type whose implementation is
hidden and accessed through its public methods. A class that you create also can be called
a programmer-defined data type; in other words, it is a type that is not built into the lan-
guage. A class is a composite type—that is, a class is composed from smaller parts.
Java’s primitive types are not composite. Java has eight built-in primitive data types such as
int and double. Primitive types can also be called scalar types. You do not have to define
these simple types; the creators of Java already have done so. For example, when the int
type was first created, the programmers who designed it had to think about the following:
Q: What shall we call it?
A: int.
Q: What are its attributes?
A: An int is stored in four bytes; it holds whole-number values.
Q: What methods are needed by int?
A: A method to assign a value to a variable (for example, an int’s value might be 32).
Q: Any other methods?
A: Some operators to perform arithmetic with variables.
Q: Any other methods?
A: Of course, there are even more attributes and methods of an int, but these are a good
start.
Your job in constructing a new data type is similar. If you need a class for employees, you
should ask:
Q: What shall we call it?
A: Employee.
Q: What are its attributes?
A: It has an integer ID number, a String last name, and a double salary.
Q: What methods are needed by Employee?
A: A method to assign values to the data fields of an instance of this class.
Q: Any other methods?
A: A method to display data in an instance of this class.
Q: Any other methods?
A: Probably, but this is enough to get started.
97070_ch03_hr_110-169.indd 154 24/02/18 3:52 pm
155
Understanding that Classes Are Data Types
When you declare a primitive type object, you provide its type and an identifier. When
you declare an object from one of your classes, you do the same. After each exists, you
can use them in similar ways. For example, suppose you declare an int named myInt and
an Employee named myEmployee. Then each can be passed into a method, returned from
a method, or assigned to another object of the same data type. For example, Figure 3-31
shows a program in which the main() method uses two other methods. One method
accepts an Employee as a parameter, and the other returns an Employee. (The Employee
class is defined in Figure 3-25.)
Figure 3-31 The MethodsThatUseAnEmployee application
import java.util.Scanner;
class MethodsThatUseAnEmployee
{
public static void main (String args[])
{
Employee myEmployee;
myEmployee = getEmployeeData();
displayEmployee(myEmployee);
}
public static Employee getEmployeeData()
{
Employee tempEmp = new Employee();
int id;
double sal;
Scanner input = new Scanner(System.in);
System.out.print("Enter employee ID >> ");
id = input.nextInt();
tempEmp.setEmpNum(id);
System.out.print("Enter employee salary >> ");
sal = input.nextDouble();
tempEmp.setEmpSalary(sal);
return tempEmp;
}
public static void displayEmployee(Employee anEmp)
{
System.out.println("\nEmployee #" + anEmp.getEmpNum() +
" Salary is " + anEmp.getEmpSalary());
}
}
Employee is declared.
Value returned from
getEmployeeData() method is
assigned to myEmployee object.
myEmployee object is passed to
displayEmployee() method.
Return type is Employee.
Employee object is returned.
Parameter is
Employee type.
Figure 3-32 shows a typical execution of the program in Figure 3-31. You can see in this
sample program that an Employee is passed into and out of methods just like a primitive
object would be. Classes are not mysterious; they are just new data types that you
invent.
97070_ch03_hr_110-169.indd 155 24/02/18 3:52 pm
156
Using Methods, Classes, and ObjectsC h a p t e r 3
Notice in the application in Figure 3-31 that the Employee declared in the main() method is
not constructed there. An Employee is constructed in the getEmployeeData() method and
passed back to the main() method, where it is assigned to the myEmployee reference. The
Employee constructor could have been called in main(), but the values assigned would have
been overwritten after the call to getEmployeeData().
Figure 3-32 Typical execution of the MethodsThatUseAnEmployee application
The false statement is #2. An instantiated object can be passed into or returned
from a method.
tWO trUthS & a LIe
Understanding that Classes Are Data Types
1. When you declare a primitive variable or instantiate an object from a class,
you provide both a type and an identifier.
2. Unlike a primitive variable, an instantiated object cannot be passed into or
returned from a method.
3. The address of an instantiated object can be assigned to a declared refer-
ence of the same type.
Understanding that Classes Are Data Types
In this section, you modify the CreateSpaServices class to include a method for
data entry. This change makes the main() method shorter, gives you the ability to
reuse code, and shows that an object of the SpaService class data type can be
returned from a method as easily as a primitive data type.
You Do It
(continues)
97070_ch03_hr_110-169.indd 156 24/02/18 3:52 pm
157
Understanding that Classes Are Data Types
1. Open the CreateSpaServices.java file if it is not still open in your text editor.
2. Delete the declarations for service, price, and keyboard. Declarations for
these variables will now be part of the data entry method that you will create.
3. Delete the six statements that prompt the user and get values for the
firstService objects. Also delete the seven statements that prompt the
user and retrieve data for the secondService object. You commented out
these statements in the previous “You Do It” section.
4. In place of the statements you just deleted, insert two new statements. The first
sends a copy of the firstService object to a method named getData(). The
method returns a SpaService object that will be filled with appropriate data,
and this object is assigned to firstService. The second statement does the
same thing for secondService.
firstService = getData(firstService);
secondService = getData(secondService);
5. After the closing curly brace for the main() method, but before the clos-
ing curly brace for the class, start the following public static getData()
method. The header indicates that the method both accepts and returns a
SpaService object. Include the opening curly brace for the method, and make
declarations for service, price, and keyboard.
public static SpaService getData(SpaService service)
{
String service;
double price;
Scanner keyboard = new Scanner(System.in);
6. Continue the method by prompting the user for and accepting a service and its
price. Include a final call to nextLine() so that the input buffer is cleared after
the last numeric entry.
System.out.print("Enter service >> ");
service = keyboard.nextLine();
System.out.print("Enter price >> ");
price = keyboard.nextDouble();
keyboard.nextLine();
7. Finish the method by assigning the entered service and price to the SpaService
object parameter using the SpaService class’s setServiceDescription()
and setPrice() methods. Then return the full object to the main() method,
(continues)
(continued)
97070_ch03_hr_110-169.indd 157 24/02/18 3:52 pm
158
Using Methods, Classes, and ObjectsC h a p t e r 3
Don’t Do It
• Don’t place a semicolon at the end of a method header. After you get used to putting
semicolons at the end of every statement, it’s easy to start putting them in too many
places. Method headers never end in a semicolon.
• Don’t think “default constructor” means only the automatically supplied constructor.
Any constructor that does not accept parameters is a default constructor.
• Don’t think that a class’s methods must accept its own fields’ values as parameters or
return values to its own fields. When a class contains both fields and methods, each
method has direct access to every field within the class.
• Don’t create a class method that has a parameter with the same identifier as a class
field—yet. If you do, you will only be allowed to access the local variable within the
method, and you will not be able to access the field. You will be able to use the same
identifier and still access both values after you read the next chapter. For now, make
sure that the parameter in any method has a different identifier from any field.
where it is assigned to the object used in the method call. Add a closing curly
brace for the method.
service.setServiceDescription(service);
service.setPrice(price);
return service;
}
8. Save the file, compile it, and execute it. The execution looks no different from the
original version in Figure 3-28 earlier in this chapter, but by creating a method
that accepts an unfilled SpaService object and returns one filled with data, you
have made the main() method shorter and reused the data entry code.
(continued)
method
invoke
call
calling method
called method
abstraction
method header
declaration
method body
implementation
stub
access modifier
return type
return a value
fully qualified identifier
Key terms
97070_ch03_hr_110-169.indd 158 24/02/18 3:52 pm
159
Chapter Summary
arguments
parameters
implementation
hiding
interface
black box
local variable
signature
actual parameters
formal parameters
return statement
method’s type
unreachable
statements
dead code
is-a relationship
instantiation
class client
class user
extended
data fields
instance variable
private access
information hiding
mutator methods
accessor methods
nonstatic methods
instance methods
primary key
new operator
reference to an object
constructor
default constructor
abstract data type (ADT)
programmer-defined data
type
Chapter Summary
• A method is an encapsulated series of statements that carry out a task. Any method can
call, or invoke, another. You place a method within a class outside of any other methods.
• Methods must include a declaration (or header or definition) and a pair of curly braces
that enclose the method body. A method declaration contains optional access specifiers,
the return type for the method, the method name, and a pair of parentheses that might
contain a list of parameters.
• When a method can receive a parameter, its declaration must contain the parameter
type and an identifier within parentheses. A method can accept multiple parameters
separated with commas. The arguments sent to a method must match (both in number
and in type) the parameters listed in the method declaration.
• The return type for a method (the method’s type) can be any Java type, including void.
A return statement sends a value back to a calling method.
• Objects are concrete instances of classes. Objects gain their attributes from their classes,
and all objects have predictable attributes because they are members of certain classes.
In addition to their attributes, objects have methods associated with them, and every
object that is an instance of a class is assumed to possess the same methods.
• A class header contains an optional access specifier, the keyword class, and any legal
identifier you choose for the name of your class. A class contains fields, which are
frequently private, and methods, which are frequently public.
• Nonstatic instance methods operate uniquely for every object. Within a class, fields can
be placed before or after methods, and methods can be placed in any logical order.
• To create an object that is an instance of a class, you supply a type and an identifier,
and then you allocate computer memory for that object using the new operator and
the class constructor. With well-written object-oriented programming methods, using
implementation hiding—or the encapsulation of method details within a class—means
that the calling method needs to understand only the interface to the called method.
97070_ch03_hr_110-169.indd 159 24/02/18 3:52 pm
160
Using Methods, Classes, and ObjectsC h a p t e r 3
• A constructor establishes an object and provides specific initial values for the object’s
data fields. A constructor always has the same name as the class of which it is a member.
By default, numeric fields are set to 0 (zero), character fields are set to Unicode
‘\u0000’, Boolean fields are set to false, and object type fields are set to null.
• A class is an abstract, programmer-defined data type, similar to Java’s built-in, primitive
data types.
Review Questions
1. In Java, methods must include all of the following except _____________.
a. a call to another method
b. a declaration
c. curly braces
d. a body
2. All method declarations contain _____________.
a. arguments
b. one or more explicitly named access specifiers
c. parentheses
d. the keyword static
3. A public static method named computeSum() is located in ClassA. To call the
method from within ClassB, use the statement _____________.
a. ClassA.computeSum();
b. ClassB(computeSum());
c. ComputeSum(ClassA);
d. You cannot call computeSum() from within ClassB.
4. Which of the following method declarations is correct for a static method
named displayFacts() if the method receives an int argument?
a. public static int displayFacts()
b. public void displayFacts(int data)
c. public static void displayFacts(int data)
d. Two of these are correct.
5. The method with the declaration public static int aMethod(double d) is a
method type of _____________.
a. static
b. int
c. double
d. You cannot determine the method type.
97070_ch03_hr_110-169.indd 160 24/02/18 3:52 pm
161
Chapter Summary
6. Which of the following is a correct call to a method declared as public static
void aMethod(char code)?
a. void aMethod();
b. void aMethod('V');
c. aMethod(char 'M');
d. aMethod('Q');
7. A method is declared as public static void showResults(double d, int i).
Which of the following is a correct method call?
a. showResults(double d, int i);
b. showResults(12.2, 67);
c. showResults(4, 99.7);
d. Two of these are correct.
8. The method with the declaration public static char procedure(double d)
has a method type of _____________.
a. public
b. static
c. char
d. double
9. The method public static boolean testValue(int response) returns
_____________.
a. no value
b. an int value
c. a boolean value
d. You cannot determine what is returned.
10. Which of the following could be the last legally coded line of a method declared
as public static int getVal(double sum)?
a. return;
b. return 77;
c. return 2.3;
d. Any of these could be the last coded line of the method.
11. The nonstatic data components of a class often are referred to as the
_____________ of that class.
a. access types
b. instance variables
c. methods
d. objects
12. An object’s data items are also known as _____________.
a. fields
b. functions
c. themes
d. instances
13. You send messages or information to an object through its _____________.
a. fields
b. methods
c. classes
d. type
97070_ch03_hr_110-169.indd 161 24/02/18 3:52 pm
162
Using Methods, Classes, and ObjectsC h a p t e r 3
14. A program or class that instantiates objects of another prewritten class is a(n)
_____________.
a. class client
b. superclass
c. object
d. patron
15. The body of a class is always written _____________.
a. in a single line, as the first statement in a class
b. within parentheses
c. between curly braces
d. as a method call
16. Most class data fields are _____________.
a. private
b. public
c. static
d. final
17. The concept of allowing a class’s private data to be changed only by a class’s own
methods is known as _____________.
a. structured logic
b. object orientation
c. information hiding
d. data masking
18. Suppose you declare an object as Book myJournal;. Before you store data in
myJournal, you _____________.
a. also must explicitly allocate memory for it
b. need not explicitly allocate memory for it
c. must explicitly allocate memory for it only if it has a constructor
d. can declare it to use no memory
19. If a class is named Student, the class constructor name is _____________.
a. any legal Java identifier
b. any legal Java identifier that begins with S
c. StudentConstructor
d. Student()
20. If you use the automatically supplied default constructor when you create an
object, _____________.
a. numeric fields are set to 0 (zero)
b. character fields are set to blank
c. Boolean fields are set to true
d. All of these are true.
97070_ch03_hr_110-169.indd 162 24/02/18 3:52 pm
163
Exercises
exercises
Programming Exercises
1. Suppose that you have created a program with only the following variables.
int x = 2;
int y = 3;
Suppose that you also have a method with the following header:
public static void mathMethod(int x)
Which of the following method calls are legal?
a. mathMethod(x);
b. mathMethod(y);
c. mathMethod(x, y);
d. mathMethod(x + y);
e. mathMethod(12L);
f. mathMethod(12);
g. mathMethod(12.2);
h. mathMethod();
i. mathMethod(a);
j. mathMethod(a / x);
2. Suppose that you have created a program with only the following variables.
int age = 34;
int weight = 180;
double height = 5.9;
Suppose that you also have a method with the following header:
public static void calculate(int age, double size)
Which of the following method calls are legal?
a. calculate(age, weight);
b. calculate(age, height);
c. calculate(weight, height);
d. calculate(height, age);
e. calculate(45.5, 120);
f. calculate(12, 120.2);
g. calculate(age, size);
h. calculate(2, 3);
i. calculate(age);
j. calculate(weight, weight);
3. Suppose that a class named Bicycle contains a private nonstatic integer named
height, a public nonstatic String named model, and a public static integer named
wheels. Which of the following are legal statements in a class named BicycleDemo
that has instantiated an object as Bicycle myBike = new Bicycle();?
a. myBike.height = 26;
b. myBike.model = "Cyclone";
c. myBike.wheels = 3;
d. myBike.model = 108;
e. Bicycle.height = 24;
f. Bicycle.model = "Hurricane";
g. Bicycle.int = 3;
h. Bicycle.model = 108;
i. Bicycle.wheels = 2;
j. Bicycle yourBike = myBike;
97070_ch03_hr_110-169.indd 163 24/02/18 3:52 pm
164
Using Methods, Classes, and ObjectsC h a p t e r 3
4. a. Create an application named NumbersDemo whose main() method holds two
integer variables. Assign values to the variables. In turn, pass each value to
methods named displayTwiceTheNumber(), displayNumberPlusFive(), and
displayNumberSquared(). Create each method to perform the task its name
implies. Save the application as NumbersDemo.java.
b. Modify the NumbersDemo class to accept the values of the two integers from a
user at the keyboard. Save the file as NumbersDemo2.java.
5. a. Create an application named Percentages whose main() method holds
two double variables. Assign values to the variables. Pass both variables to
a method named computePercent() that displays the two values and the
value of the first number as a percentage of the second one. For example, if
the numbers are 2.0 and 5.0, the method should display a statement similar
to “2.0 is 40 percent of 5.0.” Then call the method a second time, passing the
values in reverse order. Save the application as Percentages.java.
b. Modify the Percentages class to accept the values of the two doubles from a
user at the keyboard. Save the file as Percentages2.java.
6. To encourage good grades, Hermosa High School has decided to award each
student a bookstore credit that is 10 times the student’s grade point average. In
other words, a student with a 3.2 grade point average receives a $32 credit. Create
a class that prompts a student for a name and grade point average, and then
passes the values to a method that displays a descriptive message. The message
uses the student’s name, echoes the grade point average, and computes and
displays the credit. Save the application as BookstoreCredit.java.
7. There are 12 inches in a foot and 3 feet in a yard. Create a class named
InchConversion. Its main() method accepts a value in inches from a user at the
keyboard, and in turn passes the entered value to two methods. One converts the
value from inches to feet, and the other converts the same value from inches to
yards. Each method displays the results with appropriate explanation. Save the
application as InchConversion.java.
8. Assume that a gallon of paint covers about 350 square feet of wall space. Create
an application with a main() method that prompts the user for the length, width,
and height of a rectangular room. Pass these three values to a method that does
the following:
• Calculates the wall area for a room
• Passes the calculated wall area to another method that calculates and returns
the number of gallons of paint needed
• Displays the number of gallons needed
• Computes the price based on a paint price of $32 per gallon, assuming that
the painter can buy any fraction of a gallon of paint at the same price as a
whole gallon
• Returns the price to the main() method
97070_ch03_hr_110-169.indd 164 24/02/18 3:52 pm
165
Exercises
The main() method displays the final price. For example, the cost to paint
a 15-by-20-foot room with 10-foot ceilings is $64. Save the application as
PaintCalculator.java.
9. The Harrison Group Life Insurance company computes annual policy premiums
based on the age the customer turns in the current calendar year. The premium
is computed by taking the decade of the customer’s age, adding 15 to it, and
multiplying by 20. For example, a 34-year-old would pay $360, which is calculated
by adding the decades (3) to 15, and then multiplying by 20. Write an application
that prompts a user for the current year and a birth year. Pass both to a method
that calculates and returns the premium amount, and then display the returned
amount. Save the application as Insurance.java.
10. Herbert’s Home Repair estimates each job cost as the cost of materials plus $35
per hour while on the job, plus $12 per hour for travel time to the job site. Create
a class that contains a main() method that prompts the user for the name of a
job (for example, Smith bathroom remodel), the cost of materials, the number of
hours of work required, and the number of hours travel time. Pass the numeric
data to a method that computes estimate for the job and returns the computed
value to the main() method where the job name and estimated price are
displayed. Save the program as JobPricing.java.
11. a. Create a class named Sandwich. Data fields include a String for the main
ingredient (such as tuna), a String for bread type (such as wheat), and a
double for price (such as 4.99). Include methods to get and set values for
each of these fields. Save the class as Sandwich.java.
b. Create an application named TestSandwich that instantiates one Sandwich
object and demonstrates the use of the set and get methods. Save this
application as TestSandwich.java.
12. a. Create a class named Student that has fields for an ID number, number
of credit hours earned, and number of points earned. (For example,
many schools compute grade point averages based on a scale of 4, so a
three-credit-hour class in which a student earns an A is worth 12 points.)
Include methods to assign values to all fields. A Student also has a field for
grade point average. Include a method to compute the grade point average
field by dividing points by credit hours earned. Write methods to display the
values in each Student field. Save this class as Student.java.
b. Write a class named ShowStudent that instantiates a Student object from the
class you created and assign values to its fields. Compute the Student grade
point average, and then display all the values associated with the Student.
Save the application as ShowStudent.java.
c. Create a constructor for the Student class you created. The constructor should
initialize each Student’s ID number to 9999, his or her points earned to 12, and
credit hours to 3 (resulting in a grade point average of 4.0). Write a program
that demonstrates that the constructor works by instantiating an object and
displaying the initial values. Save the application as ShowStudent2.java.
97070_ch03_hr_110-169.indd 165 24/02/18 3:52 pm
166
Using Methods, Classes, and ObjectsC h a p t e r 3
13. a. Create a class named Lease with fields that hold an apartment tenant’s name,
apartment number, monthly rent amount, and term of the lease in months.
Include a constructor that initializes the name to “XXX”, the apartment
number to 0, the rent to 1000, and the term to 12. Also include methods to
get and set each of the fields. Include a nonstatic method named addPetFee()
that adds $10 to the monthly rent value and calls a static method named
explainPetPolicy() that explains the pet fee. Save the class as Lease.java.
b. Create a class named TestLease whose main() method declares four Lease
objects. Call a getData() method three times. Within the method, prompt a
user for values for each field for a Lease, and return a Lease object to the main()
method where it is assigned to one of main()’s Lease objects. Do not prompt the
user for values for the fourth Lease object, but let it continue to hold the default
values. Then, in main(), pass one of the Lease objects to a showValues() method
that displays the data. Then call the addPetFee() method using the passed Lease
object and confirm that the fee explanation statement is displayed. Next, call the
showValues() method for the Lease object again and confirm that the pet fee has
been added to the rent. Finally, call the showValues() method with each of the
other three objects; confirm that two hold the values you supplied as input and
one holds the constructor default values. Save the application as TestLease.java.
Debugging Exercises
1. Each of the following files saved in the Chapter03 folder in your downloadable student
files has syntax and/or logic errors. In each case, determine and fix the problem. After
you correct the errors, save each file using the same filename preceded with Fix. For
example, DebugThree1.java will become FixDebugThree1.java.
a. DebugThree1.java
b. DebugThree2.java
c. DebugThree3.java
d. DebugThree4.java
When you change a filename, remember to change every instance of the class name within the file so
that it matches the new filename. In Java, the filename and class name must always match.
Game Zone
1. Playing cards are used in many computer games, including versions of such
classics as solitaire, hearts, and poker. Design a Card class that contains a
character data field to hold a suit (s for spades, h for hearts, d for diamonds,
or c for clubs) and an integer data field for a value from 1 to 13. (When you
learn more about string handling in the chapter “Characters, Strings, and the
StringBuilder,” you can modify the class to hold words for the suits, such as
spades or hearts, as well as words for some of the values—for example, ace or
king.) Include get and set methods for each field. Save the class as Card.java.
97070_ch03_hr_110-169.indd 166 24/02/18 3:52 pm
167
Write an application that randomly selects two playing cards and displays their
values. Simply assign a suit to each of the cards, but generate a random number
for each card’s value. Appendix D contains information about generating random
numbers. To fully understand the process, you must learn more about Java
classes and methods. However, for now, you can copy the following statements to
generate a random number between 1 and 13 and assign it to a variable:
final int CARDS_IN_SUIT = 13;
myValue = ((int)(Math.random() * 100) % CARDS_IN_SUIT + 1);
After reading the chapter “Making Decisions,” you will be able to have the game
determine the higher card. For now, just observe how the card values change as you
execute the program multiple times. Save the application as PickTwoCards.java.
You use the Math.random() function to generate a random number. The function call uses only a
class and method name—no object—so you know the random() method must be a static method.
2. Computer games often contain different characters or creatures. For example,
you might design a game in which alien beings possess specific characteristics
such as color, number of eyes, or number of lives. Design a character for a game,
creating a class to hold at least three attributes for the character. Include methods
to get and set each of the character’s attributes. Save the file as MyCharacter.
java. Then write an application in which you create at least two characters.
In turn, pass each character to a display method that displays the character’s
attributes. Save the application as TwoCharacters.java.
Case Problems
1. a. Carly’s Catering provides meals for parties and special events. In Chapter 2, you
wrote an application that prompts the user for the number of guests attending
an event, displays the company motto with a border, and then displays the price
of the event and whether the event is a large one. Now modify the program so
that the main() method contains only three executable statements that each
call a method as follows:
• The first executable statement calls a public static int method that
prompts the user for the number of guests and returns the value to the
main() method.
• The second executable statement calls a public static void method
that displays the company motto with the border.
• The last executable statement passes the number of guests to a public
static void method that computes the price of the event, displays the
price, and displays whether the event is a large event.
Save the file as CarlysEventPriceWithMethods.java.
Exercises
97070_ch03_hr_110-169.indd 167 24/02/18 3:52 pm
168
Using Methods, Classes, and ObjectsC h a p t e r 3
b. Create a class to hold Event data for Carly’s Catering. The class contains:
• Two public final static fields that hold the price per guest ($35) and
the cutoff value for a large event (50 guests)
• Three private fields that hold an event number, number of guests for
the event, and the price. The event number is stored as a String because
Carly plans to assign event numbers such as M312.
• Two public set methods that set the event number (setEventNumber())
and the number of guests (setGuests()). The price does not have a set
method because the setGuests() method will calculate the price as the
number of guests multiplied by the price per guest every time the number
of guests is set.
• Three public get methods that return the values in the three nonstatic
fields.
Save the file as Event.java.
c. Use the CarlysEventPriceWithMethods class you created in Step 1a as a
starting point for a program that demonstrates the Event class you created in
Step 1b, but make the following changes:
• You already have a method that gets a number of guests from a user; now
add a method that gets an event number. The main() method should
declare an Event object, call the two data entry methods, and use their
returned values to set the fields in the Event object.
• Call the method from the CarlysEventPriceWithMethods class that
displays the company motto with the border. The method is accessible
because it is public, but you must fully qualify the name because it is in
another class.
• Revise the method that displays the event details so that it accepts
the newly created Event object. The method should display the event
number, and it should still display the number of guests, the price per
guest, the total price, and whether the event is a large event.
Save the program as EventDemo.java.
2. a. Sammy’s Seashore Supplies rents beach equipment such as kayaks, canoes,
beach chairs, and umbrellas to tourists. In Chapter 2, you wrote an application
that prompts the user for the number of minutes a piece of sports equipment
was rented, displays the company motto with a border, and displays the price
for the rental. Now modify the program so that the main() method contains
only three executable statements that each call a method as follows:
• The first executable statement calls a method that prompts the user for
the rental time in minutes and returns the value to the main() method.
97070_ch03_hr_110-169.indd 168 24/02/18 3:52 pm
169
• The second executable statement calls a method that displays the
company motto with the border.
• The last executable statement passes the number of minutes to a method
that computes the hours, extra minutes, and price for the rental, and then
displays all the details.
Save the file as SammysRentalPriceWithMethods.java.
b. Create a class to hold Rental data for Sammy’s Seashore Supplies. The class
contains:
• Two public final static fields that hold the number of minutes in an
hour and the hourly rental rate ($40)
• Four private fields that hold a contract number, number of hours for
the rental, number of minutes over an hour, and the price. The contract
number is stored as a String because Sammy plans to assign contract
numbers such as K681.
• Two public set methods. One sets the contract number
(setContractNumber()). The other is named setHoursAndMinutes(),
and it accepts the number of minutes for the rental and then sets the
hours, extra minutes over an hour, and the total price. Recall from
Chapter 2 that the price is $40 per hour plus $1 for every extra minute.
• Four public get methods that return the values in the four nonstatic
fields.
Save the file as Rental.java.
c. Use the SammysRentalPriceWithMethods class you created in Step 2a as a
starting point for a program that demonstrates the Rental class you created
in Step 2b, but make the following changes:
• You already have a method that gets a number of minutes from a user;
now add a method that gets a contract number. The main() method
should declare a Rental object, call the two data entry methods, and use
their returned values to set the fields in the Rental object.
• From the SammysRentalPriceWithMethods class, call the RentalDemo
method that displays the company motto with the border. The method
is accessible because it is public, but you must fully qualify the name
because it is in another class.
• Revise the method that displays the rental details so that it accepts the
newly created Rental object. The method should display the contract
number, and it still should display the hours and minutes, the hourly rate,
and the total price.
Save the program as RentalDemo.java.
Exercises
97070_ch03_hr_110-169.indd 169 24/02/18 3:52 pm
C h a p t e r 4
More Object
Concepts
Upon completion of this chapter, you will be able to:
Understand blocks and scope
Overload a method
Avoid ambiguity
Create and call constructors with parameters
Use the this reference
Use static fields
Use automatically imported, prewritten constants
and methods
Use composition and nest classes
97070_ch04_hr_170-229.indd 170 24/02/18 3:55 pm
171
Understanding Blocks and Scope
A block can exist entirely within another block or entirely outside and separate from
another block, but blocks can never overlap. For example, if a method contains two opening
curly braces, indicating the start of two blocks, the first opening brace and last closing
brace comprise the pair that defines the outer block, and the second opening brace and first
closing brace comprise the pair that defines the inner block.
You cannot refer to a variable outside the block in which it is declared. As you learned in
Chapter 3, the portion of a program within which you can refer to a variable is the variable’s
scope; in this part of the program, the variable exists and can be accessed using its
unqualified name. In Java, a variable comes into existence, or comes into scope, when you
declare it, and a variable ceases to exist, or goes out of scope, at the end of the block
in which it is declared. Programmers say that a Java variable’s scope level is its block.
Although you can create as many variables and blocks as you need within any program, it is
not wise to do so without a reason. The use of unnecessary variables and blocks increases
the likelihood of improper use of variable names and scope.
Understanding Blocks and Scope
Within any class or method, the code between a pair of curly braces is called a block (or,
more completely, a code block). For example, the method shown in Figure 4-1 contains two
blocks. An outer block begins at the first opening curly brace and ends at the last closing
curly brace, at the end of the method. The inner block starts with the second opening curly
brace and ends with the first closing curly brace. It contains two executable statements: the
declaration of anotherNumber and a println() statement. The inner block is nested, or
contained entirely, within the outer block.
Figure 4-1 A method with nested blocks
public static void methodWithNestedBlocks()
{
int aNumber = 10;
System.out.println
("In outer block, aNumber is " + aNumber);
{
int anotherNumber = 512;
System.out.println
("In inner block, aNumber is " +
aNumber + " and another number is " +
anotherNumber);
}
System.out.println("In outer block, aNumber is " + aNumber);
}
aNumber comes into existence
anotherNumber comes into existence
anotherNumber ceases to exist; it goes out of scope
aNumber ceases to exist; it goes out of scope
Outer block
starts with
opening brace
Inner block
starts with next
opening brace
Outer block
ends
Inner block ends
97070_ch04_hr_170-229.indd 171 24/02/18 3:55 pm
172
More Object Concepts C h a p t e r 4
In the methodWithNestedBlocks() method shown in Figure 4-1, the variable aNumber exists
from the point of its declaration until the end of the method. This means aNumber exists
both in the outer block and in the inner block and can be used anywhere in the method.
The variable anotherNumber comes into existence within the inner block; anotherNumber
goes out of scope when the inner block ends and cannot be used beyond its block.
Figure 4-2 shows the output when the method in Figure 4-1 executes.
Figure 4-2 Output produced by application that uses methodWithNestedBlocks()
The program that produces the output shown in Figure 4-2 is available in your downloadable
student files.
Figure 4-3 The methodWithInvalidStatements() method
public static void methodWithInvalidStatements()
{
aNumber = 75;
int aNumber = 22;
aNumber = 6;
anotherNumber = 489;
{
anotherNumber = 165;
int anotherNumber = 99;
anotherNumber = 2;
}
aNumber = 50;
anotherNumber = 34;
}
aNumber = 29;
Illegal statement; this variable has not been declared yet
Illegal statement; this variable has not been declared yet
Illegal statement; this variable still has not been declared
Illegal statement; this variable was declared in the inner block
and has gone out of scope here
Illegal statement; this variable has gone out of scope
You cannot use a data item that is not in scope. For example, Figure 4-3 shows a method
that contains two blocks and some valid and invalid statements. The opening and closing
braces for each block are vertically aligned. You are not required to vertically align the
opening and closing braces for a block, but your programs are much easier to read if you do.
The first assignment statement in the first, outer block in Figure 4-3, aNumber = 75;, is
invalid because aNumber has not been declared yet. Similarly, the statements that attempt
to assign 489 and 165 to anotherNumber are invalid because anotherNumber has not been
declared yet. After anotherNumber is declared, it can be used for the remainder of the
inner block, but the statement that attempts to assign 34 to it is outside the block in which
97070_ch04_hr_170-229.indd 172 24/02/18 3:55 pm
173
Understanding Blocks and Scope
anotherNumber was declared. The last statement in Figure 4-3, aNumber = 29;, does not
work because it falls outside the block in which aNumber was declared; it actually falls
outside the entire methodWithInvalidStatements() method.
Within a method, you can declare a variable with the same name multiple times, as long
as each declaration is in its own nonoverlapping block. For example, the two declarations
of variables named someVar in Figure 4-4 are valid because each variable is contained
within its own block. The first instance of someVar has gone out of scope before the second
instance comes into scope.
Many programmers would recommend that you do not declare variables with the same name in the
same method even if doing so is legal because the variables exist in separate blocks. You should follow
the recommendations of your instructor or supervisor.
You cannot declare the same variable name more than once within a block, even if a block
contains other blocks. When you declare a variable more than once in a block, you are
attempting to redeclare the variable, which is an illegal action. For example, in Figure 4-5,
the second declaration of aValue causes an error because you cannot declare the same
variable twice within the outer block of the method. By the same reasoning, the third
declaration of aValue is also invalid, even though it appears within a new block. The block
that contains the third declaration is entirely within the outer block, so the first declaration
of aValue has not gone out of scope.
Figure 4-4 The twoDeclarations() method
public static void twoDeclarations()
{
{
int someVar = 7;
System.out.println(someVar);
}
{
int someVar = 845;
System.out.println(someVar);
}
}
This variable is totally different from the one
in the previous block even though their
identifiers are the same.
This variable will go out of scope at the next
closing curly brace.
Don’t declare blocks for no reason. A new
block starts here only to demonstrate scope.
Figure 4-5 The invalidRedeclarationMethod()
public static void invalidRedeclarationMethod()
{
int aValue = 35;
int aValue = 44;
{
int anotherValue = 0;
int aValue = 10;
}
}
Invalid redeclaration of aValue because it is
in the same block as the first declaration
Invalid redeclaration of aValue; even though this
is a new block, this block is inside the first block
97070_ch04_hr_170-229.indd 173 24/02/18 3:55 pm
174
More Object Concepts C h a p t e r 4
Although you cannot declare a variable twice within the same block, you can declare a
variable within one method of a class and use the same variable name within another
method of the class. In this case, the variable declared inside each method resides in its own
location in computer memory. When you use the variable’s name within the method in
which it is declared, it takes precedence over, or overrides, any other variable with the same
name in another method. In other words, a locally declared variable always masks or hides
another variable with the same name elsewhere in the class.
For example, consider the class in Figure 4-6. In the main() method of the
OverridingVariable class, aNumber is declared and assigned the value 10. When the
program calls firstMethod(), a new variable is declared with the same name but
with a different memory address and a new value. The new variable exists only within
firstMethod(), where it is displayed holding the value 77. After firstMethod() executes
and the logic returns to the main() method, the original aNumber is displayed, containing
10. When aNumber is passed to secondMethod(), a copy is made within the method.
This copy has the same identifier as the original aNumber, but a different memory
address. So, within secondMethod(), when the value is changed to 862 and displayed, it
has no effect on the original variable in main(). When the logic returns to main() after
secondMethod(), the original value is displayed again. Examine the output in Figure 4-7
to understand the sequence of events.
Figure 4-6 The OverridingVariable class
public class OverridingVariable
{
public static void main(String[] args)
{
int aNumber = 10;
System.out.println("In main(), aNumber is " + aNumber);
firstMethod();
System.out.println("Back in main(), aNumber is " + aNumber);
secondMethod(aNumber);
System.out.println("Back in main() again, aNumber is " + aNumber);
}
public static void firstMethod()
{
int aNumber = 77;
System.out.println("In firstMethod(), aNumber is "
+ aNumber);
}
public static void secondMethod(int aNumber)
{
System.out.println("In secondMethod(), at first " +
"aNumber is " + aNumber);
aNumber = 862;
System.out.println("In secondMethod(), after an assignment " +
"aNumber is " + aNumber);
}
}
aNumber is declared in
main().
Whenever aNumber
is used in main(), it
retains its value of 10.
This aNumber resides at a different
memory address from the one in main().
It is declared locally in this method.
This aNumber also resides at a different
memory address from the one in main().
It is declared locally in this method.
97070_ch04_hr_170-229.indd 174 24/02/18 3:55 pm
175
Understanding Blocks and Scope
When they have the same name, variables within methods of a class override or hide the
class’s fields. Java calls this phenomenon shadowing; a variable that hides another shadows
it. For example, Figure 4-8 shows an Employee class that contains two instance variables
and three void methods. The setValues() method provides values for the two class
instance fields. Whenever the method named methodThatUsesInstanceAttributes() is
used with an Employee object, the instance values for empNum and empPayRate are used.
However, when the other method, methodThatUsesLocalVariables(), is used with an
Employee object, the local variable values within the method, 33333 and 555.55, shadow the
class’s instance variables. Figure 4-9 shows a short application that declares an Employee
object and uses each method.
In the methodThatUsesLocalVariables() method in Figure 4-8, the locally declared
empNum and empPayRate are assigned 33333 and 555.55, respectively. These local variables
are said to be closer in scope than the variables with the same name at the top of the
class that are shadowed. When you write programs, you can choose to avoid confusing
situations that arise when you give the same name to a class’s instance field and to a local
method variable. But, if you do use the same name, be aware that within the method, the
method’s local variable overrides the instance variable. Figure 4-10 shows the output of the
program in Figure 4-9.
Figure 4-7 Output of the OverridingVariable application
Object-oriented programmers also use the term override when a child class contains a field or method
that has the same name as one in the parent class. You will learn more about inheritance in the chapters
“Introduction to Inheritance” and “Advanced Inheritance Concepts.”
You are familiar with local names overriding names defined elsewhere. If someone in your household is
named Eric, and someone in the house next door also is named Eric, members of your household who
talk about Eric are referring to the local version. They would add a qualifier such as Eric Johnson or Eric
next door to refer to the nonlocal version.
97070_ch04_hr_170-229.indd 175 24/02/18 3:55 pm
176
More Object Concepts C h a p t e r 4
Figure 4-10 Output of the TestEmployeeMethods application
Figure 4-8 The Employee class
public class Employee
{
private int empNum;
private double empPayRate;
public void setValues()
{
empNum = 111;
empPayRate = 22.22;
}
public void methodThatUsesInstanceAttributes()
{
System.out.println("Employee number is " + empNum);
System.out.println("Pay rate is " + empPayRate);
}
public void methodThatUsesLocalVariables()
{
int empNum = 33333;
double empPayRate = 555.55;
System.out.println("Employee number is " + empNum);
System.out.println("Pay rate is " + empPayRate);
}
}
This method uses the class fields.
This method also uses
the class fields.
This method uses the locally declared
variables that happen to have the
same names as the class fields.
public class TestEmployeeMethods
{
public static void main(String[] args)
{
Employee aWorker = new Employee();
aWorker.setValues();
aWorker.methodThatUsesInstanceAttributes();
aWorker.methodThatUsesLocalVariables();
}
}
Figure 4-9 The TestEmployeeMethods application
97070_ch04_hr_170-229.indd 176 24/02/18 3:55 pm
177
Understanding Blocks and Scope
Programmers frequently use the same name for an instance field and a parameter to a method in the
same class simply because it is the “best name” to use; in these cases, the programmer must use the
this reference, which you will learn about later in this chapter.
It is important to understand the impact that blocks and methods have on your variables.
Variables and fields with the same names represent different memory locations when they
are declared within different scopes. After you understand the scope of variables, you can
avoid many potential errors in your programs.
The false statement is #3. When they have the same name, variables within meth-
ods of a class override a class’s instance variables.
tWO trUthS & a LIe
Understanding Blocks and Scope
1. A variable ceases to exist, or goes out of scope, at the end of the block in
which it is declared.
2. You cannot declare the same variable name more than once within a block,
even if a block contains other blocks.
3. A class’s instance variables override locally declared variables with the same
names that are declared within the class’s methods.
Demonstrating Scope
In this section, you create a method with several blocks to demonstrate block scope.
1. Start your text editor, and then open a new document, if necessary.
2. Type the first few lines for a class named DemoBlock:
public class DemoBlock
{
public static void main(String[] args)
{
3. Add a statement that displays the purpose of the program:
System.out.println("Demonstrating block scope");
You Do It
(continues)
97070_ch04_hr_170-229.indd 177 24/02/18 3:55 pm
178
More Object Concepts C h a p t e r 4
4. On a new line, declare an integer named x, assign the value 1111 to it, and
display its value:
int x = 1111;
System.out.println("In first block x is " + x);
5. Begin a new block by typing an opening curly brace on the next line. Within the
new block, declare another integer named y, and display x and y. The value of x
is 1111, and the value of y is 2222:
{
int y = 2222;
System.out.println("In second block x is " + x);
System.out.println("In second block y is " + y);
}
6. On the next line, begin another new block. Within this new block, declare a new
integer with the same name as the integer declared in the previous block; then
display x and y. The value of y is 3333. Call a method named demoMethod(),
and display x and y again. Even though you will include statements within
demoMethod() that assign different values to x and y, the x and y displayed
here are still 1111 and 3333:
{
int y = 3333;
System.out.println("In third block x is " + x);
System.out.println("In third block y is " + y);
demoMethod();
System.out.println("After method x is " + x);
System.out.println("After method block y is " + y);
}
7. On a new line after the end of the block, type the following:
System.out.println("At the end x is " + x);
This last statement in the main() method displays the value of x, which is still
1111. Type a closing curly brace.
8. Finally, enter the following demoMethod() that creates its own x and y variables,
assigns different values, and then displays them:
public static void demoMethod()
{
int x = 8888, y = 9999;
System.out.println("In demoMethod x is " + x);
System.out.println("In demoMethod block y is " + y);
}
(continues)
(continued)
97070_ch04_hr_170-229.indd 178 24/02/18 3:55 pm
179
Overloading a Method
9. Type the final closing curly brace, and then save the file as DemoBlock.java.
At the command prompt, compile the file by typing the command
javac DemoBlock.java. If necessary, correct any errors, and compile
the program again.
10. Run the program by typing the
command java DemoBlock. Your
output should look like Figure 4-11.
Make certain you understand how the
values of x and y are determined in
each line of output.
11. To gain a more complete
understanding of blocks and scope
levels, change the values of x and y
in several locations throughout the
program, and try to predict the exact
output before resaving, recompiling,
and rerunning the program.
(continued)
Overloading a Method
Overloading a method allows you to use one identifier to execute diverse tasks. In Java, it
more specifically means writing multiple methods in the same scope that have the same
name but different parameter lists. In other words, you overload methods by providing
different parameter lists for methods with the same name. In overloaded methods, the
parameter identifiers do not have to be different, but the parameter lists must satisfy one
or both of these conditions:
• The lists must have different numbers of parameters. For example, one list could
have one double, another list could have two doubles, and a third list could have
10 doubles.
• The lists must have parameter data types in different orders. For example, one list could
have two doubles, another could have an int followed by a double, and a third could
have a double followed by an int.
When you use the English language, you overload words all the time. When you say open
the door, open your eyes, and open a computer file, you are talking about three very different
actions using very different methods and producing very different results. However, anyone
who speaks English fluently has no trouble understanding your meaning because the verb
open is understood in the context of the noun that follows it.
Figure 4-11 Output of the DemoBlock
application
97070_ch04_hr_170-229.indd 179 24/02/18 3:55 pm
180
More Object Concepts C h a p t e r 4
When you overload a Java method, multiple methods share a name, and the compiler
understands which one to use based on the arguments in the method call. For example,
suppose you create a class method to apply a simple interest rate to a bank balance. The
method is named calculateInterest(); it receives two double parameters—the balance
and the interest rate—and displays the multiplied result. Figure 4-12 shows the method.
When an application calls the calculateInterest() method and passes two double
values, as in calculateInterest(1000.00, 0.04), the interest is calculated correctly as
4% of $1,000.00.
Assume, however, that different users want to calculate interest using different argument
types. Some users who want to indicate an interest rate of 4% might use 0.04; others might
use 4 and assume that it means 4%. When the calculateInterest() method is called with
the arguments 1000.00 and 0.04, the interest is calculated correctly as 40.00. When the
method is called using 1000.00 and 4, the method works because the integer argument
is promoted to a double, but the interest is calculated incorrectly as 4000.00, which is
100 times too high.
A solution for the conflicting use of numbers to represent parameter values is to overload
the calculateInterest() method. For example, in addition to the calculateInterest()
method shown in Figure 4-12, you could add the method shown in Figure 4-13.
Figure 4-13 The calculateInterest() method with a double parameter and an int parameter
public static void calculateInterest(double bal, int rate)
{
double interest, rateAsPercent;
rateAsPercent = rate / 100.0;
interest = bal * rateAsPercent;
System.out.println("Simple interest on $" +
bal + " at " + rate + "% rate is " +
interest);
}
Notice the data type
for rate.
Dividing by 100.0 converts rate
to its percent equivalent.
public static void calculateInterest(double bal, double rate)
{
double interest;
interest = bal * rate;
System.out.println("Simple interest on $" + bal +
" at " + rate + "% rate is " + interest);
}
Figure 4-12 The calculateInterest() method with two double parameters
97070_ch04_hr_170-229.indd 180 24/02/18 3:55 pm
181
Overloading a Method
In Figure 4-13, note that rateAsPercent is calculated by dividing by 100.0 and not by 100. If two integers
are divided, the result is a truncated integer; dividing by a double 100.0 causes the result to be a double.
Alternatively, you could use an explicit cast such as rateAsPercent = (double)rate / 100.
If an application calls the method calculateInterest() using two double arguments—for
example, calculateInterest(1000.00, 0.04)—the first version of the method, the one
shown in Figure 4-12, executes. However, if an integer is used as the second argument in
a call to calculateInterest()—as in calculateInterest(1000.00, 4)—the second
version of the method, the one shown in Figure 4-13, executes. In this second example,
the whole number rate figure is correctly divided by 100.0 before it is used to determine
the interest earned.
Of course, you could use methods with different names to solve the dilemma of producing
an accurate interest figure—for example, calculateInterestUsingDouble() and
calculateInterestUsingInt(). However, it is easier and more convenient for programmers
who use your methods to remember just one method name they can use in the form that is
most appropriate for their programs. It is convenient to be able to use one reasonable name
for tasks that are functionally identical except for the argument types that can be passed to
them. The compiler knows which method version to call based on the passed arguments.
In Chapter 3, you learned that methods such as println() have been created to accept different
argument types (for example, a String, a numeric value, or no argument) and that this feature is called
method overloading.
Automatic Type Promotion in Method Calls
In Chapter 2, you learned that Java casts variables to a unifying type when you perform
arithmetic with unlike types. For example, when you multiply an int and a double, the
result is a double. In a similar way, Java can promote one data type to another when you
pass a parameter to a method. For example, if a method has a double parameter and you
pass in an integer, the integer is promoted to a double. Recall that the order of promotion
is double, float, long, and int. Any type in this list can be promoted to any type that
precedes it.
When an application contains just one version of a method, you can call the method using
a parameter of the correct data type or one that can be promoted to the correct data type.
For example, consider the simple method shown in Figure 4-14.
public static void simpleMethod(double d)
{
System.out.println("Method receives double parameter");
}
Figure 4-14 The simpleMethod() method with a double parameter
97070_ch04_hr_170-229.indd 181 24/02/18 3:55 pm
182
More Object Concepts C h a p t e r 4
If you write an application in which you declare doubleValue as a double variable and
intValue as an int variable (as shown in Figure 4-15), either of the two method calls
simpleMethod(doubleValue); or simpleMethod(intValue); results in the output
Method receives double parameter.
Figure 4-15 The CallSimpleMethod application that calls simpleMethod() with a
double and an int
public class CallSimpleMethod
{
public static void main(String[] args)
{
double doubleValue = 45.67;
int intValue = 17;
simpleMethod(doubleValue);
simpleMethod(intValue);
}
public static void simpleMethod(double d)
{
System.out.println("Method receives double parameter");
}
}
Either a double or an
int can be sent to a
method that accepts a
double.
The method call that uses the integer in
Figure 4-15 works because the integer is cast
as (or promoted to) a double. Figure 4-16
shows output of the program.
Note that if the method with the declaration
void simpleMethod(double d) did not exist,
but the declaration void simpleMethod(int i)
did exist, then the method call simpleMethod(doubleValue); would fail. Although an int
can be promoted to a double, a double is not automatically reduced to an int. This makes
sense if you consider the potential loss of information when a double value is reduced to an
integer.
Suppose that you add an overloaded version of simpleMethod() to the program in
Figure 4-15. This version accepts an integer parameter, as shown in Figure 4-17.
When you properly overload a method, you can call it providing different argument lists,
and the appropriate version of the method executes. In the program version in Figure 4-17,
Figure 4-16 Output of the
CallSimpleMethod application
97070_ch04_hr_170-229.indd 182 24/02/18 3:55 pm
183
Overloading a Method
the output changes when you call
simpleMethod(intValue);. Instead
of promoting an integer argument to a
double, the compiler recognizes a more
exact match for the method call that
uses the integer argument, so it calls the
version of the method that produces
the output Method receives integer
parameter. Figure 4-18 shows the output.
Figure 4-17 The CallSimpleMethodAgain application that calls simpleMethod()
with a double and an int
public class CallSimpleMethodAgain
{
public static void main(String[] args)
{
double doubleValue = 45.67;
int intValue = 17;
simpleMethod(doubleValue);
simpleMethod(intValue);
}
public static void simpleMethod(double d)
{
System.out.println("Method receives double parameter");
}
public static void simpleMethod(int d)
{
System.out.println("Method receives integer parameter");
}
}
The call with an int
argument uses the
method that is a better
match when it is
available.
Figure 4-18 Output of the
CallSimpleMethodAgain application
The false statement is #3. Overloading methods is preferable to using unique
identifiers because it is convenient for programmers to use one reasonable name
for tasks that are functionally identical, except for the argument types that can be
passed to them.
tWO trUthS & a LIe
Overloading a Method
1. When you overload Java methods, you write multiple methods with a shared
name.
2. When you overload Java methods, the methods are called using different
arguments.
3. Instead of overloading methods, it is preferable to write methods with unique
identifiers.
97070_ch04_hr_170-229.indd 183 24/02/18 3:55 pm
184
More Object Concepts C h a p t e r 4
Overloading Methods
In this section, you overload methods to display dates. The date-displaying methods
might be used by many different applications in an organization, such as those that
schedule jobs, appointments, and employee reviews. The methods take one, two,
or three integer arguments. If there is one argument, it is the month, and the date
becomes the first day of the given month in the year 2018. If there are two argu-
ments, they are the month and the day in the year 2018. Three arguments represent
the month, day, and year.
1. Open a new file in your text editor.
2. Begin the following DemoOverload class with three integer variables to test the
method and three calls to a displayDate() method:
public class DemoOverload
{
public static void main(String[] args)
{
int month = 6, day = 24, year = 2019;
displayDate(month);
displayDate(month, day);
displayDate(month, day, year);
}
3. Create the following displayDate() method that requires one parameter to
represent the month and uses default values for the day and year:
public static void displayDate(int mm)
{
System.out.println("Event date " + mm + "/1/2018");
}
4. Create the following displayDate() method that requires two parameters to
represent the month and day and uses a default value for the year:
public static void displayDate(int mm, int dd)
{
System.out.println("Event date " + mm + "/" + dd + "/2018");
}
You Do It
Instead of creating your own class to store dates, you can use the built-in Java class
LocalDate to handle dates. You work with the class later in this chapter. This exercise
provides you with some insight into considerations taken by the creators of Java’s built-in
LocalDate class.
(continues)
97070_ch04_hr_170-229.indd 184 24/02/18 3:55 pm
185
Learning About Ambiguity
5. Create the following displayDate() method that requires three parameters
used as the month, day, and year:
public static void displayDate(int mm, int dd, int yy)
{
System.out.println("Event date " + mm + "/" + dd + "/" + yy);
}
6. Type the closing curly brace for the DemoOverload class.
7. Save the file as DemoOverload.java.
8. Compile the program, correct any errors,
recompile if necessary, and then execute
the program. Figure 4-19 shows the
output. Notice that whether you call the
displayDate() method using one, two,
or three arguments, the date is displayed
correctly because you have successfully
overloaded the displayDate() method.
(continued)
Learning about ambiguity
Overloading methods is useful because you can use a single identifier to execute different
instructions depending on the arguments you send to the method. However, when you
overload methods, you risk creating an ambiguous situation—one in which the compiler
cannot determine which method to use. For example, consider the following overloaded
computeBalance() method declarations:
public static void computeBalance(double deposit)
public static void computeBalance(double withdrawal)
A program that contains these two methods will not compile. If it did compile, and
you made a method call such as computeBalance(100.00);, the compiler would not
know which method to use because both methods would be exact matches for your call.
Sometimes, it is hard to recognize potentially ambiguous situations. For example, consider
the following two method declarations:
public static void calculateInterest(int bal, double rate)
public static void calculateInterest(double bal, int rate)
Figure 4-19 Output of the
DemoOverload application
97070_ch04_hr_170-229.indd 185 24/02/18 3:55 pm
186
More Object Concepts C h a p t e r 4
These calculateInterest() methods have different types in their parameter lists, so a
program that contains these methods can compile. A call to calculateInterest() with
an int and a double argument (in that order) executes the first version of the method, and
a call to calculateInterest() with a double and an int argument executes the second
version of the method. With each of these calls, the compiler can find an exact match for
the arguments you send. However, if you call calculateInterest() using two integer
arguments, as in calculateInterest(300, 6);, an ambiguous situation arises because
there is no exact match for the method call. Because either of the two integers in the
method call can be promoted to a double, the call matches both versions of the method.
The compiler can’t determine which version of the calculateInterest() method to use,
and the program does not compile.
The two versions of calculateInterest() could coexist if no ambiguous calls were ever
made. An overloaded method with different parameters lists is not ambiguous on its own—
it becomes ambiguous only if you make an ambiguous method call. A program containing
a potentially ambiguous situation will run problem-free if you do not make any ambiguous
method calls.
It is important to remember that you can overload methods correctly by providing different
parameter lists for methods with the same name. Methods with identical names that have
identical parameter lists but different return types are not overloaded—they are illegal.
For example, the following two methods are illegal in the same class:
int aMethod(int x)
void aMethod(int x)
The compiler determines which of several versions of a method to call based on the
arguments in the method call, and does not consider the return type.
Watch the video Overloading Methods.
The compiler determines which version of a method to call by the method’s signature. In Chapter 3, you
learned that a method’s signature is the combination of the method name and the number, types, and
order of parameters.
If the keyword final appears in a method’s parameter list, it is ignored when determining
ambiguity. In other words, two methods with the headers void aMethod(int x) and
void aMethod(final int x) are ambiguous.
97070_ch04_hr_170-229.indd 186 24/02/18 3:55 pm
187
Creating and Calling Constructors with Parameters
Creating and Calling Constructors with parameters
In Chapter 3, you learned that Java automatically provides a constructor when you create
a class. You also learned that you can write your own constructor, and that you often do so
when you want to ensure that fields within classes are initialized to some appropriate default
value. You learned that the automatically provided constructor is a default constructor (one
that does not require arguments), and that you can write a custom default constructor.
However, when you write your own constructors, you also can write versions that receive
parameters. Such parameters often are used to initialize data fields for an object.
For example, consider the Employee class with just
one data field, shown in Figure 4-20. Its constructor
assigns 999 to the empNum of each potentially
instantiated Employee object. Anytime an Employee
object is created using a statement such as Employee
partTimeWorker = new Employee();, even if no other
data- assigning methods are ever used, you ensure that
the partTimeWorker Employee, like all Employee objects,
will have an initial empNum of 999.
Alternatively, you might choose to create Employee
objects with initial empNum values that differ for each
Employee. To accomplish this when the object is
The false statement is #1. A method that accepts an int parameter followed by
a String is not ambiguous with one that accepts the parameters in the reverse
order.
tWO trUthS & a LIe
Learning About Ambiguity
1. When it is part of the same program as void myMethod(int age, String
name), the following method would be ambiguous:
void myMethod(String name, int age)
2. When it is part of the same program as void myMethod(int age, String
name), the following method would be ambiguous:
String myMethod(int zipCode, String address)
3. When it is part of the same program as void myMethod(int age, String
name), the following method would be ambiguous:
void myMethod(int x, String y)
public class Employee
{
private int empNum;
Employee()
{
empNum = 999;
}
}
Figure 4-20 The Employee
class with a default constructor
that initializes the empNum field
97070_ch04_hr_170-229.indd 187 24/02/18 3:55 pm
188
More Object Concepts C h a p t e r 4
instantiated, you can pass an employee number to
the constructor. Figure 4-21 shows an Employee class
that contains a constructor that receives a parameter.
With this constructor, an argument is passed using a
statement such as the following:
Employee partTimeWorker = new Employee(881);
When the constructor executes, the integer within
the constructor call is passed to Employee() as the
parameter num, which is assigned to the empNum field.
When you create an Employee class with a
constructor such as the one shown in Figure 4-21,
every Employee object you create must have an integer argument in its constructor call. In
other words, with this new version of the class, the following statement no longer works:
Employee partTimeWorker = new Employee();
After you write a constructor for a class, you no longer receive the automatically provided
default constructor. If a class’s only constructor requires an argument, you must provide an
argument for every object of the class that you create. If you want to create a constructor
with parameters and also provide a default constructor, you can overload the constructors.
Overloading Constructors
Like other methods, you can overload constructors. Overloading constructors provides
you with a way to create objects with different initializing arguments, or none, as needed.
For example, in addition to using the provided constructor shown in Figure 4-21, you can
create a second constructor for the Employee class; Figure 4-22 shows an Employee class
that contains two constructors. When you use this class to create an Employee object,
you have the option of creating the object either with or without an initial empNum
value. When you create an Employee object
with the statement Employee aWorker = new
Employee();, the constructor with no
parameters is called, and the Employee object
receives an initial empNum value of 999. When
you create an Employee object with Employee
anotherWorker = new Employee(7677);, the
constructor version that requires an integer is
used, and the anotherWorker Employee receives
an initial empNum of 7677.
You can use constructor arguments to initialize
field values, but you also can use them for any
other purpose. For example, you could use the
presence or absence of an argument simply to
determine which of two possible constructors to
public class Employee
{
private int empNum;
Employee(int num)
{
empNum = num;
}
}
Figure 4-21 The Employee class
with a constructor that accepts a value
public class Employee
{
private int empNum;
Employee(int num)
{
empNum = num;
}
Employee()
{
empNum = 999;
}
}
Figure 4-22 The Employee class that
contains two constructors
97070_ch04_hr_170-229.indd 188 24/02/18 3:55 pm
189
Creating and Calling Constructors with Parameters
Watch the video Overloading Constructors.
call, yet not make use of the argument within the constructor. As long as the constructor
parameter lists differ, the constructors are not ambiguous.
The false statement is #1. A default constructor is one that takes no arguments.
The constructor that is created automatically when you do not write your own
version is a default constructor, but so is one that you write to take no arguments.
tWO trUthS & a LIe
Creating and Calling Constructors with Parameters
1. A default constructor is one that is created automatically.
2. When you write a constructor, it can be written to receive parameters or not.
3. If a class’s only constructor requires an argument, you must provide an
argument for every object of the class that you create.
Creating Overloaded Constructors
In this section, you create a class with overloaded constructors and demonstrate
how they work.
1. Open a new file in your text editor, and start the CarInsurancePolicy class as
follows. The class contains three fields that hold a policy number, the number
of payments the policyholder will make annually, and the policyholder’s city of
residence.
public class CarInsurancePolicy
{
private int policyNumber;
private int numPayments;
private String residentCity;
You Do It
(continues)
97070_ch04_hr_170-229.indd 189 24/02/18 3:55 pm
190
More Object Concepts C h a p t e r 4
2. Create a constructor that requires parameters for all three data fields.
public CarInsurancePolicy(int num, int payments, String city)
{
policyNumber = num;
numPayments = payments;
residentCity = city;
}
3. Suppose the agency that sells car insurance policies is in the city of Mayfield.
Create a two-parameter constructor that requires only a policy number and the
number of payments. This constructor assigns Mayfield to residentCity.
public CarInsurancePolicy(int num, int payments)
{
policyNumber = num;
numPayments = payments;
residentCity = "Mayfield";
}
4. Add a third constructor that requires only a policy number parameter. This
constructor uses the default values of two annual payments and Mayfield as the
resident city. (Later in this chapter, you will learn how to eliminate the duplicated
assignments in these constructors.)
public CarInsurancePolicy(int num)
{
policyNumber = num;
numPayments = 2;
residentCity = "Mayfield";
}
5. Add a display() method that outputs all the insurance policy data:
public void display()
{
System.out.println("Policy #" + policyNumber + ". " +
numPayments + " payments annually. Driver resides in " +
residentCity + ".");
}
6. Add a closing curly brace for the class. Save the file as
CarInsurancepolicy.java.
(continues)
(continued)
97070_ch04_hr_170-229.indd 190 24/02/18 3:55 pm
191
Creating and Calling Constructors with Parameters
7. Open a new text file to create a short application that demonstrates the
constructors at work. The application declares three CarInsurancePolicy
objects using a different constructor version each time. Type the following code:
public class CreatePolicies
{
public static void main(String[] args)
{
CarInsurancePolicy first = new CarInsurancePolicy(123);
CarInsurancePolicy second = new CarInsurancePolicy(456, 4);
CarInsurancePolicy third = new CarInsurancePolicy
(789, 12, "Newcastle");
8. Display each object, and add closing curly braces for the method and the class:
first.display();
second.display();
third.display();
}
}
9. Save the file as Createpolicies.java, and then compile and test the program.
The output appears in Figure 4-23.
10. Add a fourth declaration to the CreatePolicies class that attempts to create
a CarInsurancePolicy object using a default constructor:
CarInsurancePolicy fourth = new CarInsurancePolicy();
11. Save and compile the revised CreatePolicies program. The class does not
compile because the CarInsurancePolicy class does not contain a default
constructor. Change the newly added declaration to a comment, compile the
class again, and observe that the class now compiles correctly.
(continues)
(continued)
Figure 4-23 Output of the CreatePolicies program
97070_ch04_hr_170-229.indd 191 24/02/18 3:55 pm
192
More Object Concepts C h a p t e r 4
Learning about the this reference
When you start creating classes, they can become large very quickly. Besides data fields,
each class can have many methods, including several overloaded versions. On paper, a
single class might require several pages of coded statements.
When you instantiate an object from a class, memory is reserved for each instance field in
the class. For example, if a class contains 20 data fields, when you create one object from that
class, enough memory is reserved to hold the 20 field values for that object. When you create
200 objects of the same class, the computer reserves enough memory for 4,000 data fields—20
fields for each of the 200 objects. In many applications, the computer memory requirements
can become substantial. Fortunately, objects can share some variables and methods.
In Chapter 3, you learned that if a field or method name is preceded by the keyword
static when it is declared, only one field or method exists, no matter how many objects
are instantiated. In other words, if a field is static, then only one copy of the field exists,
and all objects created have the same value for that field. However, you frequently want
each instantiation of a class to have its own copy of each data field so that each object can
hold unique values. For example, if an Employee class contains fields for employee number,
Examining Prewritten Overloaded Methods
In this section, you examine some built-in classes and recognize their correctly
overloaded methods.
1. Navigate to the Java website that provides the documentation for Java SE9
classes (https://docs.oracle.com/javase/9/docs/api/allclasses-noframe.html),
and using the alphabetical list of classes, find the printStream class, and
select it.
2. Examine the list of constructors for the class, and notice that each version has
a unique parameter list.
3. Examine the list of methods named print() and println(). Notice that
each overloaded version has a unique parameter list.
4. Using the alphabetical list of classes, find the JOptionPane class, and
select it.
5. Examine the list of constructors for the class, and notice that each version has
a unique parameter list.
6. Examine the list of methods named showConfirmDialog() and
showInputDialog(). Notice that each overloaded version has a unique
parameter list.
(continued)
97070_ch04_hr_170-229.indd 192 24/02/18 3:55 pm
193
Learning About the this Reference
name, and salary, every individual Employee object needs a unique number, name, and
salary value. Fields that hold unique values for each object are not defined as static.
When you create a method that uses a nonstatic field value for a class—for example, to get or
set the field value—the method must be nonstatic. That means it performs in a different way
for each object. However, it would take an enormous amount of memory to store a separate
copy of each method for every object created from a class, and it would be wasteful, especially
because each method’s code would be identical. Luckily, in Java just one copy of each
nonstatic method in a class is stored, and all instantiated objects can use that copy. The secret
behind a single method copy’s ability to work with multiple object fields is that each nonstatic
method in a class automatically receives the memory address of the object it references.
When you use a nonstatic method, you use the object name, a dot, and the method name—
for example, aWorker.getEmpNum() or anotherWorker.getEmpNum(). When you execute
the getEmpNum() method, you are running the only copy of the method. However, within the
getEmpNum() method, when you access the empNum field, you access a different field depending
on the object. The compiler accesses the correct object’s field because every time you call
a nonstatic method, a reference—an object’s memory address—is implicitly understood.
The reference to an object that is passed to any object’s nonstatic method is called the this
reference; this is a reserved word in Java. Only nonstatic, instance methods have a this
reference. For example, the two getEmpNum() methods for the Employee class shown in
Figure 4-24 perform identically. The first method simply uses the this reference without your
being aware of it; the second method uses the this reference explicitly. Both methods return
the empNum of the object used to call the method.
Frequently, you neither want nor need to refer to the this reference within the instance
methods that you write, but the this reference is always there, working behind the scenes,
so that the data field for the correct object can be accessed.
On a few occasions, you must use the this reference to make your classes work correctly;
one example is shown in the Student class in Figure 4-25. Within the constructor for this
Figure 4-24 Two versions of the getEmpNum() method, with and without
an explicit this reference
public int getEmpNum()
{
return empNum;
}
public int getEmpNum()
{
return this.empNum;
}
The this reference is sent into this nonstatic
method as a parameter automatically; you do
not (and cannot) write code for it. You do not
need to use this with empNum.
However, you can explicitly use the this
reference with empNum. The two methods
in this figure operate identically.
97070_ch04_hr_170-229.indd 193 24/02/18 3:55 pm
194
More Object Concepts C h a p t e r 4
class, the parameter names stuNum and gpa are identical to the class field names. Within the
constructor, stuNum and gpa refer to the locally declared names, not the class field names.
The statement stuNum = stuNum accomplishes nothing—it assigns the local variable value
to itself. The client application in Figure 4-26 attempts to create a Student object with an
ID number of 111 and a grade point average of 3.5, but Figure 4-27 shows the incorrect
output. The values are not assigned to the fields; instead, they are just zeroes.
One way to fix the problem with the Student class is to use different identifiers for the
class’s fields and the parameters to the constructor. However, sometimes the identifiers you
have chosen are the best and simplest identifiers for a value. If you choose to use the same
identifiers, you can use the this reference explicitly to identify the fields. Figure 4-28 shows
a modified Student class.
Figure 4-25 A Student class whose constructor does not work
public class Student
{
private int stuNum;
private double gpa;
public Student (int stuNum, double gpa)
{
stuNum = stuNum;
gpa = gpa;
}
public void showStudent()
{
System.out.println("Student #" + stuNum +
" gpa is " + gpa);
}
}
Don’t Do It
All four variables used in these two
statements are the local versions declared in
the constructor’s parameter list. The fields are
never accessed because the local variables
shadow the fields. These two assignment
statements accomplish nothing.
Figure 4-27 Output of the
TestStudent application using
the incorrect Student class in
Figure 4-25
public class TestStudent
{
public static void main(String[] args)
{
Student aPsychMajor =
new Student(111, 3.5);
aPsychMajor.showStudent();
}
}
Figure 4-26 The TestStudent class that instantiates a
Student object
97070_ch04_hr_170-229.indd 194 24/02/18 3:55 pm
195
Figure 4-29 Output of the
TestStudent application using
the new version of the Student
class
The only difference between the classes in Figures 4-25
and 4-28 is the explicit use of the this reference within
the constructor. When the this reference is used with
a field name in a method, the reference is to the class’s
data field instead of to the local variable declared within
the method. When the TestStudent application uses this
new version of the Student class, the output appears as
expected, as shown in Figure 4-29.
Using the this Reference to Make Overloaded Constructors
More Efficient
Suppose you create a Student class with data fields for a student number and a grade point
average. Further suppose you want four overloaded constructors as follows:
• A constructor that accepts an int and a double and assigns them the student number
and grade point average, respectively
• A constructor that accepts a double and assigns it to the grade point average, but
initializes every student number to 999
• A constructor that accepts an int and assigns it to the student number, but initializes
every grade point average to 0.0
• A default constructor that assigns 999 to every student number and 0.0 to every grade
point average
Figure 4-28 The Student class using the explicit this reference within the constructor
public class Student
These are
the Student
fields.
These parameters are
locally declared in the
Student constructor.
These identifiers, without this, refer to the
locally declared variables and not the fields.
Because these
identifiers are preceded
by this, they refer
to the fields in the
Student class.
The showStudent() method
has no locally declared variables,
so these identifiers refer to the
Student fields.
{
{
}
}
}
{
private int stuNum;
private double gpa;
public Student(int stuNum, double gpa)
this.stuNum = stuNum;
this.gpa = gpa;
public void showStudent()
System.out.printIn("Student #" +
stuNum + " gpa is " + gpa);
Learning About the this Reference
97070_ch04_hr_170-229.indd 195 24/02/18 3:55 pm
196
More Object Concepts C h a p t e r 4
Figure 4-30 shows the class. Although this class works, and allows Students to be
constructed in four different ways, there is a lot of repetition within the constructors.
Figure 4-30 Student class with four constructors
Each constructor contains
similar statements.
public class Student
private int stuNum;
private double gpa;
stuNum = num;
stuNum = 999;
stuNum = num;
stuNum = 999;
gpa = avg;
gpa = avg;
gpa = 0.0;
gpa = 0.0;
}
}
}
}
}
Student(int num, double avg)
Student(double avg)
Student(int num)
Student()
{
{
{
{
{
You can reduce the amount of repeated code in Figure 4-30 and make the code less
error-prone by calling one constructor version from the others. To do so, you use the this
reference from one constructor version to call another version. Figure 4-31 shows how the
Student class can be rewritten.
By writing each constructor to call one master constructor, you save coding and reduce the
chance for errors. For example, if code is added later to ensure that all student ID numbers
are three digits, or that no grade point average is greater than 4.0, the new code will be
written only in the two-parameter version of the constructor, and all the other versions
will use it. (Testing a variable to ensure it falls within the proper range of values requires
decision making. Chapter 5 covers this topic.)
Although you can use the this reference with field names in any method within a class, you
cannot call this() from other methods in a class; you can call it only from constructors.
Additionally, if you call this() from a constructor, it must be the first statement within the
constructor.
97070_ch04_hr_170-229.indd 196 24/02/18 3:55 pm
197
Watch the video The this Reference.
Figure 4-31 The Student class using this in three of four constructors
public class Student
this(999, avg);
this(num, 0.0);
this(999, 0.0);
{
{
{
{
{
private int stuNum;
private double gpa;
Student(int num, double avg)
stuNum = num;
gpa = avg;
Student(double avg)
Student(int num)
Student()
}
}
}
}
}
Each of these calls to
this() calls the two-
parameter version of the
constructor.
The false statement is #3. Usually, you neither want nor need to refer to the this
reference within the methods you write, but you can use it—for example, when
there are conflicts between identifiers for fields and local variables.
tWO trUthS & a LIe
Learning About the this Reference
1. Usually, you want each instantiation of a class to have its own nonstatic data
fields, but each object does not need its own copy of most methods.
2. When you use a nonstatic method, the compiler accesses the correct
object’s field because you implicitly pass an object reference to the method.
3. The this reference is supplied automatically in classes; you cannot use it
explicitly.
Learning About the this Reference
97070_ch04_hr_170-229.indd 197 24/02/18 3:55 pm
198
More Object Concepts C h a p t e r 4
Using the this Reference to Make Constructors More Efficient
In this section, you modify the CarInsurancePolicy class so that its constructors
are more efficient.
1. Open the CarInsurancepolicy.java file. Change the class name
to CarInsurancePolicy2, and immediately save the file as
CarInsurancepolicy2.java.
2. Change the name of the three-parameter constructor from
CarInsurancePolicy() to CarInsurancePolicy2().
3. Replace the constructor that accepts a single parameter for the policy number
with the following constructor. The name of the constructor is changed from the
earlier version, and this one passes the policy number and two constant values
to the three-parameter constructor:
public CarInsurancePolicy2(int num)
{
this(num, 2, "Mayfield");
}
4. Replace the constructor that accepts two parameters (for the policy number
and number of payments) with the following constructor. This constructor has
a new name and passes the two parameters and one constant value to the
three-parameter constructor:
public CarInsurancePolicy2(int num, int payments)
{
this(num, payments, "Mayfield");
}
5. Save the file, and compile it.
6. Open the Createpolicies.java file that demonstrates the use of the different
constructor versions. Change the class name to CreatePolicies2, and save
the file as Createpolicies2.java.
7. Add the digit 2 in six places—three times to change the class name
CarInsurancePolicy to CarInsurancePolicy2 when the name is used as
a data type, and in the three constructor calls.
8. Save the file, and then compile and execute it. The output is identical to that
shown in Figure 4-23 in the previous “You Do It” section, but the repetitious
constructor code has been eliminated.
You Do It
(continues)
97070_ch04_hr_170-229.indd 198 24/02/18 3:55 pm
199
Using static Fields
9. You can further reduce the code in the CarInsurancePolicy class by
changing the single-parameter constructor to the following, which removes
the constant "Mayfield" from the constructor call:
public CarInsurancePolicy2(int num)
{
this(num, 2);
}
Now, the single-parameter version calls the two-parameter version and passes
the policy number and the constant 2. In turn, the two-parameter version calls
the three-parameter version, adding "Mayfield" as the city.
10. Save this version of the CarInsurancePolicy2 class, and compile it. Then recompile
the Createpolicies2.java file, and execute it. The output remains the same.
(continued)
Using static Fields
In Chapter 3, you learned that methods you create to use without objects are static. For
example, the main() method in a program and the methods that main() calls without an
object reference are static. You also learned that most methods you create within a class
from which objects will be instantiated are nonstatic. Static methods do not have a this
reference because they have no object associated with them; therefore, they are called
class methods.
You can also create class variables, which are variables that are shared by every
instantiation of a class. Whereas instance variables in a class exist separately for every
object you create, there is only one copy of each static class variable per class. For
example, consider the BaseballPlayer class in Figure 4-32. The BaseballPlayer
class contains a static field named countOfPlayers, and two nonstatic fields named
number and battingAverage. The BaseballPlayer constructor sets values for number
and battingAverage and increases countOfPlayers by one. In other words, every time
a BaseballPlayer object is constructed, it contains individual values for number and
battingAverage, and the countOfPlayers field contains a count of the number of existing
objects and is shared by all BaseballPlayer objects.
The showPlayer() method in the BaseballPlayer class displays a BaseballPlayer’s
number, batting average, and a count of all current players. The showPlayer() method is
not static—it accesses an individual object’s data. Methods declared as static cannot
access instance variables, but nonstatic instance methods such as showPlayer() can access
both static and instance variables.
97070_ch04_hr_170-229.indd 199 24/02/18 3:55 pm
200
More Object Concepts C h a p t e r 4
The TestPlayer class in Figure 4-33 is an application that declares two BaseballPlayer
objects, displays them, and then creates a third BaseballPlayer object and displays it. When
you examine the output in Figure 4-34, you can see that by the time the first two objects
are declared, the countOfPlayers value that they share is 2. Whether countOfPlayers is
accessed using the aCatcher object or the aShortstop object, the value of countOfPlayers
is the same. After the third object is declared, its count value is 3, as is the value of count
associated with both of the previously declared objects. In other words, the countOfPlayers
variable is incremented within the constructor, so its value changes with each new
instantiation, and because the field is static, each object has access to the single memory
location that holds the countOfPlayers value. No matter how many BaseballPlayer
objects are eventually instantiated, each refers to the single countOfPlayers field.
Figure 4-32 The BaseballPlayer class
public class BaseballPlayer
{
private static int countOfPlayers = O;
private int number;
private double battingAverage;
public BaseballPlayer(int id, double avg)
{
number = id;
battingAverage = avg;
countOfPlayers = countOfPlayers + 1;
}
public void showPlayer()
{
System.out.println("Player #" + number +
" batting average is " + battingAverage +
" There are " + countOfPlayers + " players");
}
}
The field countOfPlayers
is static; all objects of type
BaseballPlayer will share
its value.
public class TestPlayer
{
public static void main(String[] args)
{
BaseballPlayer aCatcher = new BaseballPlayer(12, .218);
BaseballPlayer aShortstop = new BaseballPlayer(31, .385);
aCatcher.showPlayer();
aShortstop.showPlayer();
BaseballPlayer anOutfielder = new BaseballPlayer(44, .505);
anOutfielder.showPlayer();
aCatcher.showPlayer();
}
}
Figure 4-33 The TestPlayer class
97070_ch04_hr_170-229.indd 200 24/02/18 3:55 pm
201
Using Constant Fields
In Chapter 2, you learned to create named constants by using the keyword final.
Sometimes a data field in a class should be constant. For example, you might want to store
a school ID value that is the same for every Student object you create, so you declare it to
be static. In addition, if you want the value for the school ID to be fixed so that all Student
objects use the same ID value—for example, when applying to scholarship- granting
organizations or when registering for standardized tests—you might want to make the
school ID unalterable. As with ordinary variables, you use the keyword final with a field to
make its value unalterable after construction. For example, the class in Figure 4-35 contains
the symbolic constant SCHOOL_ID. Because it is static, all objects share a single memory
location for the field, and because it is final, it cannot change during program execution.
A nonstatic final field’s value can be assigned a value in a constructor. For example, you
can set it using a constant, or you can set it using a parameter passed into the constructor.
However, a static final field’s value must be set at declaration, as in the Student class
example in Figure 4-35. This makes sense because only one static field is stored for every
object instantiated, so it would be redundant to continually reset the field’s value during
object construction.
Figure 4-34 Output of the TestPlayer application
Figure 4-35 The Student class containing a symbolic constant
public class Student
{
private static final int SCHOOL_ID = 12345;
private int stuNum;
private double gpa;
public Student(int stuNum, double gpa)
{
this.stuNum = stuNum;
this.gpa = gpa;
}
public void showStudent()
{
System.out.println("Student #" + stuNum +
" gpa is " + gpa);
}
}
static final
symbolic constant
Using static Fields
97070_ch04_hr_170-229.indd 201 24/02/18 3:55 pm
202
More Object Concepts C h a p t e r 4
You can use the keyword final with methods or classes as well as with fields. When used in this
manner, final indicates limitations placed on inheritance. You will learn more about inheritance in
the chapters “Introduction to Inheritance” and “Advanced Inheritance Concepts.”
Fields that are final also can be initialized in a static initialization block. For more details about this
technique, see the Java website.
Fields declared to be static are not always final. Conversely, final fields are not always
static. In summary:
• If you want to create a field that all instantiations of the class can access, but the field
value can change, then it is static but not final. For example, in the last section you
saw a nonfinal static field in the BaseballPlayer class that held a changing count of
all instantiated objects.
• If you want each object created from a class to contain its own final value, you
would declare the field to be final but not static. For example, you might want each
BaseballPlayer object to have its own, nonchanging date of joining the team.
• If you want all objects to share a single nonchanging value, then the field is static and final.
The false statement is #1. Static methods do not have a this reference because
they have no object associated with them.
tWO trUthS & a LIe
Using static Fields
1. Methods declared as static receive a this reference that contains
a reference to the object associated with them.
2. Methods declared as static are called class methods.
3. A final static field’s value is shared by every object of a class.
Using Static and Nonstatic final Fields
In this section, you create a class for the Riverdale Kennel Club to demonstrate the
use of static and nonstatic final fields. The club enters its dogs in an annual triathlon
event in which each dog receives three scores in agility, conformation, and obedience.
You Do It
(continues)
97070_ch04_hr_170-229.indd 202 24/02/18 3:55 pm
203
1. Open a new file in your text editor, and enter the first few lines for a
DogTriathlonParticipant class. The class contains a final field that holds
the number of events in which the dog participated. Once a final field is set, it
should never change. The field is not static because it is different for each dog.
The class also contains a static field that holds the total cumulative score for
all the participating dogs. The field is not final because its value increases as
each dog participates in the triathlon, but it is static because at any moment in
time, it is the same for all participants.
public class DogTriathlonParticipant
{
private final int NUM_EVENTS;
private static int totalCumulativeScore = 0;
2. Add six private fields that hold the participating dog’s name, the dog’s score in
three events, the total score, and the average score:
private String name;
private int obedienceScore;
private int conformationScore;
private int agilityScore;
private int total;
private double avg;
3. The constructor for the class requires five parameters—the dog’s name, the
number of events in which the dog participated, and the dog’s scores in the
three events. (After you read the chapter about decision making, you will be
able to ensure that the number of nonzero scores entered matches the number
of events, but for now no such checks will be made.) The constructor assigns
each value to the appropriate field.
public DogTriathlonParticipant(String name,
int numEvents, int score1, int score2, int score3)
{
this.name = name;
NUM_EVENTS = numEvents;
obedienceScore = score1;
conformationScore = score2;
agilityScore = score3;
4. After the assignments, the constructor calculates the total score for the
participant and the participant’s average score. Notice the result of the division
is cast to a double so that any fractional part of the calculated average is
not lost. Also, add the participant’s total score to the cumulative score for all
participants. Recall that this field is static because it should be the same for
(continues)
(continued)
Using static Fields
97070_ch04_hr_170-229.indd 203 24/02/18 3:55 pm
204
More Object Concepts C h a p t e r 4
all participants at any point in time. After these statements, add a closing curly
brace for the constructor.
total = obedienceScore +
conformationScore + agilityScore;
avg = (double) total / NUM_EVENTS;
totalCumulativeScore = totalCumulativeScore +
total;
}
5. Start a method that displays the data for each triathlon participant.
public void display()
{
System.out.println(name + " participated in " +
NUM_EVENTS +
" events and has an average score of " + avg);
System.out.println(" " + name +
" has a total score of " + total +
" bringing the total cumulative score to " +
totalCumulativeScore);
}
6. Add a closing curly brace for the class. Then, save the file as
Dogtriathlonparticipant.java. Compile the class, and correct any errors.
7. Open a new file in your text editor, and then enter the header and
opening and closing curly braces for a class you can use to test the
DogTriathlonParticipant class. Also include a main() method header
and its opening and closing braces.
public class TestDogs
{
public static void main(String[] args)
{
}
}
8. Between the braces of the main() method, declare a DogTriathlonParticipant
object. Provide values for the participant’s name, number of events, and three
scores, and then display the object.
DogTriathlonParticipant dog1 =
new DogTriathlonParticipant("Bowser", 2, 85, 89, 0);
dog1.display();
(continues)
(continued)
97070_ch04_hr_170-229.indd 204 24/02/18 3:55 pm
205
9. Create and display two more objects within the main() method.
DogTriathlonParticipant dog2 =
new DogTriathlonParticipant("Rush", 3, 78, 72, 80);
dog2.display();
DogTriathlonParticipant dog3 =
new DogTriathlonParticipant("Ginger", 3, 90, 86, 72);
dog3.display();
10. Save the file as testDogs.java. Compile and execute the program. The
output looks like Figure 4-36. Visually confirm that each total, average, and
cumulative total is correct.
11. Experiment with the DogTriathlonParticipant class and its test class. For
example, try the following:
• Add a new statement at the end of the TestDogs class that again displays
the data for any one of the participants. Note that as long as no new
objects are created, the cumulative score for all participants remains the
same no matter which participant uses it.
• Try to assign a value to the NUM_EVENTS constant from the display()
method, and then compile the class and read the error message generated.
• Remove the keyword static from the definition of totalCumulativeScore
in the DogTriathlonParticipant class, and then recompile the classes
and run the program. Notice in the output that the nonstatic cumulative
score no longer reflects the cumulative score for all objects, but only the
score for the current object using the display() method.
• Use 0 as the number of events for an object. When the participant’s
average is calculated, the result is not numeric, and NaN is displayed.
NaN is an acronym for Not a Number. In Chapter 5, you will learn to
make decisions, and then you can prevent the NaN output.
(continued)
Figure 4-36 Output of the TestDogs program
Using static Fields
97070_ch04_hr_170-229.indd 205 24/02/18 3:55 pm
206
More Object Concepts C h a p t e r 4
Using automatically Imported, prewritten Constants
and Methods
If you write Java programs for an organization, you most likely will create dozens or
hundreds of custom-made classes eventually. For example, you might create an Employee
class with fields appropriate for describing employees in your organization, and an
Inventory class with fields appropriate for whatever type of item you sell or manufacture.
However, many classes do not require customization for specific businesses. Instead,
they are commonly used by a wide variety of programmers. Rather than have each Java
programmer “reinvent the wheel,” the creators of Java have produced hundreds of classes
for you to use in your programs.
You already have used several of these prewritten classes; for example, you have used
the System and JOptionPane classes to produce output. Each of these classes is stored in
a package, or a library of classes, which is simply a folder that provides a convenient
grouping for classes. Java has two categories of packages:
• The java.lang package is implicitly imported into every program you write.
The classes it contains are fundamental classes that provide the basis of the Java
programming language. The System class, which you have used to access print()
and println(), is an automatically imported class in the java.lang package. Others
include the Object class, which you will learn about in Chapter 11; wrapper classes
such as Integer, Float, and Double, which you will learn about in Chapter 7; and
the Math class, which is discussed in the next section. Some references list a few
other Java classes as also being “fundamental,” but the java.lang package is the only
automatically imported, named package.
• All other Java packages are available only if you explicitly name them within your program.
These packages contain the optional classes. For example, when you use JOptionPane,
you must import the javax.swing package into your program, and when you use the
LocalDate class, you must import the java.time package, as you learn later in this chapter.
The Math Class
The class java.lang.Math contains constants and methods that you can use to perform
common mathematical functions. All of the constants and methods in the Math class are
static—they are class variables and class methods. In other words, you do not create any
Math objects when you use the class.
For example, PI is a commonly used Math class constant. In geometry, pi is an
approximation of a circle’s radius based on the ratio of the circumference of the
circle to its diameter. Within the Math class, the declaration for PI is as follows:
public final static double PI = 3.14159265358979323846;
97070_ch04_hr_170-229.indd 206 24/02/18 3:55 pm
207
Using Automatically Imported, Prewritten Constants and Methods
Notice that PI is:
• public, so any program can access it directly
• final, so it cannot be changed
• static, so only one copy exists and you can access it without declaring a Math object
• double, so it holds a floating-point value
You can use the value of PI within any program you write by referencing the full package
path in which PI is defined; for example, you can calculate the area of a circle using the
following statement:
areaOfCircle = java.lang.Math.PI * radius * radius;
However, the java.lang package is imported automatically into your programs, so if you
simply reference Math.PI, Java recognizes this code as a shortcut to the full package path.
Therefore, the preferred (and simpler) statement is the following:
areaOfCircle = Math.PI * radius * radius;
In addition to constants, many useful methods are available within the Math class.
For example, the Math.max() method returns the larger of two values, and the method
Math.abs() returns the absolute value of a number. Table 4-1 lists some common Math
class methods.
Method Value that the Method returns
abs(x) Absolute value of x
acos(x) Arc cosine of x
asin(x) Arc sine of x
atan(x) Arc tangent of x
atan2(x, y) Theta component of the polar coordinate (r, theta) that corresponds to the
Cartesian coordinate x, y
ceil(x) Smallest integral value not less than x (ceiling)
cos(x) Cosine of x
exp(x) Exponent, where x is the base of the natural logarithms
floor(x) Largest integral value not greater than x
log(x) Natural logarithm of x
table 4-1 Common Math class methods (continues)
97070_ch04_hr_170-229.indd 207 24/02/18 3:55 pm
208
More Object Concepts C h a p t e r 4
Because all constants and methods in the Math class are classwide (that is, static), there is
no need to create an instance of the Math class. You cannot instantiate objects of type Math
because the constructor for the Math class is private, and your programs cannot access the
constructor.
Method Value that the Method returns
max(x, y) Larger of x and y
min(x, y) Smaller of x and y
pow(x, y) x raised to the y power
random() Random double number between 0.0 and 1.0
rint(x) Closest integer to x (x is a double, and the return value is expressed
as a double)
round(x) Closest integer to x (where x is a float or double, and the return value is an
int or long)
sin(x) Sine of x
sqrt(x) Square root of x
tan(x) Tangent of x
table 4-1 Common Math class methods
(continued)
Unless you are a mathematician, you won’t use many of these Math class methods, and
it is unwise to do so unless you understand their purposes. For example, because the square
root of a negative number is undefined, if you display the result after the method call
imaginaryNumber = Math.sqrt(-12);, you see NaN.
Importing Classes that Are Not Imported Automatically
Java contains hundreds of classes, only a few of which—those in the java.lang package—
are included automatically in the programs you write. To use any of the other prewritten
classes, you must use one of three methods:
• Use the entire path with the class name.
• Import the class.
• Import the package that contains the class you are using.
97070_ch04_hr_170-229.indd 208 24/02/18 3:55 pm
209
Using Automatically Imported, Prewritten Constants and Methods
For example, in its java.time package, Java includes several classes that are useful when
working with dates and time. One of the classes, LocalDate, holds data about a date,
including a month, day, and year, and contains methods that allow you to easily work with
dates. You can declare a LocalDate reference by using the full class path, as in the following:
java.time.LocalDate myAnniversary;
However, you probably prefer to use a shorter statement. You have seen examples in this
book in which the Scanner and JOptionPane classes were imported using the following
statements:
import java.util.Scanner;
import javax.swing.JOptionPane;
These import statements allow you to create Scanner and JOptionPane references without
typing the complete paths.
Similarly, you can import the LocalDate class using the following statement:
import java.time.LocalDate;
Then you can declare a LocalDate reference with a shortened statement such as the
following:
LocalDate myAnniversary;
The java.time package was new in Java 8. Several other classes such as Calendar and
GregorianCalendar were used for working with time in earlier Java versions. The classes defined
in java.time base their calendar system on the ISO calendar, which is an international standard for
expressing dates and times.
An alternative to importing a class is to import an entire package of classes. You can use
the asterisk ( * ) as a wildcard symbol, which indicates that it can be replaced by any set
of characters. In a Java import statement, you use a wildcard symbol to represent all the
classes in a package. Therefore, the following statement imports the LocalDate class and
any other java.time classes as well:
import java.time.*;
The import statement does not move the entire imported class or package into your
program, as its name implies. Rather, it simply notifies the program that you will use the
data and method names that are part of the imported class or package.
There is no performance disadvantage to importing an entire package instead of just
the classes you need, and you will commonly see the wildcard method in professionally
written Java programs. However, you have the alternative of importing each class you
need individually. Importing all of a package’s classes at once saves typing, but importing
each class by name, without wildcards, can be a form of documentation, specifically to
97070_ch04_hr_170-229.indd 209 24/02/18 3:55 pm
210
More Object Concepts C h a p t e r 4
The LocalDate class is so named to distinguish it from other Java classes that include time zone
information in their dates—in other words, dates that are not “local.”
show which parts of the package are being used. Additionally, if two or more packages
contain classes with the same identifiers, then using the wildcard can result in conflicts.
You cannot use the import statement wildcard exactly like a DOS or UNIX wildcard
because you cannot import all the Java classes with import java.*;. The Java wildcard
works only with specific packages such as import java.util.*; or import java.time.*;.
Also, note that the asterisk in an import statement imports all of the classes in a package,
but not other packages that are within the imported package.
Java also uses the question mark character ( ? ) as a wildcard when instantiating generic data types. You
will learn about this topic as you continue to study Java.
Your own classes are included in applications without import statements because of your
classpath settings. See Appendix A for more information on classpath.
Using the LocalDate Class
A LocalDate object can be created using several approaches. For example, you can create
two LocalDate objects with the current date and May 29, 2020, using the following
statements:
LocalDate today = LocalDate.now();
LocalDate graduationDate = LocalDate.of(2020, 5, 29);
These statements use the static methods now() and of(), respectively. You can tell the
methods are static because they are used with the class name and without an object. The
now() method accepts no arguments, and the of() method accepts three integers that
represent a year, month, and day. You can tell from these two statements that both the
now() and of() methods have a return type of LocalDate because their returned values are
assigned to LocalDate objects.
Unlike the other classes you have seen, you do not use the new operator and call a
constructor when creating LocalDate objects; instead you use of() or now(). The class’s
constructors are not usable because they are not public.
A LocalDate object can be displayed as a String with dashes separating the year, month,
and day. For example, Figure 4-37 shows a program that creates two LocalDate objects
then displays them. Figure 4-38 shows the output.
97070_ch04_hr_170-229.indd 210 24/02/18 3:55 pm
211
Using Automatically Imported, Prewritten Constants and Methods
Specific data field values can be retrieved from a LocalDate object by using the
getYear(), getMonthValue(), and getDayOfMonth() methods that each return an integer.
For example, assuming that graduationDate has been created with arguments 2019, 5,
and 29, the following statement produces the output “Graduation will be on day 29 in
month 5”:
System.out.println("Graduation will be on day " +
graduationDate.getDayOfMonth() + " in month " +
graduationDay.getMonthValue());
Other useful LocalDate methods include getMonth() and getDayOfWeek(). Each of these
methods returns an enumeration, which is a data type that consists of a list of values. You
will learn to create your own enumerations in Chapter 9, but for now, you can use Java’s
Month and DayOfWeek enumerations returned by these methods. The enumerations are
constants with names such as JANUARY, FEBRUARY, and MARCH and SUNDAY, MONDAY, and
TUESDAY. For example, assuming that graduationDate has been set to May 29, 2019, the
following statement displays Graduation is on WEDNESDAY.
System.out.println("Graduation is on " +
graduationDate.getDayOfWeek());
You might choose to create a LocalDate object using one of the Month enumerations, as in
the following declaration:
LocalDate annualMeeting = LocalDate.of(2018, Month.OCTOBER, 1);
Figure 4-38 Execution of the LocalDateDemo application
import java.time.*;
public class LocalDateDemo
{
public static void main(String[] args)
{
Local Date today = Loca1Date.now();
Loca1Date graduationDate = Loca1Date.of(20l8, 5, 29);
System.out.println("Today is " + today);
System.out.println("Graduation is " + graduationDate);
}
}
Figure 4-37 The LocalDateDemo application
97070_ch04_hr_170-229.indd 211 24/02/18 3:55 pm
212
More Object Concepts C h a p t e r 4
Another set of methods adds and subtracts time from an existing date. Some of the
most useful method names are plusDays(), plusWeeks(), plusMonths(), plusYears(),
minusDays(), minusWeeks(), minusMonths(), and minusYears(). Each of these methods
accepts a long argument; of course, you can pass any of the methods an int to promote it
to a long. For example, Figure 4-39 shows an application that prompts a user for a furniture
order date and displays details about the delivery date, which is two weeks later.
Figure 4-40 Typical execution of the
DeliveryDate application
import java.time.*;
import java.util.Scanner;
public class DeliveryDate
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Loca1Date orderDate;
int mo;
int day;
int year;
final int WEEKS_FOR_DELIVERY = 2;
System.out.print("Enter order month ");
mo = input.nextInt();
System.out.print("Enter order day ");
day = input.nextInt();
System.out.print("Enter order year ");
year = input.nextInt();
orderDate = LocalDate.of(year, mo, day);
System.out.println("Order date is " + orderDate);
System.out.println("Delivery date is " +
orderDate.plusWeeks(WEEKS_FOR_DELIVERY)) ;
}
}
Figure 4-39 The DeliveryDate application
Figure 4-40 shows a typical execution of the
program in Figure 4-39. Notice that the two-week
delivery date is displayed correctly, even though
it falls both in the next month and the next year.
Without the built-in methods of the LocalDate
class, this output would require some fairly
complicated calculations and decisions, but because
the creators of Java have provided the class and its
methods for you, your task is greatly simplified.
97070_ch04_hr_170-229.indd 212 24/02/18 3:55 pm
213
Using Automatically Imported, Prewritten Constants and Methods
Many programmers need the methods in LocalDate, including those who manage
personnel, inventory, and billing systems and programmers who write games that keep
track of player records. Their jobs are easier because Java’s creators implemented so many
useful LocalDate methods. Additionally, when programmers advance to writing different
types of applications or change employers, they do not have to learn how to use obscure
date- handling methods that might have been written by previous programmers. After
programmers have learned about LocalDate’s built-in methods and constants, they know
how to work with dates in many situations.
The false statement is #2. Many Java packages are available only if you explicitly
name them within your program, but others are imported automatically.
tWO trUthS & a LIe
Using Automatically Imported, Prewritten Constants and Methods
1. The creators of Java have produced hundreds of classes for you to use in
your programs.
2. Java packages are available only if you explicitly name them within your
program.
3. The implicitly imported java.lang package contains fundamental Java
classes.
Using the Java Web Site
In this section, you learn more about using the LocalDate class and are introduced
to the LocalDateTime class.
1. Using a web browser, go to the Java website that provides documentation for
the Java SE9 classes (https://docs.oracle.com/javase/9/docs/api/allclasses-
noframe.html), and using the alphabetical list of classes, find the LocalDate
class and select it.
2. Notice that java.time is cited at the top of the description, indicating that it is
the containing package.
You Do It
(continues)
97070_ch04_hr_170-229.indd 213 24/02/18 3:55 pm
214
More Object Concepts C h a p t e r 4
3. Read the history and background of the LocalDate class to get an idea of how
many issues are involved in determining values such as the first day of the week
and a week’s number in a year. Then read the rest of the documentation to get
a feel for the fields and methods that are available with the class.
4. Find the documentation for the LocalDateTime class. It is similar to the
LocalDate class, except it includes information about the time of day. Read
descriptions of the methods getHour(), getMinute(), getSecond(), and
getNano(). (A nanosecond is one-billionth of a second.)
Using an Explicitly Imported, Prewritten Class
Next, you use the LocalDateTime class to create an application that outputs a
user’s response time to a question.
1. Open a new file in your text editor, and type the following two import
statements. You need the JOptionPane class to use the showConfirmDialog()
method, and you need the java.time package to use the LocalDateTime
class:
import javax.swing.JOptionPane;
import java.time.*;
2. Begin the TimedResponse application as follows. Declare two LocalDateTime
objects named time1 and time2. These objects will hold the exact time before
a user is prompted and the exact time after the user responds. Also declare
integers to hold the value of the seconds for both times. The difference
between these two values is the elapsed time between the creations of the two
LocalDateTime values.
public class TimedResponse
{
public static void main(String[] args)
{
LocalDateTime time1, time2;
int seconds1, seconds2, difference;
3. Assign the current time to the time1 object, and then extract the value of the
current seconds field.
time1 = LocalDateTime.now();
seconds1 = time1.getSecond();
4. Display a dialog box that asks the user to make a difficult choice.
JOptionPane.showConfirmDialog
(null, "Is stealing ever justified? ");
(continues)
(continued)
97070_ch04_hr_170-229.indd 214 24/02/18 3:55 pm
215
Using Automatically Imported, Prewritten Constants and Methods
5. Next, get the system time immediately after the user responds to the dialog
box, and extract its seconds component.
time2 = LocalDateTime.now();
seconds2 = time2.getSecond();
6. Compute the difference between the times, and display the result in a dialog
box.
difference = seconds2 - seconds1;
JOptionPane.showMessageDialog(null, "End seconds: " + seconds2 +
"\nStart seconds: " + seconds1 +
"\nIt took " + difference + " seconds for you to answer");
7. Add two closing curly braces—one for the method and the other for the class—
and then save the file as timedresponse.java.
8. Compile and execute the program. When the question appears, ponder it for
a few seconds, and then choose a response. Figure 4-41 shows a typical
execution.
9. The output in the TimedResponse application is accurate only when the first
and second LocalDateTime objects are created during the same minute, as in
the output in Figure 4-41, when the question was asked at 4 seconds after the
minute and then answered 17 seconds after the same minute. If the first object
is created 58 seconds after a minute starts and the user doesn’t respond to the
question until 2 seconds after the next minute starts, the difference between the
second values will be calculated incorrectly as –56 instead of 4 seconds. After
you learn how to make decisions in Chapter 5, you will be able to rectify this
problem.
(continued)
Figure 4-41 Typical execution of the TimedResponse application
97070_ch04_hr_170-229.indd 215 24/02/18 3:55 pm
216
More Object Concepts C h a p t e r 4
Understanding Composition and Nested Classes
Two of the ways that you can group classes are by using composition and by nesting classes.
This section takes a brief look at both concepts.
Composition
The fields in a class can be simple data types such as int and double, but they also can be
class types. Composition describes the relationship between classes when an object of one
class is a data field within another class. You already have studied many classes that contain
String object fields. These classes employ composition.
When you use an object as a data member of another object, you must remember to supply
values for the contained object if it has no default constructor. For example, you might
create a class named NameAndAddress that stores name and address information. Such a
class could be used for employees, customers, students, or anyone else who has a name
and address. Figure 4-42 shows a NameAndAddress class. The class contains three fields, all
of which are set by the constructor. A display() method displays the name and address
information on three lines.
Suppose you want to create a School class that holds information about a school. Instead
of declaring fields for the School’s name and address, you could use the NameAndAddress
class. The relationship created is sometimes called a has-a relationship because one class
“has an” instance of another. Figure 4-43 shows a School class that declares and uses a
NameAndAddress object.
public class NameAndAddress
{
private String name;
private String address;
private int zipCode;
public NameAndAddress(String nm, String add, int zip)
{
name = nm;
address = add;
zipCode = zip;
}
public void display()
{
System.out.println(name);
System.out.println(address);
System.out.println(zipCode);
}
}
Figure 4-42 The NameAndAddress class
97070_ch04_hr_170-229.indd 216 24/02/18 3:55 pm
217
Understanding Composition and Nested Classes
As Figure 4-43 shows, the School constructor requires four parameters. Within the constructor,
three of the items—the name, address, and zip code—are passed to the NameAndAddress
constructor to provide values for the appropriate fields. The fourth constructor parameter
(the school’s enrollment) is assigned to the School class enrollment field.
In the School class display method, the NameAndAddress object’s display() method
is called to display the school’s name and address. The enrollment value is displayed
afterward. Figure 4-44 shows a simple program that instantiates one School object.
Figure 4-45 shows the execution.
Figure 4-45 Output of the SchoolDemo program
Figure 4-43 The School class
public class School
public void display()
private NameAndAddress nameAdd;
private int enrollment;
public School(String name, String add; int zip, int enrolled)
{
{
{
nameAdd = new NameAndAddress(name, add, zip);
enrollment = enrolled;
nameAdd.display();
System.out.printIn("Enrollment is " + enrollment);
System.out.printIn("The school information:");
}
}
}
This statement
declares a
NameAndAddress
object.
This statement calls the
constructor in the
NameAndAddress
class.
This statement calls the
display() method in
the NameAndAddress
class.
public class SchoolDemo
{
public static void main(String[] args)
{
School mySchool = new School
("Audubon Elementary",
"3500 Hoyne", 60618, 350);
mySchool.display();
}
}
Figure 4-44 The SchoolDemo program
97070_ch04_hr_170-229.indd 217 24/02/18 3:55 pm
218
More Object Concepts C h a p t e r 4
Nested Classes
Every class you have studied so far has been stored in its own file, and the filename has
always matched the class name. In Java, you can create a class within another class and
store them together; such classes are nested classes. The containing class is the top-level
class. There are four types of nested classes:
• static member classes: A static member class has access to all static methods of the
top-level class.
• Nonstatic member classes, also known as inner classes: This type of class requires an
instance; it has access to all data and methods of the top-level class.
• Local classes: These are local to a block of code.
• anonymous classes: These are local classes that have no identifier.
The most common reason to nest a class inside another is because the inner class is used
only by the top-level class; in other words, it is a “helper class” to the top-level class. Being
able to package the classes together makes their connection easier to understand and their
code easier to maintain.
For example, consider a RealEstateListing class used by a real estate company to describe
houses that are available for sale. The class might contain separate fields for a listing
number, the price, the street address, and the house’s living area. As an alternative, you
might decide that although the listing number and price “go with” the real estate listing, the
street address and living area really “go with” the house. So you might create an inner class
like the one in Figure 4-46.
public class RealEstateListing
{
private int listingNumber;
private double price;
private HouseData houseData;
public RealEstateListing(int num, double price, String address,
int sqFt)
{
listingNumber = num;
this.price = price;
houseData = new HouseData(address, sqFt);
}
public void display()
{
System.out.println("Listing number #" + listingNumber +
" Selling for $" + price);
System.out println("Address: " + houseData.streetAddress);
System.out.println(houseData.squareFeet + " square feet");
}
Figure 4-46 The RealEstateListing class (continues)
97070_ch04_hr_170-229.indd 218 24/02/18 3:55 pm
219
Understanding Composition and Nested Classes
Notice that the inner HouseData class in Figure 4-46 is a private class. You don’t have to
make an inner class private, but doing so keeps its members hidden from outside classes.
If you wanted a class’s members to be accessible, you would not make it an inner class. An
inner class can access its top-level class’s fields and methods, even if they are private, and
an outer class can access its inner class’s members.
You usually will not want to create inner classes. For example, if you made the HouseData
class a regular class (as opposed to an inner class) and stored it in its own file, you could use
it with composition in other classes—perhaps a MortgageLoan class or an Appraisal class.
As it stands, it is usable only in the class in which it now resides. You probably will not
create nested classes frequently, but you will see them implemented in some built-in Java
classes.
This is an inner class.
(continued)
private class HouseData
{
private String streetAddress;
private int squareFeet;
public HouseData(String address, int sqFt)
{
streetAddress = address;
squareFeet = sqFt;
}
}
}
Figure 4-46 The RealEstateListing class
The false statement is #1. Composition describes the relationship between
classes when an object of one class is a data field within another class.
tWO trUthS & a LIe
Understanding Composition and Nested Classes
1. Exposition describes the relationship between classes when an object
of one class is a data field within another class.
2. When you use an object as a data member of another object, you must
remember to supply values for the contained object if it has no default
constructor.
3. A nested class resides within another class.
97070_ch04_hr_170-229.indd 219 24/02/18 3:55 pm
220
More Object Concepts C h a p t e r 4
Don’t Do It
• Don’t try to use a variable that is out of scope.
• Don’t assume that a constant is still a constant when passed to a method’s parameter.
If you want a parameter to be constant within a method, you must use final in the
parameter list.
• Don’t try to overload methods by giving them different return types. If their identifiers
and parameter lists are the same, then two methods are ambiguous no matter what their
return types are.
• Don’t think that default constructor means only the automatically supplied version.
A constructor with no parameters is a default constructor, whether it is the one that is
automatically supplied or one you write.
• Don’t forget to write a default constructor for a class that has other constructors if you
want to be able to instantiate objects without using arguments.
• Don’t assume that a wildcard in an import statement works like a DOS or UNIX wildcard.
The wildcard works only with specific packages and does not import embedded packages.
Key terms
block
outer block
inner block
nested
scope
comes into scope
goes out of scope
scope level
redeclare a variable
overrides
shadowing
closer in scope
overloading
ambiguous
reference
this reference
class methods
class variables
NaN
package
library of classes
java.lang
fundamental classes
optional classes
wildcard symbol
enumeration
nanosecond
composition
has-a relationship
nested classes
top-level class
static member class
nonstatic member classes
inner classes
local classes
anonymous classes
Chapter Summary
• A variable’s scope is the portion of a program within which it can be referenced. A block
is the code between a pair of curly braces. Within a method, you can declare a variable
with the same name multiple times, as long as each declaration is in its own nonover-
lapping block. If you declare a variable within a class and use the same variable name
within a method of the class, the variable used inside the method takes precedence over
(or overrides, or masks) the first variable.
97070_ch04_hr_170-229.indd 220 24/02/18 3:55 pm
221
Chapter Summary
• Overloading involves writing multiple methods with the same name but different
parameter lists. Methods that have identical parameter lists are illegal, even if they have
different return types.
• When you overload methods, you risk creating an ambiguous situation—one in which
the compiler cannot determine which method to use.
• When you write your own constructors, they can receive parameters. Such parameters
often are used to initialize data fields for an object. After you write a constructor for a
class, you no longer receive the automatically provided default constructor. If a class’s
only constructor requires an argument, you must provide an argument for every
object of the class that you create. You can overload constructors just as you can other
methods.
• Within nonstatic methods, data fields for the correct object are accessed because a this
reference is implicitly passed to nonstatic methods. Static methods do not have a this
reference because they have no object associated with them; static methods are also
called class methods.
• Static class fields and methods are shared by every instantiation of a class. When a field
in a class is final, it cannot change after it is assigned its initial value.
• Java contains hundreds of prewritten classes that are stored in packages, which are
folders that provide convenient groupings for classes. The java.lang package is
implicitly imported into every Java program. The classes it contains are the fundamental
classes, as opposed to the optional classes, which must be explicitly named. The class
java.lang.Math contains constants and methods that can be used to perform
common mathematical functions. The LocalDate and LocalDateTime classes allow
you to define and manipulate dates and time.
• Composition describes the relationship between classes when an object of one class is a
data field within another class. You can create nested classes that are stored in the same
file. The most common reason to nest a class inside another is because the inner class
is used only by the outer or top-level class; in other words, it is a “helper class” to the
top-level class.
Review Questions
1. The code between a pair of curly braces in a method is a _____________.
a. function
b. brick
c. block
d. sector
2. When a block exists within another block, the blocks are _____________.
a. structured
b. illegal
c. sheltered
d. nested
97070_ch04_hr_170-229.indd 221 24/02/18 3:55 pm
222
More Object Concepts C h a p t e r 4
3. The portion of a program within which you can reference a variable is the
variable’s _____________.
a. scope
b. space
c. domain
d. range
4. You can declare variables with the same name multiple times _____________.
a. within a statement
b. within a block
c. within a method
d. You never can declare multiple variables with the same name.
5. If you declare a variable as an instance variable within a class, and you declare
and use the same variable name within a method of the class, then within the
method, _____________.
a. the variable used inside the method takes precedence
b. the class instance variable takes precedence
c. the two variables refer to a single memory address
d. an error will occur
6. A method variable _____________ a class variable with the same name.
a. acquiesces to
b. destroys
c. overrides
d. alters
7. Nonambiguous, overloaded methods must have the same _____________.
a. types of parameters
b. number of parameters
c. parameter names
d. name
8. If a method is written to receive a double parameter, and you pass an integer to
the method, then the method will _____________.
a. work correctly; the integer will be promoted to a double
b. work correctly; the parameter type will automatically become an integer
c. execute, but any output will be incorrect
d. not work; an error message will be issued
9. A constructor _____________ parameters.
a. can receive
b. cannot receive
c. must receive
d. can receive a maximum of 10
10. A constructor _____________ overloaded.
a. must be
b. cannot be
c. can be
d. is always automatically
97070_ch04_hr_170-229.indd 222 24/02/18 3:55 pm
223
Chapter Summary
11. Usually, you want each instantiation of a class to have its own copy of
_____________.
a. the data fields
b. the class methods
c. both of the above
d. none of the above
12. If you create a class that contains one method, and instantiate two objects, you
usually store _____________ for use with the objects.
a. one copy of the method
b. two copies of the method
c. two different methods containing two different this references
d. data only (the methods are not stored)
13. The this reference _____________.
a. can be used implicitly
b. must be used implicitly
c. must not be used implicitly
d. must not be used
14. Methods that you reference with individual objects are _____________.
a. private
b. public
c. static
d. nonstatic
15. Variables that are shared by every instantiation of a class are _____________.
a. class variables
b. private variables
c. public variables
d. illegal
16. The keyword final used with a variable declaration indicates _____________.
a. the end of the program
b. a static field
c. a symbolic constant
d. that no more variables will be declared in the program
17. Java classes are stored in a folder or _____________.
a. packet
b. bundle
c. package
d. gaggle
18. Which of the following statements determines the square root of a number and
assigns it to the variable s?
a. s = sqrt(number);
b. s = Math.sqrt(number);
c. number = sqrt(s);
d. number = Math.sqrt(s);
19. A LocalDate object _____________.
a. can be displayed as a String
b. contains static fields with data such as the current year
c. is created using a public default constructor
d. all of the above
97070_ch04_hr_170-229.indd 223 24/02/18 3:55 pm
224
More Object Concepts C h a p t e r 4
20. Which of the following expressions correctly returns an integer that represents
the month of a LocalDate object named hireDate?
a. getMonth(hireDate)
b. getMonthValue(hireDate)
c. hireDate.getMonthValue()
d. all of the above
exercises
Programming Exercises
1. Create a class named FormLetterWriter that includes two overloaded methods
named displaySalutation(). The first method takes one String parameter that
represents a customer’s last name, and it displays the salutation Dear Mr. or Ms.
followed by the last name. The second method accepts two String parameters
that represent a first and last name, and it displays the greeting Dear followed by
the first name, a space, and the last name. After each salutation, display the rest of
a short business letter: Thank you for your recent order. Write a main() method
that tests each overloaded method. Save the file as FormLetterWriter.java.
2. Create a class named Billing that includes three overloaded computeBill()
methods for a photo book store.
• When computeBill() receives a single parameter, it represents the price of
one photo book ordered. Add 8% tax, and return the total due.
• When computeBill() receives two parameters, they represent the price of
a photo book and the quantity ordered. Multiply the two values, add 8% tax,
and return the total due.
• When computeBill() receives three parameters, they represent the price of a
photo book, the quantity ordered, and a coupon value. Multiply the quantity
and price, reduce the result by the coupon value, and then add 8% tax and
return the total due.
Write a main() method that tests all three overloaded methods. Save the
application as Billing.java.
3. a. Create a FitnessTracker class that includes data fields for a fitness activity,
the number of minutes spent participating, and the date. The class includes
methods to get each field. In addition, create a default constructor that
automatically sets the activity to running, the minutes to 0, and the date to
January 1 of the current year. Save the file as FitnessTracker.java. Create an
application that demonstrates each method works correctly, and save it as
TestFitnessTracker.java.
97070_ch04_hr_170-229.indd 224 24/02/18 3:55 pm
225
Exercises
b. Create an additional overloaded constructor for the FitnessTracker class
you created in Exercise 3a. This constructor receives parameters for each of
the data fields and assigns them appropriately. Add any needed statements
to the TestFitnessTracker application to ensure that the overloaded
constructor works correctly, save it, and then test it.
c. Modify the FitnessTracker class so that the default constructor calls
the three-parameter constructor. Save the class as FitnessTracker2.java.
Create an application to test the new version of the class, and name it
TestFitnessTracker2.java.
4. a. Create a class named BloodData that includes fields that hold a blood type
(the four blood types are O, A, B, and AB) and an Rh factor (the factors are
1 and –). Create a default constructor that sets the fields to O and 1, and
an overloaded constructor that requires values for both fields. Include get
and set methods for each field. Save this file as BloodData.java. Create an
application named TestBloodData that demonstrates each method works
correctly. Save the application as TestBloodData.java.
b. Create a class named Patient that includes an ID number, age, and
BloodData. Provide a default constructor that sets the ID number to 0, the age
to 0, and the BloodData values to O and 1. Create an overloaded constructor
that provides values for each field. Also provide get methods for each field.
Save the file as Patient.java. Create an application that demonstrates that
each method works correctly, and save it as TestPatient.java.
5. a. Create a class to hold data about a high school sports team. The Team
class holds data fields for high school name (such as Roosevelt High), sport
(such as Girls’ Basketball), and team name (such as Dolphins). Include a
constructor that takes parameters for each field, and include get methods
that return the values of the fields. Also include a public final static
String named MOTTO and initialize it to Sportsmanship!. Write an application
named TestTeam to instantiate three Team objects with different values, and
then display all the data, including the motto, for each object. Save both the
Team.java and TestTeam.java files.
b. Create a class named Game. Include two Team fields that hold data about
the teams participating in the game. Also include a field for game time (for
example, 7 PM). Include a constructor that takes parameters for two Team
objects and a time. Write an application named TestGame to instantiate a
Game object, then pass the Game to a method that displays the details about
the Game.
6. a. Create a class named Circle with fields named radius, diameter, and area.
Include a constructor that sets the radius to 1 and calculates the other two
values. Also include methods named setRadius() and getRadius(). The
setRadius() method not only sets the radius, but it also calculates the other
97070_ch04_hr_170-229.indd 225 24/02/18 3:55 pm
226
More Object Concepts C h a p t e r 4
two values. (The diameter of a circle is twice the radius, and the area of a cir-
cle is pi multiplied by the square of the radius. Use the Math class PI constant
for this calculation.) Save the class as Circle.java.
b. Create a class named TestCircle whose main() method declares several
Circle objects. Using the setRadius() method, assign one Circle a
small radius value, and assign another a larger radius value. Do not assign
a value to the radius of the third circle; instead, retain the value assigned
at construction. Display all the values for all the Circle objects. Save the
application as TestCircle.java.
7. Write a Java application that uses the Math class to determine the answers for
each of the following:
a. The square root of 37
b. The sine and cosine of 300
c. The value of the floor, ceiling, and round of 22.8
d. The larger and the smaller of the character ‘D’ and the integer 71
e. A random number between 0 and 20 (Hint: The random() method returns a
value between 0 and 1; you want a number that is 20 times...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here