100% found this document useful (10 votes)
7K views830 pages

Murach's Java Programming

Belajar Javs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (10 votes)
7K views830 pages

Murach's Java Programming

Belajar Javs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 830

M urach

mu rach's

programming
4™ EDITION
JOEL MURACH

A CORE JAVA BOOK


that teaches you the Java essentials
at a professional pace,
using the time-saving features ofNetBeans

AN OBJECT-ORIENTED BOOK
that shows you how ro use business classes,
inheritance, and interfaces the way they’re
used in the real world

A GUI PROGRAMMING BOOK


that show's you how to develop graphical user
interfaces that handle events and validate data

A DATA ACCESS BOOK


that shows you how to develop
3-tier, object-oriented, database applications
the way the pros do it
TRAINING & REFERENCE

murach's

programming
4th EDITION
Joel Murach

M ike M u r a c h & A sso ciates , I n c .


4340 N. Knoll Ave. · Fresno, CA 93722
www.murach.com · [email protected]
Author: Joel Murach
Editor: Anne Boehm
Cover design: Zylka Design
Production: Maria Pedroza David

Books for Java programmers


Murach’s Java Programming
Murach’s Java Servlets and JSP

Books for database programmers


Murach’s Oracle SQL and PL/SQL
Murach’s MySQL
Murach’s SQL Server fo r Developers

Books for web developers


Murach ’s HTML5 and CSS3
Murach’s JavaScript and DOM Scripting
Murach’s PHP and MySQL

Books for .NET programmers


Murach’s C # 2010
Murach’s ASP.NET 4 Web Programming with C#2010
Murach’s ADO.NET 4 Database Programming with C# 2010
Murach’s Visual Basic 2010
Murach’s ASP.NET 4 Web Programming with VB 2010
Murach’s ADO.NET 4 Database Programming with VB 2010

Books for IBM mainframe programmers


Murach’s OS/390 and z/OS JCL
Murach’s Mainframe COBOL
Murach’s CICSforthe COBOL Programmer
DB2 for the COBOL Programmer, Part 1

© 2011, Mike Murach & Associates, Inc.


All rights reserved.

Printed in the United States of America

10 9 8 7 6 5 4 3 2 1
ISBN: 978-1-890774-65-3
Contents
Introduction XV

S ection 1 Essential Java skills


Chapter 1 How to get started with Java and NetBeans 3
Chapter 2 Introduction to Java programming 35
Chapter 3 How to work with data 79
Chapter 4 How to code control statements 111
Chapter 5 How to validate input data 145
Chapter 6 How to test and debug an application 167

S ection 2 O b ject-oriented program m ing w ith Java


Chapter 7 How to define and use classes 185
Chapter 8 How to work with inheritance 237
Chapter 9 How to work with interfaces 275
Chapter 10 Other object-oriented programming skills 311

S ection 3 M ore Jav a skills


Chapter 11 How to work with arrays 339
Chapter 12 How to work with collections and generics 363
Chapter 13 How to work with dates and strings 405
Chapter 14 How to handle exceptions 431

S ection 4 GUI program m ing w ith Swing


Chapter 15 How to develop a form 459
Chapter 16 How to work with controls and handle events 501
Chapter 17 How to develop and deploy applets 537

S ection 5 D ata access program m ing w ith Java


Chapter 18 How to work with text and binary files 559
Chapter 19 How to work with XML 613
Chapter 20 How to work with a Derby database 645
Chapter 21 How to use JDBC to work with a database 677

S ection 6 Advanced J ava skills


Chapter 22 How to work with threads 717
Chapter 23 How to deploy an application 751

A ppendixes
Appendix A How to set up your PC for this book 771
Appendix B How to set up your Mac for this book 111
E x p a n d e d c o n te n ts

Section 1 Essential Java skills


Chapter 1 How to get started with Java and NetBeans
Introduction to Java............................................................................. 4
Toolkits and platforms..................................................................................................... 4
How Java compares to C++ and C #................................................................................. 4
Applications, applets, and servlets.................................................................................. 6
The code for the console version of the Future Value application.................................. 8
How Java compiles and interprets code....................................................................... 10
Introduction to Java ID E s............................................................................................. 12
How to use NetBeans to work with existing projects................... 14
Introduction to Java projects and the NetBeans ID E ................................................... 14
How to open, close, and delete a project..................................................................... 16
How to compile and run a project................................................................................. 16
How to use the Output window with a console application........................................ 18
How to work with two or more projects........................................................................ 20
How to use NetBeans to develop new projects............................ 22
How to create a new project.......................................................................................... 22
How to set the Java version for a project....................................................................... 24
How to work with Java source code and files................................................................26
How to use the code completion feature........................................................................ 28
How to detect and correct syntax errors........................................................................ 30

Chapter 2 Introduction to Java programming


Basic coding skills............................................................................36
How to code statements................................................................................................. 36
How to code comments................................................................................................. 36
How to create identifiers.................................................................................................38
How to declare a class and a main method....................................................................40
How to work with numeric variables...............................................42
How to declare and initialize variables..........................................................................42
How to code assignment statements..............................................................................44
How to code arithmetic expressions..............................................................................44
How to work with string variables...................................................46
How to create a String object......................................................................................... 46
How to join and append strings..................................................................................... 46
How to include special characters in strings..................................................................48
How to use Java classes, objects, andmethods............................50
How to create objects and call methods........................................................................ 50
How to import Java classes............................................................................................ 52
How to use the API documentation to research Java classes........................................ 54
How to use the console for input and output................................ 56
How to use the System.out object to print output to the console................................. 56
How to use the Scanner class to read input from the console...................................... 58
Examples that get input from the console.....................................................................60
How to code simple control statements........................................ 62
How to compare numeric variables............................................................................... 62
How to compare string variables................................................................................... 62
How to code if/else statements...................................................................................... 64
How to code while statements....................................................................................... 66
Expanded contents V

Two illustrative applications............................................................. 68


The Invoice application.................................................................................................. 68
The Test Score application..............................................................................................70
How to test and debug an application............................................. 72
How to test an application..............................................................................................72
How to debug an application..........................................................................................72

Chapter 3 How to work with data


Basic skills for working with d a ta .................................................... 80
The eight primitive data types........................................................................................80
How to declare and initialize variables........................................................................ 82
How to declare and initialize constants....................................................................... 84
How to code assignment statements and arithmetic expressions.................................. 86
How to use the shortcut assignment operators...............................................................88
How to work with the order of precedence.................................................................... 90
How to work with casting...............................................................................................92
How to use Java classes for working with data typ es................... 94
How to use the NumberFormat class........................................................................... 94
How to use the Math class........................................................................................... 96
How to use the Integer and Double classes.................................................................98
The formatted Invoice application.................................................. 100
The code for the application....................................................................................... 100
A bug in the arithmetic............................................................................................... 102
How to debug the application..................................................................................... 102
How to use the BigDecimal class................................................... 104
The constructors and methods.................................................................................... 104
How to use BigDecimal arithmetic............................................................................. 106

Chapter 4 How to code control statements


How to code Boolean expressions................................................. 112
How to compare primitive data types......................................................................... 112
How to compare strings.............................................................................................. 114
How to use the logical operators................................................................................ 116
How to code if/else and switch statements................................... 118
How to code if/else statements................................................................................... 118
How to code switch statements................................................................................... 120
An enhanced version of the Invoice application......................................................... 124
How to code loops............................................................................126
How to code while and do-while loops...................................................................... 126
How to code for loops................................................................................................. 128
The Future Value application...................................................................................... 130
How to code nested loops........................................................................................... 132
How to code break and continue statements................................ 134
How to code break statements.................................................................................... 134
How to code continue statements.................................................................................136
How to code and call static methods............................................. 138
How to code static methods........................................................................................ 138
How to call static methods.......................................................................................... 138
The Future Value application with a static method..................................................... 140
Expanded contents

Chapter 5 How to validate input data


How to handle exceptions............................................................... 146
How exceptions w ork...................................................................................................146
How to catch exceptions............................................................................................. 148
The Future Value application with exception handling...............................................150
How to validate data......................................................................... 152
How to prevent exceptions from being thrown.......................................................... 152
How to validate a single entry................................................................................... 154
How to use generic methods to validate an entry...................................................... 156
The Future Value application with data validation........................158
The console................................................................................................................. 158
The co d e....................................................................................................................... 160

Chapter 6 How to test and debug an application


Basic skills for testing and debugging.......................................... 168
Typical test phases...................................................................................................... 168
The three types of errors............................................................................................. 168
Common Java errors.....................................................................................................170
A simple way to trace code execution....................................................................... 172
How to use NetBeans to debug an application.............................174
How to set and remove breakpoints........................................................................... 174
How to step through code........................................................................................... 176
How to inspect variables...............................................................................................176
How to inspect the stack trace.................................................................................... 178

Section 2 Object-oriented programming with Java

Chapter 7 How to define and use classes


An introduction to classes.............................................................. 186
How classes can be used to structure an application................................................. 186
How encapsulation works.............................................................................................188
The relationship between a class and its objects......................................................... 190
How to code a class that defines an object...................................192
How to use NetBeans to create a new class............................................................... 192
The code for the Product class.................................................................................... 194
How to code instance variables.................................................................................. 196
How to code constructors........................................................................................... 198
How to code m ethods.................................................................................................. 200
How to overload methods............................................................................................ 202
How to use the this keyword........................................................................................ 204
How to use NetBeans to work with classes.................................................................206
How to create and use an object....................................................208
How to create an object............................................................................................... 208
How to call the methods of an object.......................................................................... 210
How primitive types and reference types are passed to a method.............................. 212
A ProductDB class that creates a Product object........................................................214
A ProductApp class that uses a Product object...........................................................216
How to code and use static fields and methods...........................218
How to code static fields and methods........................................................................ 218
How to call static fields and methods.......................................................................... 220
How to code a static initialization block......................................................................222
When to use static fields and methods.........................................................................222
Expanded contents

The Line Item application................................................................ 224


The console...................................................................................................................224
The class diagrams....................................................................................................... 224
The code for the classes................................................................................................226

Chapter 8 How to work with inheritance


An introduction to inheritance........................................................ 238
How inheritance works.................................................................................................238
How the Java API uses inheritance.............................................................................. 240
How the Object class works......................................................................................... 242
How to use inheritance in your applications................................................................244
Basic skills for working with inheritance.......................................246
How to create a superclass........................................................................................... 246
How to create a subclass...............................................................................................248
How polymorphism works........................................................................................... 250
The Product application.................................................................. 252
The console...................................................................................................................252
The ProductApp class.................................................................................................. 254
The Product, Book, and Software classes.................................................................... 256
The ProductDB class....................................................................................................256
More skills for working with inheritance........................................260
How to get information about an object’s type............................................................260
How to cast objects...................................................................................................... 262
How to compare objects.............................................................................................. 264
How to work with the abstract and finalkeywords....................... 266
How to work with the abstract keyword...................................................................... 266
How to work with the final keyword......................................................................... 268

Chapter 9 How to work with interfaces


An introduction to interfaces.......................................................... 276
A simple interface.........................................................................................................276
Interfaces compared to abstract classes....................................................................... 278
Some interfaces of the Java A P I.................................................................................. 280
How to work with interfaces............................................................282
How to code an interface........................................................................................... 282
How to implement an interface.................................................................................... 284
How to inherit a class and implement an interface......................................................286
How to use an interface as a parameter..................................................................... 288
How to use inheritance with interfaces...................................................................... 290
How to use NetBeans to work with interfaces...........................................................292
A Product Maintenance application thatuses interfaces.............294
The class diagram.........................................................................................................294
The console...................................................................................................................296
The DAOFactory class..................................................................................................298
The ProductTextFile class............................................................................................ 298
The ProductMaintApp class........................................................................................ 300
How to implement the Cloneable interface...................................304
A Product class that implements the Cloneable interface...........................................304
A Lineltem class that implements the Cloneable interface........................................ 306
Viiî Expanded contents

Chapter 10 Other object-oriented programming skills


How to work with packages.............................................................312
An introduction to packages.........................................................................................312
How to use NetBeans to work with packages.............................................................. 314
How to use NetBeans to work with libraries................................................................316
How to use javadoc to document a package................................. 318
How to add javadoc comments to a class.....................................................................318
How to use HTML and javadoc tags in javadoc comments......................................... 320
How to use NetBeans to generate documentation....................................................... 322
How to view the documentation for a package............................................................ 322
How to code classes that are closely related................................ 324
How to code more than one class per file.....................................................................324
An introduction to nested classes.................................................................................326
How to work with enumerations..................................................... 328
How to declare an enumeration....................................................................................328
How to use an enumeration.......................................................................................... 328
How to enhance an enumeration...................................................................................330
How to work with static imports...................................................................................330

Section 3 More Java skills

Chapter 11 How to work with arrays


Basic skills for working with arrays............................................... 340
How to create an array.................................................................................................. 340
How to assign values to the elements of an array........................................................ 342
How to use for loops with arrays..................................................................................344
How to use enhanced for loops with arrays..................................................................346
More skills for working with arrays................................................ 348
The methods of the Arrays class................................................................................... 348
Code examples that work with the Arrays class.......................................................... 350
How to implement the Comparable interface.............................................................. 352
How to create a reference to an array...........................................................................354
How to copy an array.................................................................................................... 354
How to work with two-dimensional arrays.................................... 356
How to work with rectangular arrays...........................................................................356
How to work with jagged arrays................................................................................... 358

Chapter 12 How to work with collections and generics


An introduction to Java collections............................................... 364
A comparison of arrays and collections.......................................................................364
An overview of the Java collection framework............................................................366
An introduction to generics.......................................................................................... 368
How to use the ArrayList class....................................................... 370
The ArrayList class....................................................................................................... 370
Code examples that work with array lists.....................................................................372
An Invoice application that uses an array lis t............................... 374
An overview of the Invoice application........................................................................374
The code for the Invoice class......................................................................................376
The code for the InvoiceApp class...............................................................................378
Expanded contents ix

How to use the LinkedList class..................................................... 380


The LinkedList class..................................................................................................... 380
Code examples that work with linked lists...................................................................382
A class that uses a linked list to implement a generic queue....................................... 384
An enhanced version of the Invoice application........................... 386
An overview of the enhanced Invoice application....................................................... 386
The code for the InvoiceApp class...............................................................................388
How to work with m aps................................................................... 392
The HashMap and TreeMap classes.............................................................................392
Code examples that work with hash maps and tree m aps........................................... 394
How to work with legacy collections.............................................. 396
An introduction to legacy collection classes................................................................ 396
How to use an untyped collection.................................................................................398
How to use wrapper classes with untyped collections................................................. 400

Chapter 13 How to work with dates and strings


How to work with dates and tim es................................................. 406
How to use the GregorianCalendar class to set dates and times.................................. 406
How to use the Calendar and GregorianCalendar fields and methods........................408
How to use the Date class.............................................................................................410
How to use the DateFormat class to format dates and tim es....................................... 412
A DateUtils class that provides methods for handling dates....................................... 414
An Invoice class that includes an invoice date............................................................. 416
How to work with the String class.................................................. 418
Constructors of the String class....................................................................................418
Code examples that create strings.................................................................................418
Methods of the String class..........................................................................................420
Code examples that work with strings......................................................................... 422
How to work with the StringBuilder class..................................... 424
Constructors and methods of the StringBuilder class.................................................. 424
Code examples that work with the StringBuilder class............................................... 426

Chapter 14 How to handle exceptions


An introduction to exceptions........................................................ 432
The exception hierarchy...............................................................................................432
How exceptions are propagated....................................................................................434
How to work with exceptions.......................................................... 436
How to use the try statement........................................................................................ 436
How to use the try-with-resources statement............................................................... 438
How to use the methods of an exception..................................................................... 440
How to use a multi-catch block....................................................................................442
How to use the throws clause.......................................................................................444
How to use the throw statement....................................................................................446
How to work with custom exception classes................................ 448
How to create your own exception class.......................................................................448
How to use exception chaining.....................................................................................450
How to work with assertions........................................................... 452
How to code assert statements......................................................................................452
How to enable and disable assertions.......................................................................... 452
Expanded contents

Section 4 GUI programming with Swing


Chapter 15 How to develop a form
An introduction to S w ing.................................................................460
The user interface for the Future Value Calculator application................................... 460
The inheritance hierarchy for Swing components....................................................... 462
How to design a form........................................................................464
How to create a project for a GUI application...........................................................464
How to add a form to a project.................................................................................. 464
How to add controls to a form ................................................................................... 466
How to set properties.................................................................................................... 468
Common properties for forms and controls................................................................. 470
How to add code to a form .............................................................. 472
How to set the variable name for a control................................................................472
How to create an event handler for a control.............................................................474
How to rename or remove an event handler................................................................ 476
How to enter the code for a form..................................................................................478
Common methods for controls.....................................................................................480
How to display and center a form.................................................................................482
The code for the FutureValueFrame class................................................................... 484
How to validate Swing input data................................................... 486
How to display error messages.....................................................................................486
How to validate the data entered into a text field ........................................................ 488
The SwingValidator class............................................................................................. 490
How to validate multiple entries...................................................................................492
The Future Value application...........................................................494
The user interface......................................................................................................... 494
The co d e........................................................................................................................494

Chapter 16 How to work with controls and handle events


How to work with components........................................................502
How to work with text areas......................................................................................... 502
How to work with check boxes..................................................................................... 504
How to work with radio buttons...................................................................................506
How to work with combo boxes...................................................................................508
How to work with lists.................................................................................................. 510
The Payment application..................................................................514
The user interface......................................................................................................... 514
The co d e........................................................................................................................514
How to code low-level events..........................................................518
A summary of low-level events....................................................................................518
How to work with focus events....................................................................................520
How to work with keyboard events..............................................................................522
The Product Maintenance application........................................... 524
The user interface......................................................................................................... 524
The co d e........................................................................................................................526

Chapter 17 How to develop and deploy applets


An introduction to applets...............................................................538
The Future Value Calculator applet..............................................................................538
A brief history of applets.............................................................................................. 538
Applet security issues................................................................................................... 540
The inheritance hierarchy for applets...........................................................................542
Four methods of an applet............................................................................................ 542
Expanded contents XI

How to develop applets................................................................... 544


How to develop a panel for an applet.......................................................................... 544
How to code an applet..................................................................................................546
How to test an applet with the Applet Viewer............................................................. 546
How to deploy applets..................................................................... 548
A procedure for deploying an applet........................................................................... 548
How to create an HTML document for an applet........................................................ 550
How to run an applet within a web browser................................................................ 552

Section 5 Data access programming with Java


Chapter 18 How to work with text and binary files
Introduction to directories and files............................................... 560
A package for working with directories and files........................................................ 560
Code examples that work with directories and files....................................................562
Introduction to file input and output.............................................. 564
How files and streams work..........................................................................................564
A file I/O example........................................................................................................ 566
How to work with I/O exceptions.................................................................................568
How to work with text files .............................................................. 570
How to connect a character output stream to a file...................................................... 570
How to write to a text file .............................................................................................572
How to connect a character input stream to a file........................................................574
How to read from a text file..........................................................................................576
An interface for working with file I/O ......................................................................... 578
A class that works with a text file.................................................................................580
How to work with binary files.......................................................... 584
How to connect a binary output stream to a file.......................................................... 584
How to write to a binary file.........................................................................................586
How to connect a binary input stream to a file............................................................ 588
How to read from a binary file......................................................................................590
Two ways to work with binary strings......................................................................... 592
How to work with random-access files.......................................... 594
How to connect to a random-access file ...................................................................... 594
How to read to and write from a random-access file................................................... 596
How to read and write fixed-length strings.................................................................. 598
A class that works with a random-access file.............................................................. 600

Chapter 19 How to work with XML


Introduction to X M L ......................................................................... 614
An XML document.......................................................................................................614
XML tags, declarations, and comments...................................................................... 616
XML elements.............................................................................................................. 616
XML attributes.............................................................................................................. 618
An introduction to DTDs..............................................................................................620
How to view and edit an XML file.................................................... 622
How to view an XML file.............................................................................................622
How to edit an XML file...............................................................................................622
An introduction to three XML APIs................................................. 624
DOM ............................................................................................................................. 624
SA X .............................................................................................................................. 624
StAX............................................................................................................................. 624
xii Expanded, contents

How to use StAX to work with XML...............................................626


How to create an XMLStreamWriter object................................................................ 626
How to write X M L ....................................................................................................... 628
How to create an XMLStreamReader object............................................................... 630
How to read XML......................................................................................................... 632
A class that works with an XML file............................................................................636

Chapter 20 How to work with a Derby database


How a relational database is organized....................................... 646
How a table is organized............................................................................................... 646
How the tables in a database are related.......................................................................648
How the columns in a database are defined................................................................. 650
How to use SQL to work with the data in a database................. 652
How to query a single table..........................................................................................652
How to join data from two or more tables................................................................... 654
How to add, update, and delete data in a table............................................................ 656
An introduction to Derby................................................................658
An overview of D erby.................................................................................................. 658
How to configure your system to work with a Derby database...................................660
How to use the ij tool to work with a Derby database................ 662
How to start and stop the ij tool....................................................................................662
How to connect to and disconnect from a database..................................................... 662
How to create a database and connect to i t .................................................................. 664
How to run SQL statements....................................................................................... 664
How to run SQL scripts from the ij prompt...............................................................666
How to run SQL scripts from the command prompt.................................................668
How to start and stop the Derby database server...................... 670
How to start the server................................................................................................670
How to stop the server................................................................................................670
How to learn more about Derby.....................................................672
How to view the Derby documentation....................................................................... 672
How to navigate through the documentation............................................................... 672

Chapter 21 How to use JDBC to work with databases


An introduction to Java database drivers................................... 678
The four driver types..................................................................................................... 678
How to add a database driver to a project.................................................................... 680
How to use Java to connect to a database...................................682
How to load a database driver.......................................................................................682
How to connect to an embedded database................................................................... 684
How to disconnect from an embedded database.......................................................... 686
How to connect to a networked database..................................................................... 688
How to use Java to work with a database................................... 690
How to return a result set..............................................................................................690
How to move the cursor through a result s e t............................................................... 692
How to return data from a result s e t............................................................................ 694
How to modify data in a database.................................................................................696
How to work with prepared statements....................................................................... 698
Two classes for working with databases..................................... 700
A utility class for working with strings....................................................................... 700
A class that works with a database...............................................................................702
Expanded contents xiii

An introduction to working with metadata....................................708


How to work with metadata......................................................................................... 708
How SQL data types map to Java data types...............................................................710

Section 6 Advanced Java skills


Chapter 22 How to work with threads
An introduction to threads.............................................................. 718
How threads work.........................................................................................................718
Typical uses for threads............................................................................................... 718
Classes and interfaces for working with threads.........................................................720
The life cycle of a thread............................................................................................. 722
How to create threads...................................................................... 724
Constructors and methods of the Thread class............................................................724
How to create a thread by extending the Thread class................................................726
How to create a thread by implementing the Runnable interface............................... 728
How to manipulate threads............................................................. 730
How to set a thread’s priority....................................................................................... 730
How to interrupt a thread............................................................................................. 732
How to synchronize threads........................................................... 734
How to create synchronized threads............................................................................734
How to communicate among threads.......................................................................... 736
The Order Queue application..........................................................738
The operation................................................................................................................738
The classes....................................................................................................................740
The OrderQueueApp class........................................................................................... 742
The Order class.............................................................................................................742
The OrderTaker class................................................................................................... 744
The OrderHandler class............................................................................................... 746
The QrderQueue class................................................................................................. 746

Chapter 23 How to deploy an application


An introduction to deployment....................................................... 752
How executable JAR files work................................................................................... 752
How Java Web Start w orks.......................................................................................... 752
How an installer program works.................................................................................. 752
How to use an executable JAR file ................................................. 754
How to create an executable JAR file.......................................................................... 754
How to deploy a GUI application................................................................................ 756
How to deploy a console application........................................................................... 758
How to use Java Web Start.............................................................. 760
A procedure for using Java Web S tart......................................................................... 760
How to create a JNLP file............................................................................................ 762
How to create an HTML document that launches an application.............................. 764
How to deploy an application to a remote web server.................................................766
How to launch an application...................................................................................... 768
How to fix a common problem.................................................................................... 768
Introduction
Since its release in 1996, the Java language has established itself as one of
the leading languages for object-oriented programming. Today, Java continues
to be one of the most popular languages for application development, especially
for web applications and for mobile applications like Android apps. And that’s
going to continue for many years to come, for several reasons.
First, developers can obtain Java and a wide variety of tools for working
with Java for free. Second, Java code can run on any modem operating system.
Third, Java’s development has been guided largely by the Java community, and
Sun Microsystems released most of Java as open source software in 2007. As a
result, the Java platform is able to evolve according to the needs of the
programmers who use the language. Although Sun was acquired by Oracle
Corporation in 2010, Oracle has committed itself to supporting Java and the
Java community.

Who this book is for


This book is for anyone who wants to learn the core features of the Java
language. It works if you have no programming experience at all. It works if
you have programming experience with another language. It works if you
already know an older version of Java and you want to get up-to-speed with the
latest version. And it works if you’ve already read three or four other Java books
and still don’t know how to develop a real-world application.
If you’re completely new to programming, the prerequisites are minimal.
You just need to be familiar with the operation of the platform that you’re using.
If, for example, you’re developing programs using Windows on a PC, you
should know how to use Windows to perform tasks like opening, saving,
printing, closing, copying, and deleting files.

What version of Java this book supports


This book is designed to work with the Java Platform, Standard Edition 7
(Java SE 7) or later. This edition of Java includes the Java Development Kit
(JDK). For marketing reasons, Oracle sometimes refers to this version of the
JDK as JDK 7. However, from a developer’s point of view, this version of the
JDK is commonly referred to as version 1.7.
Introduction

As you work with Java SE 7, please keep in mind that all Java versions are
backwards-compatible. That means that everything in this book will also work
with future versions of the JDK.

What operating systems this book supports


The Oracle web site provides the most current version of the JDK for the
Windows, Linux, and Solaris operating systems. As this book goes to press, the
Mac OS X operating system includes JDK 1.6, and there are some unofficial
builds available for JDK 1.7. Before long, OS X will provide support for JDK
1.7. Until then, you can install an unofficial build as described in appendix B.
Since most Java development today is done under Windows, this book uses
Windows to illustrate any platform-dependent procedures. However, whenever
possible, we describe these procedures for other operating systems too. For
example, appendix B shows how to install the software for this book on Mac
OS X. However, if you’re using another platform such as Linux or Solaris, you
may need to search the Internet for more information about performing these
platform-dependent procedures. Fortunately, if you use NetBeans as described
in this book, there are very few platform-dependent procedures.

What IDE this book supports


This book shows you how to use the NetBeans IDE (Integrated
Development Environment) to code, test, and debug applications. Although
there are other excellent IDEs for working with Java, we decided to present
NetBeans because we think it’s the best IDE for getting started with Java. It’s
intuitive, easy to use, available for free, and it runs on all operating systems.
Even if you want to use another IDE such as Eclipse, we recommend that
you use NetBeans to work with the applications presented in this book. Then,
once you’re done with this book, it should be easy for you to switch from
NetBeans to another IDE. However, if you’d prefer to get started with another
IDE right away, you can do that too. But first, you’ll need to convert the
NetBeans projects that are available from our web site so you can work with
them in your preferred IDE.

How to get the software you need


You can download all of the software that you need for this book for free
from the Internet. To make that easier for you, appendix A shows how to
download and install the JDK as well as NetBeans on a PC. Similarly, appendix
B shows how to download and install the JDK, NetBeans, and Derby on a Mac.
That’s all the software you need to start developing professional Java
applications on your own.
Introduction XVII

What you’ll learn in this book


Unlike competing books, this one focuses on the practical features that
you’ll need for developing professional Java applications. Here’s a quick tour:
• In section 1, you’ll quickly master the basics of the Java language. In chapter
1, you’ll learn how to get started with NetBeans. In chapter 2, you’ll learn
how to write console applications that use the Scanner class to get input
from the user. By the end of chapter 5, you’ll know how to code applications
that use custom methods to validate user input so they won’t crash. And in
chapter 6, you’ll learn how to use NetBeans to thoroughly test and debug
your applications.
• In section 2, you’ll learn how to use Java for object-oriented programming.
In chapter 7, you’ll learn how to create and use your own classes, which is
the basis for developing applications that are easier to test, debug, and
maintain. Then, in chapters 8 through 10, you’ll learn how to develop more
sophisticated classes that use inheritance, interfaces, packages, type-safe
enumerations, and the factory pattern. In addition, you’ll learn how to use
the three-tiered architecture that’s the standard used by most professionals
for designing and developing object-oriented, database applications.
• In section 3, you’ll learn more of the core Java features that you’ll use all the
time. In chapters 11 through 14, for instance, you’ll learn how to work with
arrays, collections, dates, strings, and exceptions. Along the way, you’ll
learn how to use features such as enhanced for loops, typed collections,
generics, and the StringBuilder class. You’ll also learn how to use JDK 1.7
features such as the try-with-resources statement.
• In section 4, you’ll learn how to use a built-in tool provided by NetBeans to
develop graphical user interfaces (GUIs). We highly recommend this
approach for getting started with GUI programming. First, you’ll learn how
to use Swing components to develop real-world GUI applications that handle
events, validate data, and populate objects. Then, you’ll learn how to develop
applets, a special type of Java application that can be downloaded from the
Internet and run within a web browser.
• Because storing data is critical to most applications, section 5 shows you
how to store data in a file or database. In chapter 18, you’ll learn how to
work with text files and binary files, including random-access files. In
chapter 19, you’ll learn how to use an API known as StAX (the Streaming
API for XML) that was introduced with JDK 1.6 to work with XML
documents and files. In chapter 20, you’ll learn how to work with the open-
source Apache Derby database. And in chapter 21, you’ll learn how to use
JDBC to work with any database.
• In section 6, you’ll learn some advanced Java skills. In chapter 22, you’ll
learn how to use threads so your applications can perform two or more tasks
at the same time. Finally, in chapter 23, you’ll learn how to deploy your
finished applications using executable JAR files or Java Web Start.
XVÎii Introduction

Why you’ll learn faster and better with this book


Like all our books, this one has features that you won’t find in competing
books. That’s why we believe that you’ll learn faster and better with our book
than with any other. Here are just three of those features.
• To help you develop applications at a professional level, this book presents
complete, non-trivial applications. For example, chapter 16 presents a
Product Maintenance application that uses presentation classes, business
classes, and data access classes. You won’t find complete, real-world
applications like this in other Java books even though studying these types of
applications is the best way to master Java development.
• All of the information in this book is presented in our unique paired-pages
format, with the essential syntax, guidelines, and examples on the right page
and the perspective and extra explanation on the left page. This helps you
learn more while reading less, and it helps you quickly find the information
that you need when you use this book for reference.
• The exercises at the end of each chapter give you a chance to try out what
you’ve just learned. They guide you through the development of some of the
book’s applications, and they challenge you to apply what you’ve learned in
new ways. As a result, you’ll gain valuable, hands-on experience in Java
programming that will build both your skills and your confidence.

How our downloadable files make learning easier


To make learning easier, you can download the source code for all the
applications presented in this book from our web site (www.murach.com). This
source code includes the files and databases required by these applications.
Then, you can view the complete code for these applications as you read each
chapter; you can run these applications to see how they work; and you can copy
portions of code for use in your own applications.
You can also download the source code that you need for doing the
exercises in this book. That way, you don’t have to start every exercise from
scratch. This takes the busywork out of doing these exercises so you can get
more practice in less time. For more information about these downloads, please
see appendix A (Windows) and appendix B (Mac OS X).
Introduction

Support materials for trainers and instructors


If you’re a corporate trainer or a college instructor who would like to use
this book for a course, we offer an Instructor’s CD that includes: (1) a complete
set of PowerPoint slides that you can use to review and reinforce the content of
the book; (2) instructional objectives that describe the skills a student should
have upon completion of each chapter; (3) the solutions to the exercises in this
book; (4) projects that the students start from scratch; (5) solutions to those
projects; and (6) test banks that measure mastery of those skills.
To learn more about this Instructor’s CD and to find out how to get it, please
go to our web site at www.murach.com and click the Trainers link or Instructors
link. Or, if you prefer, you can call Kelly at 1-800-221-5528 or send an email to
kellv @murach.com.

A companion book for web developers


Since web programming is one of the primary uses of Java, we also offer a
book on web programming called Murach’s Java Servlets and JSP. It shows you
how to use Java servlets and JavaServer Pages as you develop professional web
applications. As you read that book, you’ll discover that Java web programming
requires most of the skills that are presented in sections 1-3 of this book. That’s
why we see this book as the perfect companion for Murach ’s Java Servlets and
JSP.

Please let us know how this book works for you


When we started the first edition of this book, our goals were (1) to teach
you Java as quickly and easily as possible and (2) to teach you the practical Java
concepts and skills that you need for developing real-world business
applications. We’ve tried to improve on that with each subsequent edition, and
as this fourth edition goes to press, we hope that the book is more effective than
ever before. Many of the improvements have come from the feedback we’ve
received from our readers, so if you have any comments about this book, we
would appreciate hearing from you at murachbooks @murach.com.
Thanks for buying this book. We hope you enjoy reading it, and we wish
you great success with your Java programming.

Joel Murach Anne Boehm


Author Editor
Section 1

Essential Java skills


This section gets you started quickly with Java programming. First,
chapter 1 introduces you to Java applications and shows you how to use
NetBeans to work with Java projects. Then, chapter 2 introduces you to the
basic skills that you need for developing Java applications. When you
complete these chapters, you’ll be able to write, test, and debug simple
applications of your own.
After that, chapter 3 presents the details for working with numeric
data. Chapter 4 presents the details for coding control statements. Chapter
5 shows how to validate the data that’s entered by the user. And chapter 6
shows how to thoroughly test and debug an application. These are the
essential skills that you’ll use in almost every Java application that you
develop. When you finish these chapters, you’ll be able to write solid
programs of your own. And you’ll have the background that you need for
learning how to develop object-oriented programs.
1

How to get started


with Java and NetBeans
Before you can begin learning the Java language, you need to install Java. In
addition, you need to choose an IDE or a text editor for working with Java. For
this book, we recommend that you use the NetBeans IDE. Appendix A of this
book shows you how to install both Java and NetBeans on a Windows system,
and appendix B shows you how to install them on a Macintosh OS X system.
Then, this chapter shows how to use the NetBeans IDE to create and work with
a Java application. But first, this chapter presents some background information
about Java.

Introduction to Java ................................................................ 4


Toolkits and platforms...................................................................................... 4
How Java compares to C++ and C # .................................................................4
Applications, applets, and servlets................................................................... 6
The code for the console version of the Future Value application...................8
How Java compiles and interprets code.......................................................... 10
Introduction to Java ID Es................................................................................12
How to use NetBeans to work with existing projects...... 14
Introduction to Java projects and the NetBeans IDE......................................14
How to open, close, and delete a project........................................................ 16
How to compile and run a project.................................................................. 16
How to use the Output window with a console application...........................18
How to work with two or more projects.........................................................20
How to use NetBeans to develop new projects.................. 22
How to create a new project........................................................................... 22
How to set the Java version for a project........................................................24
How to work with Java source code and file s................................................26
How to use the code completion feature........................................................28
How to detect and correct syntax errors.........................................................30
Perspective............................................................................. 32
Section 1 Essential Java skills

Introduction to Java
In 1996, Sun Microsystems released a new programming language called
Java. Although Oracle bought Sun in 2010, Java remains one of the most widely
used object-oriented programming languages.

Toolkits and platforms


Figure 1-1 describes all major releases of Java starting with version 1.0 and
ending with version 1.7. Throughout Java’s history, the terms Java Development
Kit (JDK) and Software Development Kit (SDK) have been used to describe the
Java toolkit. In this book, we’ll use the term JDK since it’s the most current and
commonly used term. In addition, different numbering schemes have been used
to indicate the version of Java. For example, Java 5.0 and Java 6 refer to ver­
sions 1.5 and 1.6 of Java. In this book, we’ll use the 1.x style of numbering
since this numbering is used by the documentation for Java.
With versions 1.2 through 1.5 of the JDK, the Standard Edition (SE) of Java
was known as Java 2 Platform, Standard Edition (J2SE), and the Enterprise
Edition (EE) was known as the Java 2 Platform, Enterprise Edition (J2EE).
Since version 1.6 of the JDK, the Standard Edition of Java has been known as
Java SE, and the Enterprise Edition is known as Java EE. This book shows how
to use Java SE 7, but it should also work for earlier and future versions of Java.
That includes Java SE 8, which is scheduled for release in late 2012.

How Java compares to C++ and C#


When Sun’s developers created Java, they tried to keep the syntax for Java
similar to the syntax for C++ so it would be easy for C++ programmers to learn
Java. In addition, they designed Java so its applications can be run on any
computer platform. In contrast, C++ needs to have a specific compiler for each
platform. Java was also designed to automatically handle many operations
involving the creation and destruction of memory. This is a key reason why it’s
easier to develop programs and write bug-free code with Java than with C++.
To provide these features, the developers of Java had to sacrifice some
speed (or performance) when compared to C++. For many types of applications,
however, Java’s relative slowness is not an issue.
Microsoft’s Visual C# language is similar to Java in many ways. Like Java,
C# uses a syntax that’s similar to C++ and that automatically handles memory
operations. However, in practice, C# code only runs on Windows. Because of
that, C# is a good choice for developing applications for a Windows-only
environment. However, Java is a better choice if you need to develop cross­
platform applications.
Chapter 1 How to get started with Java and NetBeans

Java timeline
Year Month Event
1996 January Sun releases Java Development Kit 1.0 (JDK 1.0).
1997 February Sun releases Java Development Kit 1.1 (JDK 1.1).
1998 December Sun releases the Java 2 Platform with version 1.2
of the Software Development Kit (SDK 1.2).
1999 August Sun releases Java 2 Platform, Standard Edition (J2SE).
December Sun releases Java 2 Platform, Enterprise Edition (J2EE).
2000 May Sun releases J2SE with version 1.3 of the SDK.
2002 February Sun releases J2SE with version 1.4 of the SDK.
2004 September Sun releases J2SE 5.0 with version 1.5 of the JDK.
2006 December Sun releases Java SE 6 with version 1.6 of the JDK.
2010 April Oracle buys Sun.
2011 July Oracle releases Java SE 7 with version 1.7 of the JDK.

Operating systems supported by Java


Windows (XP, Vista, 7)
Linux
Solaris
Macintosh OS X

Java compared to C++ and C#


Feature Description
Syntax Java syntax is similar to C++ and C# syntax.
Platforms Compiled Java code can be run on any platform that has a Java
interpreter. Similarly, compiled C# code (MSIL) can be run on any
system that has the appropriate interpreter. Currently, only
Windows has an interpreter for MSIL. C++ code must be compiled
once for each type of system that it is going to be run on.
Speed C++ and C# run faster than Java, but Java is getting faster with
each new version.
Memory Both Java and C# handle most memory operations automatically,
while C++ programmers must write code that manages memory.

Description
• Versions 1.2 through 1.4 of Java are called the Software Development Kit (SDK).
• Versions 1.5 through 1.7 of Java are called the Java Development Kit (JDK).

Note
• Java SE 8 with version 1.8 of the JDK is expected to be released late in 2012.

Figure 1-1 Introduction to Java


Section 1 Essential Java skills

Applications, applets, and servlets


Figure 1-2 describes the three types of programs that you can create with
Java. First, you can use Java to create applications that run directly on your
computer. These are also known as desktop applications.
When you create these desktop applications, you can use a graphical user
interface (GUI) to get user input and perform a calculation as shown at the top
left of this figure. In chapter 15, you’ll learn how to create these types of applica­
tions. Until then, you’ll learn how to create another type of desktop application
known as a console application. This type of application runs in the console, or
command prompt, that’s available from your operating system. An example of a
console application is shown at the top right of this figure.
One of the unique characteristics of Java is that you can use it to create a
special type of web-based application known as an applet. For instance, this
figure shows an applet that works the same way as the applications above it. The
main difference between an application and an applet is that an applet can be
stored in an HTML page and can run inside a Java-enabled browser. As a result,
you can distribute applets via the Internet or an intranet. In chapter 17, you’ll
learn how to create and deploy applets.
Although applets can be useful for creating a complex user interface within a
browser, they have their limitations. First, you usually need to install a plug-in on
each client machine, which isn’t ideal for some types of applications. Second,
since an applet runs within a browser on the client, it’s not ideal for working with
resources that run on the server, such as enterprise databases.
To provide access to enterprise databases, many developers use Java EE to
create applications that are based on servlets. A servlet is a special type of Java
application that runs on the server and can be called by a client, which is usually
a web browser. This is also illustrated in this figure. Here, you can see that the
servlet works much the same way as the applet. The main difference is that the
code for the application runs on the server.
When a web browser calls a servlet, the servlet performs its task and returns
the result to the browser, typically in the form of an HTML page. For example,
suppose a browser requests a servlet that displays all unprocessed invoices that
are stored in a database. Then, when the servlet is executed, it reads data from the
database, formats that data within an HTML page, and returns the HTML page to
the browser.
When you create a servlet-based application like the one shown here, all the
processing takes place on the server and only HTML is returned to the browser.
That means that anyone with an Internet or intranet connection, a web browser,
and adequate security clearance can access and run a servlet-based application.
Because of that, you don’t need to install any special software on the client.
To make it easy to store the results of a servlet within an HTML page, the
Java EE specification provides for JavaServer Pages (JSPs). Most developers use
JSPs together with servlets when developing server-side Java applications.
Although servlets and JSPs aren’t presented in this book, we cover this topic in a
companion book, Murach’s Java Servlets and JSP. For more information about
this book, please visit our web site at www.murach.com.
Chapter 1 How to get started with Java and NetBeans

A GUI application and a console application


A d m in is tr a to r : C o m m a n d P ro m p t - ja v a F u tu re V a lu e A p p

icrosoft Windows [Version 6.1.7600]


opyright Cc> 2009 Microsoft Corporation, fill right
I&-I Future Value Calculator C:\UsersSftnne.murach>cd \murach\jaua\classes

C:Smurach\jaua\classes>java Futurellalueflpp
Monthly Payment: 1100

Uelcome to the Future Value Calculator


Yearly Interest Rater 3
Enter monthly inuestment: 100
Number of Years: [3 nter yearly interest rate: 3
nter number of years: 3
Future Value: $3,771.46 Future ualue: $3,771.46

Continue? <y/n>:
Calculate Exit

An applet
M ike Murach and Associates - Publisher o f Professional Program m ing Books - M ozilla Firefox

r
File Edit View

- c
H isto ry .Bookmarks

& □
Tools Help

h tt p ://w w w , m u rach.c 0 m /fv /a pp Iet-'in d ex. h tm I

□ Mil
M ike Murach and Associates - Publish...
_L·

A servlet
M ike Murach and Associates - Publisher o f Professional Program m ing Books - M ozilla Firefox

File Edit View H isto iy jjo o km a rks Tools Help

e ’ G & □ http://w w w .m urach .com /servlet/m u ra ch.fv.F utu re V a lu eS e ivle t * | |ÎJ ’ Google P

□ M ike M urach and Associates - Publish... [ <■ |

Figure 1-2 Applications, applets, and servlets


Section 1 Essential Java skills

The code for the console version


of the Future Value application
To give you an idea of how the code for a Java application works, figure 1-3
presents the code for the console version of the Future Value application that
you saw in figure 1-2.
If you have experience with other programming languages, you may be able
to understand much of this code already. If not, don’t worry! You’ll learn how
all of this code works in the next few chapters. For now, here’s a brief explana­
tion of this code.
Most of the code for this application is stored in a class named
FutureValueApp. This class begins with an opening brace ({) and ends with a
closing brace (}). Within this class, two methods are defined. These methods
also begin with an opening brace and end with a closing brace, and they are
indented to clearly show that they are contained within the class.
The first method, named main, is the main method for the application. The
code within this method is executed automatically when you run the application.
In this case, the code displays the data the user sees on the console, accepts the
data the user enters at the console, and calculates the future value.
The second method is named calculateFutureValue. This method is called
from the main method and calculates the future value based on the data the user
enters.
Chapter 1 How to get started with Java and NetBeans

The code for the Future Value application


import java.util.Scanner;
import java.text.NumberFormat;

public class FutureValueApp


{
public static void main(String[] args)
{
Systern.out.println("\nWelcome to the Future Value Calculator\n");

Scanner sc = new Scanner(System.in);


String choice = "y";

while (choice.equalsIgnoreCase(■y"))
{
// get the input from the user
System.out.print("Enter monthly investment: ");
double monthlylnvestment = sc.nextDouble();
System.out.print("Enter yearly interest rate: ");
double interestRate = sc.nextDouble();
System.out.print("Enter number of years: ");
int years = sc.nextlnt();

// calculate the future value


double monthlylnterestRate = interestRate/12/100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlylnvestment, monthlylnterestRate, months);

// format and display the result


NumberFormat currency = NumberFormat.getCurrencylnstance();
System.out.printIn("Future value: " +
currency.format(futureValue) + "\n");

// see if the user wants to continue


System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.printlnO ;
}
}
private static double calculateFutureValue(double monthlylnvestment,
double monthlylnterestRate, int months)
{
double futureValue = 0 ;
for (int i = 1; i <= months; i++)
futureValue = (futureValue + monthlylnvestment) *
(1 + monthlylnterestRate);
return futureValue;
}
}

Figure 1-3 The code for the console version of the Future Value application
Section 1 Essential Java skills

How Java compiles and interprets code


When you develop a Java application, you create one or more classes. For
each class, you write the Java statements that direct the operation of the class.
Then, you use a Java tool to translate the Java statements into instructions that
can be run by the computer. This process is illustrated in figure 1-4.
To start, you enter and edit the Java source code for a class. These are the
Java statements like the ones you saw in figure 1-3 that tell the application what
to do. Then, you use the Java compiler to compile the source code into a format
known as Java bytecodes. At this point, the bytecodes can be run on any plat­
form that has a Java interpreter to interpret (or translate) the Java bytecodes
into code that can be understood by the underlying operating system.
Since Java interpreters are available for all major operating systems, you
can run Java on most platforms. This is what gives Java applications their
platform independence. In contrast, C++ requires a specific compiler for each
type of platform that its programs are going to run on. When a platform has a
Java interpreter installed on it, it can be considered an implementation of a Java
virtual machine (JVM).
In addition, most modem web browsers can be Java enabled. This allows
applets, which are bytecodes that are downloaded from the Internet or an
intranet, to run within a web browser. To make this work, Sun developed (and
Oracle now maintains) the Java Plug-in. This piece of software is similar to
other browser plug-ins such as Apple QuickTime. It allows the browser to run
the current version of the Java interpreter. You’ll learn more about this in
chapter 17.
Chapter 1 How to get started with Java and NetBeans

How Java compiles and interprets code

Java IDE
W source code
Text editor (*.java files)

Java c<>mpiler |

1r

Java virtual machine


(JVM)
1 Operating system |
Java interpreter

Description
• When you develop a Java application, you develop one or more classes.
• You can use a Java IDE or any text editor to create, edit, and save the source code
for a Java class. Source code files have the java extension.
• The Java compiler translates Java source code into a platform-independent format
known as Java bytecodes. Files that contain Java bytecodes have the class exten­
sion.
• The Java interpreter executes Java bytecodes. Since Java interpreters exist for all
major operating systems, Java bytecodes can be run on most platforms. A Java
interpreter is an implementation of a Java virtual machine (JVM).
• Most modem web browsers can be Java enabled. This lets applets run within these
browsers. Oracle provides a tool known as the Java Plug-in that allows you to
specify the version of the Java interpreter that you want to use.

Figure 1-4 How Java compiles and interprets code


Section 1 Essential Java skills

Introduction to Java IDEs


To develop Java applications, you typically use an Integrated Development
Environment (IDE). Although you can use a simple text editor, an IDE provides
features that can make developing Java applications considerably easier. Figure
1-5 describes some of the features of the most popular IDEs.
Note that all of the IDEs listed in this figure are either free or have a free
edition. That makes them particularly attractive to students as well as program­
mers who are learning on their own. Most of these IDEs also run on all modem
operating systems.
The first two IDEs listed in this figure, NetBeans and Eclipse, are arguably
the two most popular Java IDEs. Both of these IDEs provide all of the features
listed in this figure. For example, both of these IDEs help you complete your
code and notify you of potential compile-time errors. They both automatically
compile your code before you run it. And they both include a debugger that lets
you perform standard debugging functions like setting breakpoints, stepping
through code, and viewing the values of variables.
The default installation of NetBeans also provides a feature for building
graphical user interfaces (GUIs). To use this GUI builder, you can drag controls
onto a form on the design surface. Then, you can move, size, and align the
controls and set properties of the controls that determine how they look. As you
do this, the code that displays the GUI is automatically generated. Finally, you
can generate event handlers for the events that you want to handle and then
write the code that handles these events.
On the other hand, the default installation of Eclipse does not provide a GUI
builder. However, several free GUI builder plug-ins are available for Eclipse.
These GUI builders provide features similar to the GUI builder that’s provided
by NetBeans.
The last three IDEs listed in this figure aren’t as popular as NetBeans and
Eclipse. However, we have included them here to give you an idea of the wide
range of IDE choices that are available for Java. In addition, other Java IDEs are
available that aren’t included here.
For this book, we recommend using NetBeans because we think it’s more
intuitive and easier to use than Eclipse, especially for beginners. Once you’re
done with this book, you can switch to whatever IDE you prefer. Fortunately,
once you learn how to use one IDE, it’s fairly easy to learn to use another one.
Chapter 1 How to get started with Java and NetBeans

Popular Java IDEs


IDE Description
NetBeans A free, open-source IDE that runs on most modem operating systems.
Eclipse A free, open-source IDE that runs on most modem operating systems.
IntelUJ IDEA The Community Edition of this IDE is a free, open-source IDE that
runs on most modem operating systems.
JCreator LE The Lite Edition (LE) of this IDE is free, but the code is not open-
source, and it only runs on Windows.
BlueJ A free IDE that’s designed for teaching Java to first-year students and
runs on most modem operating systems.

Features provided by most IDEs


• A code editor with code completion and error detection.
• Automatic compilation of classes when you run the application.
• A debugger that lets you set breakpoints, step through code, and view the values of
active variables.
• A GUI builder that lets you create graphical user interfaces by dragging controls
onto a form, setting properties, and writing code that handles the events that are
triggered when a user interacts with the form.

Description
• To develop Java applications, you typically use an Integrated Development Envi­
ronment (IDE) like those listed above. All of these IDEs are either free or have free
editions.

Figure 1-5 Introduction to Java IDEs


Section 1 Essential Java skills

How to use NetBeans


to work with existing projects
Now that you have some background information about Java, you’re ready
to start working with existing NetBeans projects. In particular, you’re ready to
learn how to open and run any of the applications for this book. You can
download these applications from our web site as described in appendix A
(Windows) or appendix B (Mac OS X).

Introduction to Java projects


and the NetBeans IDE
Figure 1-6 shows the NetBeans IDE with an open Java project. In
NetBeans, a project is a folder that contains all the files for an application. In
this example, the project is named ch02_Invoice.
In the Projects window, you can see that the folder for the ch02_Invoice
project contains two subfolders. The first one, named Source Packages, contains
the source files for the application. The second one, named Libraries, contains
the Java libraries that are used by the application. In this case, the application
uses just the JDK 1.7 libraries, but you can add others.
Within the Source Packages folder, the source files can be organized into
packages. In this case, no package was specified for the project, so the default
package is used. When you develop simple applications like the one shown
here, that’s usually acceptable. For more complex applications, though, you’ll
want to use two or more packages as shown in chapter 10.
The application shown here consists of a single source file named
InvoiceApp.java. You can see part of this file in the NetBeans code editor. You’ll
learn more about working with this code editor later in this chapter. For now, I
just want to point out that this file defines a single class. Because this class
contains the main method for the application, it’s called the main class. When
you run an application, the main method in the main class is executed by
default.
Chapter 1 How to get started with Java and NetBeans

NetBeans with a Java project open


Q ch 02Jnvoice - NetBeans IDE 7.0

File Edit View Navigate Source Refactor Run Debug P rofile Team Tools W ind ow Help C V Search (Ctrl+1)

f i ‘p I |Γ- ί 1 ; [<defaultconfig>
• Ϊ 1 0 S & '® -
1Projects <3 S InvoiceApp.java 3t| 111__IlzJlüH
B ~ & di02_Invoice 1m ® - a Ί ^ ^ ^ (D l ψ f» 1a ^ I « □ Im ^
Θ ·· 1jg Source Packages 1 H i m p o r t j a v a . u t i l .S c a n n e r,· *■
ß 'b L i <default package >
3 p u b l i c c l a s s I n v o ic e A p p
É)· g Libraries 4 f
S JDK 1,7 (Default) 5 p u b l i c s t a t i c v o id m a in ( S tr in g [ j arg s)
6 i
7 U. w elc o m e t i e u s e r t o t h e p r o g r a n , =
S S y s te m , o u t . p r i n t l n ( "W elcom e t o t h e I n v o i c e T o t a l C a l c u l a t o r " } ,·
9 S y s te m , o u t . p r i n t I n () ; rr · .:.· a tls r .ic l i
10
11 i f c r e a t e a S c a n n e r o b j e c t n a m e d 3C
12 S c a n n e r s c = new S c a n n e r ( S y s t e m . i n ) ;
13
14 /! p e rfo rm , i n v o i c e c a l c u l a t i o n s u n t i l c h o i c e i s n ' t e q u a l t o "y "
IS S t r i n g c h o ic e = " y" ;
16 w h i l e ( c h o i c e . e q u a ls T g n o r e C a s e ( !; ) )
17
IS f ! g e t th e i n v o i c e s u b t o t a l fro m t h e u s e r
19 S y s te m , o u t . p r i n t ( ' ' i n t e r s u b t o t a l : ") ;
20 d o u b l e s u b t o t a l = s c . r.e x tD o u b le ( ) ;
21
22 / / c a l c u l a t e th e d is c o u n t am ount and t o t a l
23 d o u b le d is c o u n t F e r c e n t= 0 .0 ;
24 i f ( s u b t o t a l >= 200}
25 d is c o u n tP e rc e n t = .2 ;
26 e l s e i f ( s u b t o t a l >= 100} *

05 111 INS

Description
• A NetBeans project consists of a top-level folder that contains the subfolders and
files for an application.
• The Source Packages subfolder contains the .java files that make up the project.
These files define classes that are later compiled into .class files.
• By default, a project consists of a single class that contains the main method. The
main method is the starting point for the application, and the class that contains it is
called the main class.
• The .java files that make up a project can be organized into one or more packages.
If you don’t specify a package for the main class when you create a project, it’s
stored in the default package.
• The Libraries subfolder contains the libraries that are available to your project.
These libraries contain the Java classes that you can use in your projects. By
default, you can use the classes in the JDK libraries.
• The folders, files, and libraries that make up a Java project are listed in the Projects
window. If this window isn’t visible, you can display it by using the
Window->Projects command. Then, you can expand and collapse the nodes in this
window by clicking on the plus and minus signs.
• You can display and work with the source code in a .java file in the code editor
window. For details, see figure 1-11.

Figure 1-6 Introduction to Java projects and the NetBeans IDE


Section 1 Essential Java skills

How to open, close, and delete a project


To open a project in NetBeans, you use the Open Project dialog box shown
in figure 1-7. This dialog box lets you navigate to the folder that contains the
project you want to open. In this figure, for example, the Open Project dialog
box shows all of the existing NetBeans projects in this folder:
C :\murach\java\netbeans\book_apps
To clearly indicate when a folder contains a Java project, the Open Project
dialog box displays a small coffee cup icon to the left of the folder name. Then,
you select the project you want to open and click the Open Project button.
When you’re done working with a project, you can close it to remove it
from the Projects window. To do that, you can use one of the techniques de­
scribed in this figure.
You can also delete a project if you decide that you no longer want to work
with it in NetBeans. Before the project is deleted, NetBeans will prompt you to
confirm the deletion. Then, by default, NetBeans deletes all of the files for the
project except for the source files. That way, you can work with those files
outside of NetBeans if you want to. If you want to delete the source files as
well, you can select the “Also Delete Sources” option in the dialog box that’s
displayed.

How to compile and run a project


Figure 1-7 also describes how to compile and run a project. An easy way to
run a project is to press F6. Then, if the project has been modified since the last
time it was compiled, NetBeans automatically compiles the project and runs the
main method in the main class.
If you want to compile a project without running it, you can use the Build
command as described in this figure. You can also use the Clean and Build
command to compile the project and remove any files that are no longer needed.
This sometimes helps to get a project to work correctly after you have copied,
moved, or renamed some of its files.
Chapter 1 How to get started with Java and NetBeans

The dialog box for opening a project


Q Open Project U s·!'
Look in: book_apps is Ö
® c h 0 1 Test ProjectName:
ch02 Invoice
^ch02. TestScore
Γ I Open as Main Project
.^•ch03. .InvoiceBigDedmal
jÿch03_InvoiceFormatted
^ch04. FutureValue Open Required Projects:
®pch04.FutureValueWithMethod
,^ · ch04_ Invoice
^pch05. FutureValueApp
^■ch05. FutureValueValidation
^ c h 0 6 . FutureValue
^ c h 0 7 Lineltem
& ch07_ Product
tebrhHft Bnofiiirt________
C: Vnurach \java V^etbeans ^ook_apps \ch02_Invoice

Files o f ty p e : p r0Jec t F o ld er ; Cancel

How to open, close, and delete a project


• To open a project, click the Open Project button in the toolbar or select the File->Open
Project command. Then, use the Open Project dialog box that’s displayed to locate and
select the project and click the Open Project button.
• You can also open a project by using the F ile O p e n Recent Project command and then
selecting the project from the list that’s displayed.
• To close a project, right-click on the project in the Projects window and select the Close
command, or select the project and then use the File->Close Project command.
• To delete a project, right-click on the project in the Projects window and select the Delete
command. When you do, you’ll have the option of deleting just the files that NetBeans uses
to manage the project or deleting all the folders and files for the project.

How to compile and run a project


• To run a project, press F6, use the Run->Run Project command, or click the Run Project
button in the toolbar.
• When you run a project, NetBeans automatically compiles it. As a result, you usually don’t
need to compile a project separately.
• To compile a project without running it, you can right-click on the project in the Projects
window and select the Build command.
• To delete all compiled files for a project and compile them again, you can right-click on the
project and select the Clean and Build command. This removes files that are no longer
needed and compiles the entire project.

Mac OS X note
• To enable right-clicking with Mac OS X, you can edit the system preferences for the
mouse.

Figure 1-7 Basic skills for working with existing projects


Section 1 Essential Java skills

How to use the Output window


with a console application
When you run a console application in NetBeans, any data that’s written to
the console is displayed in the Output window. In addition, The Output window
can accept input. This is illustrated in figure 1-8.
The project shown in this figure is for a simple application that accepts a
subtotal. Then, this application calculates and displays the discount percent,
discount amount, and invoice total based on that subtotal. You’ll see the code for
this application in the next chapter. For now, just focus on the data in the Output
window.
Here, the application started by displaying a welcome message. Then, it
displayed a prompt indicating that I should enter a subtotal. In response, I typed
“100” and pressed Enter. When I did, the application displayed the calculations
and then asked me if I wanted to continue. At this point, the application is still
running, and I can enter “y” to perform another calculation or “n” to end the
application.
When you’re learning Java, it’s common to create applications that use the
console to display output and get input. Because of that, the first three sections
of this book teach you Java using console applications. Then, section 4 of this
book will teach you how to create modem applications with graphical user
interfaces.
Chapter 1 How to get started with Java and NetBeans

An application that uses the Output window for input and output
Q ch02Jnvoîee - NetBeans IDE 7.0 l.°i® ba<J
File Edit View Navigate Source Refactor Run Debug P rofile Team Tools W ind ow Help Q .* Search (Ctrl+1)

‘p ~| I,—
! 1
f i ; [<defâulto)nfïg>
' ] Ï 1 0 S & '® -
: Projects , InvoiceApp.java Sä | (ZHJB®
IQ
Ξ ~® ch02_Invoice
ü - q H^ ^ <5® ^ a a Γ%» □ I& j
φ - £§ Source Packages
1 ( 3 i m p o r t j a v a . u c i l .S c a n n e r,·
Ô 'Ë t l <default package > 2
InvoiceADo.jsva 3 p u b l i c c l a s s I n v o ic e A p p
Θ·· g Libraries 4 {
§ JDK 1,7 (Default) 5 p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s )
6Π {
71 ί ΐ welcome ·.·.= user το tie prograir,
S y s t e m . c r j c . p r i n t I n ( "W elcom e t o t h e I n v o i c e T o t a l C a l c u l a t o r " ) ;
S y s te m , o u t . p r i n t I n () ; ’ i r i s .-.ic 1 :.“ ?
©
I t c r e a t e a S c a n n e r o b j e c t n a m e d 3C
S c a n n e r s c = r.ew S c a n n e r ( S y s te m , in ) ;

: O u tp u t - ch 0 2 _ln v o ice (r u n )

w
Welcome tc the Invoice Total Calculator

Enter subtotal: 100


Discount percent: 0.1
Discount amount: 1 0 _C
Invoice total: 90.0

Continue? {y/n): |

chQ2_Invoice (run) | _ 1 11 INS

Description
• When you run an application that prints data to the console, that data is displayed
in the Output window.
• When you run an application that requests input from the console, the Output
window pauses to accept the input. Then, you can click in the Output window, type
the input, and press the Enter key.
• In addition to displaying output and accepting input, the Output window can
display other information. For example, it can display messages when the applica­
tion is compiled, and it can display errors that are encountered when an application
is run.

Figure 1-8 How to use the Output window with a console application
Section 1 Essential Java skills

How to work with two or more projects


Up to this point, I’ve shown you how to work with a single project in
NetBeans. However, NetBeans lets you open and work with two or more
projects at the same time. If, for example, you want to run some of the projects
from the download for this book before you start creating your own projects,
you can open those projects in NetBeans at the same time. You’ll get a chance to
do that in the first exercise for this chapter.
Figure 1-9 presents the skills for working with two or more projects. To
start, you can run a project by selecting it in the Projects window and then using
the techniques you learned in figure 1-7. Alternatively, you can set one of the
projects as the main project using one of the techniques in this figure. When you
do that, NetBeans identifies the project by boldfacing it in the Projects window.
Then, that project is run automatically when you use one of the standard tech­
niques for running a project. To run a project other than the main project, you
have to right-click on the project or the file that contains the main method for
the project and select the Run or Run File command.
Chapter 1 How to get started with Java and NetBeans

NetBeans with two open projects


Q ch 02Jnvoice - NetBeans IDE 7.0 [ Q 10 I-Ä -.J j

File Edit View Navigate Source Refactor Run Debug Profile Team Tools W in d o w H elp (V Search (Ctrl+1) Ί

fh Θ Q l % l * D 0 1 '■ i<£tefeultronfig> Ί ^ ! I t ® ’

« : P ro je cts <0 & |jSg tnvoiceApp.java ss | 1 1 1Θ 0


0 - ^ ch O lT est
È
®~ Î3 Source Packages
| Β · - · - | « Ι Φ 5 ιΕ 1 ) ? * ι& Ι&3ΐΙ· B |fc J
1 3 im p o r t j a v a .u t i l . S c a n n e r; ■
s IB- g Libraries -,
Έ É .jS1 c h 02_ In v o ie e 3 p u b lic c la s s Iiw o ic e A p p
A
0 - £ src 4 {
ί Θ -'t+J <default package > 5 p u b l i c s t a t i c v o id m a i n ( S t r i n g [ J a r g s )
g 6 3 {
S IB- g Libraries 7 I I w elc o m e t h e u s e r t o t h e p r o g r sur. =
>
S S y s te m .p o t.p r in tln ( " W e lc o a e t o t h e I n v o ic e T o t a l C a l c u la to r " ) ;
(?) 9 S y s te m , o u t . p r i n t I n () ; p n r . t a b ls r .ic ii.- .e
10
11 II c r e a t e a S c a n n e r o b j e c t n a n ie d s c
12 S c a n n e r s c = new S c a n n e r ( S y s t e m . i n ) ;
13 —
14 / / p e rfo rm in v o ic e C a lc u la tio n s u n t i l c h o ic e i s n ' t e q u a l to ”y"
15 S tr in g c h o ic e = "y ";
16 w h ile ( c h o i c e . e q u a ls I g n o r e C a s e ( " y " ) )
17
ie / / g e t th e i n v o i c e s u b t o t a l fro m t h e u s e r
19 S y s te m .o u t.p r in t( " E n te r s u b to ta l:
20 d o u b l e s u b t o t a l = 3 C . n e x t D o u b l e (} ;
21
22 /1c a l c u l a t e th e d is c o u n t am ount and t o t a l
23 d o u b le d is c o u n t P e r c e n t= 0 .0 ;
24 i f ( s u b t o t a l >= 2 0 0 )
25 d is c o u n tP e r c e n t = .2 ;
26 e l s e i f ( s u b t o t a l >= 100l· ■
< U ------------------------ - ί" ! »

1 ill J N s jl

Description
• NetBeans lets you open and work with two or more projects at the same time.
• When you work with two or more projects, you can set one project as the main
project. To do that, right-click on the project and select Set as Main Project. Or,
when you open the project, select the Open as Main Project option.
• After you set a main project, you can run that project by pressing F6, by using the
Run->Run Main Project command, or by clicking the Run Main Project button in
the toolbar. The Run Main Project command and toolbar button replace the Run
Project command and toolbar button when a main project is set.
• To run a project other than the main project, right-click on the project and select the
Run command, or right-click on the file that contains the main method you want to
run and select the Run File command.
• If you don’t set a main project, you can run any project by selecting that project in
the Projects window and then using standard techniques.

Figure 1-9 How to work with two or more projects


Section 1 Essential Java skills

How to use NetBeans


to develop new projects
Now that you know how to work with existing Java projects in NetBeans,
you’re ready to learn how to develop new Java projects. That’s what you’ll learn
in the remainder of this chapter.

How to create a new project


Figure 1-10 presents the dialog boxes for creating a Java application. You
use the New Project dialog box to choose the type of project you want to create.
In most cases, you’ll create a Java Application project as shown here. Then,
when you click the Next button, NetBeans displays a New Java Application
dialog box like the second one in this figure.
The New Java Application dialog box lets you enter a name and location for
the project. In this figure, for example, the project name is “ch01_Test” and it
will be stored in this folder:
C :\murach\j ava\netbeans\book_apps
If you install the source code for this book as described in the appendix, all of
the applications presented in this book will be stored within this folder.
By default, when you create a Java application in NetBeans, NetBeans
generates a main class with a main method. If that’s not what you want, you can
remove the check mark from the “Create Main Class” option. In most cases,
though, you’ll leave this option checked. Then, you can enter a name for the
main class and, optionally, the package that contains it. For the project in this
figure, for example, NetBeans suggested chOl_test.ch01_Test, where
“chOl_test” is the name of the package and “ch01_Test” is the name of the
class.
In this figure, I deleted the package name, and I changed the name of the
class to TestApp. As a result, NetBeans created a project named ch01_Test that
contains a main class named TestApp. Because I didn’t specify a package name,
this class is stored in the default package.
Like the Open Project dialog box you saw in figure 1-7, the New Java
Application dialog box includes an option that determines if the new project is
set as the main project. If you know that you want a project set as the main
project when you create it, you should select this option. Otherwise, you can set
the main project later using the technique you learned in figure 1-9.
When this dialog box is complete, you can click the Finish button to create
the project and the class that contains the main method. Then, NetBeans creates
a folder that corresponds with the project name, and it creates some additional
files that it uses to configure the project.
Chapter 1 How to get started with Java and NetBeans

The dialog boxes for creating a new project


0 New Project

S te p s __________________________ Choose P ro je c t_________________________________

1. Choose P ro je c t Categories: Projects:

...[jL § ;-| jjjÿ Java Application

....! I Java Web Java Class Library


Java Project w ith Existing Sources
ij, Java Free-Form Project
PHP
É -· ί Samples

description:

C re a te s a n e w J a v a SE a p p lic a tio n in a standard IDE project, You can also aenerate a main class
in the project. Standard p rojects use a n ID F g e n e r a te d A n t build s c rip t to build, run, and debug
your project,

0 N e w Java A p p lic a tio n l- a - J j

S teps N a m e an d Location

1, Choose Project Project Name: chOl Test


2. Ma m e a n d Loca tion

Project Location : C: Vnurach\javaVietbeansï»ook_apps Browse..,

Project Folder: C: Vnurach \ja va Vietbeans t>ook_apps \chO IJT e st

Q Use Dedicated Folder fo r Storing Libraries

Libraries Folder ; [__ Browse.,,

Different users and projects can share the same compilation


libraries {see Help fo r details).

2 1 Create Main Class TestApp|

[ 3 Set as Main Project

P roject Folder already exists and is n o t em pty.

1 < Back J :Mext > Cancel 11 He|p 1

Description
• To create a new project, use the File->New Project command or click the New
Project button in the toolbar to display the New Project dialog box. Then, select a
project type, click the Next button and complete the dialog box that’s displayed.
• To create a Java Application project, enter the project name and location and the
name you want to use for the main class. You can also enter the name of the
package that will contain the main class, but that’s not necessary.

Figure 1-10 How to create a new project


Section 1 Essential Java skills

How to set the Java version for a project


In some cases, you’ll want to change the version of Java that a project uses.
For example, you might want the project to run on computers with earlier
versions of Java. Then, you can use the Project Properties dialog box in figure
1-11 to change the version for the project.
To use an earlier version of Java, you start by displaying the Sources
category. Then, you select the version you want to use from the Source/Binary
Format drop-down list. In this figure, I selected JDK 6. As a result, any lan­
guage features that were added after Java 6 won’t be available to the project. In
addition, the bytecodes that are generated by the compiler for the project will
run under Java 6 and later versions.
Although setting the Source/Binary Format option will keep you from using
language features that were added with a later version of Java, it won’t keep you
from using features of the JDK libraries for later versions. In many cases, that’s
not a problem. If you want to be sure that you don’t use any of the new features,
though, you should change the Java platform that’s used by the project. To do
that, just select the JDK version from the Java Platform drop-down list in the
Libraries category of the Project Properties dialog box.
Note that the Java Platform drop-down list only includes the versions you
have installed on your computer. Before you can select a different version, then,
you may have to install it as described in the appendix A (Windows) or appen­
dix B (Mac OS X). After you do that, you can click the Manage Platforms
button to the right of the Java Platform drop-down list to display a dialog box
that lets you add the version you installed.
You might also want to change the Java version for a project if a newer
version becomes available and you want to use some of the features of that
version. After you install the new version, you can use the JDK libraries for that
version in a project by selecting the JDK from the Java Platform drop-down list.
In addition, if you want to use the new language features of that version and you
don’t need the project to run under earlier versions of Java, you can select the
new JDK from the Source/Binary Format drop-down list.
Note that to use a newer version, you must set the Java Platform option first.
Otherwise, that JDK won’t be available in the Source/Binary Format list.
Chapter 1 How to get started with Java and NetBeans

The Project Properties dialog box


Project Properties - ch01_Test

Categories:
,-■· 0 Sources Java Platform: JDK 1.6 T Manage Platforms...
i... 0 Libraries
Libraries Folder : Browse,..
a -® Build
s Compiling
Compile Processor | Run | Compile Tests | Run Testsj
0 Packaging
9 Documenting Compile-time Libraries:
I...o Run
Add Project...
a·· o Application
0 Web Start Add Library...
:..0 Formatting
Add JAR/Folder
I Q Project Properties - ch O l.T e st

Categories:

;... 0 Sources Project Folder:ς .^ Urach\java'netbean5^book_apps\chOl_Test


j...O Libraries
Source Package Folders:
0- O Build Hove Up
! }-. 0 Compiling
j j - Q Packaging
! I... © Documenting
;...Q Run
0- O Application
j i- . o Web Start
'...O Formatting ancel
Test Package Folders:

Package Folder Label Add Folder...

test [Test Packages

Move Up

Source/Binary Format: JDK 6 T Indudes/Exdudes,.

Encoding: UTF-6

Cancel Help

Description
• The Project Properties dialog box lets you set various properties that affect the
project. To display this dialog box, right-click on the project in the Projects window
and select the Properties command.
• To set the version of the Java language and compiled bytecodes the project uses,
select the version from the Source/Binary Format drop-down list in the Sources
category. Then, the compiled bytecodes for the project will run under this version
of Java and later. In addition, the project can only use language features for the
specified version of Java.
• To set the version of the JDK libraries that are available to the project, select the
version from the Java Platform drop-down list in the Libraries category. Then, your
project can only use the features that are available from that version of the JDK
libraries. For this to work, the version of the JDK you want to use must be installed
on your system.
• To be sure that the JDK libraries are compatible with the language features and
bytecodes, select the same version of the JDK from the Java Platform and the
Source/Binary Format drop-down lists.
Figure 1-11 How to set the Java version for a project
Section 1 Essential Java skills

How to work with Java source code and files


When you create a new project that contains a class with a main method, the
class is typically opened in a new code editor window as shown in figure 1-12.
To make it easier to for you to recognize the Java syntax, the code editor uses
different colors for different language elements. In addition, NetBeans provides
standard File and Edit menus and keystroke shortcuts that let you save and edit
the source code. For example, you can press Ctrl+S to save your source code,
and you can use standard commands to cut, copy, and paste code.
When you create a project with a main class, NetBeans generates some
code for you. In this figure, for example, NetBeans generated the code that
declares the class, the code that declares the main method, and comments that
describe the class and method. Although you can delete or modify the class and
method declarations, you won’t usually do that. However, you may want to
delete or modify some or all of the comments.
If the source code you want to work with isn’t displayed in a code editor
window, you can use the Projects window to navigate to the .java file and then
double-click on it to open it in a code editor window. In this figure, for example,
you can see the TestApp.java file in the Projects window. Notice that this file is
stored in the default package of the Source Packages folder, since no package
was specified when the project was created.
You can also rename or delete a .java file from the Projects window. To do
that, just right-click on the file and select the appropriate command. If you
rename a file, NetBeans automatically changes both the name of the .java file
and the name of the class. Since the name of the .java file must match the name
of the class, this is usually what you want.
Chapter 1 How to get started with Java and NetBeans

Net Bean’s code editor with the starting source code for a project
Çjjjc h O l J e s t - NetBeans IDE 7,0 I 1

File Edit View Navigate Source Refactor Run Debug Profile Team Tools W ind ow H elp Q ? Search {Ctrl+1)

' fâ Θ L i % : * 0 <?■ ί l<^fauitconfig> ÿ] ^ ^ [> Ü - (B ’

I Projects <0 » |dj}TestApp.java ss| M ‘I H M

B l® j
a -0 chQl_Test »
1 □ -
©· I £3 Source Packages * To c h a n g e t h i s t e i r p l a t e , c h o o e e T o o l s 1 T e m p la te s -
2
! B - M <default package > 3 • a n d a c e r. t h e t e m p l a t e i n t i e e d i t o r .
I ·"■|cSft TestApp.java 4
(3- g Libraries 5
É - @ ] JDK 1.7 (Default) 6 Ξ /**
7 *
8 ■ 0 - a o th o r A n c e
9 *!
10 p u b lic c la s s T e s tA p p {
11
12 □ / -
13 * S p a re rn a r g s t h e CBMmana l i n e a r g u m e n ts
14 L *!
15 3 p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) ί
16 ! ! TODC c o d e a p p l i c a t i o n l o a x c h e r e
17 L >
IS }
19

111 INS

Description
• To open a .java file in the code editor, double-click on it in the Projects window. Then,
you can use normal editing techniques to work with the source code.
• To collapse the code for a method or comment, click the minus sign (-) to its left. Then,
a plus sign (+) appears to the left of the method or comment, and you can click the plus
sign to display the code again.
• To save the source code for a file, use the File->Save command (Ctrl+S) or click the
Save All Files button in the toolbar. This automatically compiles the file so it doesn’t
have to be compiled when the project is run.
• To rename a file, right-click on it, select the Refactor-^ Rename command, and enter the
new name in the resulting dialog box.
• To delete a file, you can right-click on it, select the Delete command, and confirm the
deletion in the resulting dialog box.

Figure 1-12 How to work with Java source code and files
Section 1 Essential Java skills

How to use the code completion feature


Figure 1-13 shows how to use the code completion feature. This feature
prevents you from making typing mistakes, and it allows you to discover what
fields and methods are available from various classes and objects. In this figure,
for example, I started to enter a statement that prints text to the console.
First, I entered “sys” and pressed Ctrl+Spacebar (both keys at the same
time). This displayed a list with the System class as the only option. Then, I
pressed the Enter key to automatically enter the rest of the class name.
Next, I typed a period. This displayed a list of fields and methods available
from the System class. Then, I used the arrow keys to select the field named out
and pressed the Enter key to automatically enter that field name.
Finally, I typed another period. This displayed a long list of method names.
Then, I typed “pr” to scroll down the list to the methods that start with “pr”, and
I used the arrow keys to select one of the println methods as shown in the figure.
At this point, I could press Enter to have NetBeans enter the method into the
editor for me.
When you use code completion, it automatically enters opening and closing
parentheses and arguments whenever they’re needed. In this figure, for example,
you can see that the println method that I’ve selected is followed by a set of
parentheses that contains a string argument. When I inserted this method into
the code editor, the parentheses and arguments were inserted and the argument
was highlighted so I could enter a value for it.
The code completion feature can also make it easy for you to enter values
for string variables. If you type a quotation mark to identify a string value, the
code completion feature automatically enters both opening and closing quota­
tion marks and places the cursor between the two. At this point, you can enter
the text for the string.
If you experiment with the code completion feature, you’ll quickly see
when it helps you enter code more quickly and when it makes sense to enter the
code yourself. In addition, you’ll see that it helps you understand the kinds of
fields and methods that are available to the various classes and objects that
you’re working with. This will make more sense as you learn about object-
oriented programming in Java beginning in the next chapter.
Chapter 1 How to get started with Java and NetBeans

The code editor with a code completion list


Q chOl.Test - NetBeani IDE 7.0

F ile E d it V ie w N a v ig a te S o u rc e R e fa c to r Run D ebug P r o file T eam T o o ls W in d o w H e lp Search (Ctrl+I)

P r o je c t s . T e s tA p p .ja v a ss[ IΊ -IF1R


Cj B · 9>fs - e *I^ S 211ü Q j i d
ch01_Test
p u b l i c c l a s s T estA pp {
φ· I Source Packages
<defaultpadcage> public static void ma i n (String[j ergs) ^
TestApp.java S y ste m , o u t . p r|
Q " I ë Libraries G p r i n t ( O b j e c t o b :) v o id
JDK 1.7 (Default) 0 p r i n t ( S t r i n g s) v o id
O p r i n t ( b o o l e a n fc) v o id
Q p r i n t (c h a r c) v o id
o 0 p r i n t (c h a r [] s) v o id
Q p r i n t ( d o u b l e d) v o id
G p r i n t ( f l o a t £) v o id
G p r i n t ( i n t i) v o id
G p r i n t ( l o n g 1) v o id
G p r i n t f ( S t r i n g f o r m a t. O b j e c t . . . a r g s ) P r in tS tr e a m
0 p r i n t f ( L o c a l e 1 , S t r i n g f o n t a e , O b j e c t . . . a r g e ) P r in tS tr e a r r ,
G p r i n t l n () v o id
G p r i n t l n ( O b j e c t x) v o id

G p r i n t l n ( b o o le a n x) v o id
G p r i n t l n (c h a r x ) v o id
G p r i n t l n (c h a r [] x ) v o id

îava.io.PrintStream

p u b l i c v o i d p r i n t l n ( S tr in g , x)

Prints a S tring and then term in ate the line. T h is m ethod behaves as though it invokes INS
P r in t s t r e a m . p r i n t ( S t r i n j ] and then P ri n tS t re am. p r i n t I n 1) ■

P a ra m e te rs :
x - T he s t r i n g to be printed.

Description
• You can use the code completion feature to help you enter the names of classes and
objects and select from the methods and fields that are available for a class or
object.
• To activate the code completion feature for entering a class or object name, press
Ctrl+Spacebar after entering one or more letters of the class or object name. Then,
a list of all the classes and objects that start with those letters is displayed.
• To activate the code completion feature for a method or field of a class or object,
enter a period after a class or object name. Then, a list of all the methods and fields
for that class or object is displayed.
• To insert an item from a code completion list, select the item and then press the
Enter key. If the item requires parentheses, they’re added automatically. If the item
requires one or more arguments, default values are added for those arguments and
the first argument is highlighted so you can enter its value. Then, you can press the
Tab key and enter the values for any remaining arguments.
• If you enter the opening quote for a string value, the code completion feature
automatically adds the closing quote and places the cursor between the two quotes
so you can enter a value.

Figure 1-13 How to use the code completion feature


Section 1 Essential Java skills

How to detect and correct syntax errors


In NetBeans, a syntax error is caused by a statement that won’t compile. As you
enter text into the code editor, NetBeans displays syntax errors whenever it detects
them. In figure 1-14, for example, NetBeans displays an error that indicates that a
semicolon needs to be entered to complete the statement. This error is marked with a
red icon to the left of the statement. In addition, the statement that contains the error is
marked with a wavy red underline.
If you position the mouse cursor over the red error icon or over the statement itself,
NetBeans displays a description of the error. In this figure, for example, the description
indicates that NetBeans expects a semicolon at the end of the statement. As a result,
you can fix the error by typing the semicolon.
Chapter 1 How to get started with Java and NetBeans

The code editor with an error displayed

Description
• NetBeans often detects syntax errors as you enter code into the code editor.
• When NetBeans detects a syntax error, it displays a red error icon to the left of the
statement in error and it places a red wavy line under the statement.
• To get more information about a syntax error, you can position the mouse pointer
over the error icon. Or, you can move the cursor to the line that contains the error
and press Alt+Enter.

Figure 1-14 How to detect and correct syntax errors


Section 1 Essential Java skills

Perspective
In this chapter, you were introduced to Java, and you learned how to use
NetBeans to create and run a Java application. With that as background, you’re
ready to learn how to write your own Java applications. But first, I recommend
that you familiarize yourself with NetBeans by doing the exercises at the end
of this chapter.

Summary
• You use the Java Development Kit (JDK) to develop Java applications. This used
to be called the Software Development Kit (SDK) for Java.
• As of version 6, the Standard Edition (SE) of Java is called Java SE. In older
versions, it was called the Java 2 Platform, Standard Edition (J2SE).
• You can use Java SE to create applications (also known as desktop applications)
that run on your computer and a special type of Internet-based application known
as an applet.
• A desktop application can use a graphical user interface (GUI) or a console to
display output and get user input. Applications that use a console to interact with
the user are known as console applications.
• You can use the Enterprise Edition (EE) of Java, which is known as Java EE, to
create server-side applications using servlets and JavaServer Pages (JSPs).
• The Java compiler translates source code into a platform-independent format
known as Java bytecodes.
• Any machine that has a Java interpreter installed on it can be considered an
implementation of a Java virtual machine (JVM).
• An Integrated Development Environment (IDE) such as NetBeans can make
working with Java easier.
• In NetBeans, a project is a folder that contains all of the files that make up an
application.
• Java code is stored in classes. To organize multiple classes, you can store them in
packages.
• The main class of an application is the class that contains the main method, which
is the starting point of the application.
• If an application prints text to the console, NetBeans displays the text in the Output
window. NetBeans also allows you to enter input into the Output window.
• When multiple projects are open, NetBeans identifies the main project by
boldfacing its name in the Projects window.
• You can use the NetBeans code editor to enter and edit code. As you enter code,
you can use the code completion feature to help you enter the names of classes and
objects and select from fields and methods.
Chapter 1 How to get started with Java and NetBeans

Before you do the exercises for this chapter


Before you do any of the exercises in this book, you need to install the JDK and
NetBeans. In addition, you need to install the source code for this book from
our web site ('www.murach.com). See appendix A (Windows) or appendix B
(Mac OS X) for details.

Exercise 1-1 Use NetBeans to open


and run two projects
This exercise guides you through the process of using NetBeans to open and run
two console applications.

Open and run the Invoice application


1. Start NetBeans. When the Start Page is displayed, review the information on
its tabs. Then, close this page.
2. Open the project named ch01_exl_Invoice. The project should be stored in
this directory:
Cs\murach\java\netbeans\ex_starts
3. Open the InvoiceApp.java file in the code editor and review its code to get an
idea of how this application works.
4. Press F6 to run the application. Enter a subtotal when you’re prompted, and
then enter “n” when you’re asked if you want to continue.
Open and run the Test Score application
5. Open the project named ch01_ex2_TestScore. When you do, make sure to
select the “Open as Main Project” option. Then, open the TestScoreApp.java
file in the code editor and review its code.
6. Click the Run Project button in the toolbar to run the application. Enter one or
more grades when you’re prompted, and enter 999 to end the application.
Set the main project and run the applications again
7. Set the Invoice application as the main project. Then, press F6 to run this
application. When you’re done, end the application.
8. Right-click on the Test Score application and select the Run command to run
this application. When you’re done, end the application.
9. Close both projects.
Section 1 Essential Java skills

Exercise 1-2 Use NetBeans to develop


an application
This exercise guides you through the process of using NetBeans to enter, save,
compile, and run a simple application.

Enter the source code and run the application


1. Start NetBeans if it isn’t already open.
2. Select the File->New Project command from the NetBeans menu system.
Then, use the resulting dialog boxes to create a Java Application project
named ch01_Test that contains a main class named TestApp. Store the project
in this directory:
C:\murach\java\netbeans\ex_starts

3. Modify the generated code for the TestApp class so it looks like this (type
carefully and use the same capitalization):
public class TestApp
{
public static void main(String[] args)
{
System.out.println(
"This Java application has run successfully.");
}
}
4. Press F6 to compile and run the application. This should display “This Java
application has run successfully.” in the Output window.
Use the code completion feature
5. Enter the statement that starts with System, out again, right after the first
statement. This time, type “sys” and then press Ctrl+Spacebar. Then, use the
code completion feature to select the System class, and complete the
statement.
6. Enter this statement a third time, right after the second statement. This time,
type System, enter a period, and select out from the list that’s displayed. Then,
enter another period, select println(String x), and complete the statement. You
should now have the same statement three times in a row.
7. Run the application again to see that the message is displayed three times in a
row in the Output window.
Introduce and correct a syntax error
8. In the code editor window, delete the semicolon at the end of the first println
statement, and NetBeans will display an error icon to the left of the statement.
9. Correct the error, and NetBeans will remove the error icon.
10. Use the File->Save command (Ctrl+S) to save the changes.
2
Introduction
to Java programming
Now that you know the basic skills for using NetBeans to work with Java
projects, the quickest and best way to learn Java programming is to do Java
programming. That’s why this chapter shows you how to write complete Java
programs that get input from a user, make calculations, and display output.
When you finish this chapter, you should be able to write comparable programs
of your own.

Basic coding sk ills..................................................................36


How to code statements.................................................................................. 36
How to code comments.................................................................................. 36
How to create identifiers................................................................................. 38
How to declare a class and a main method.....................................................40
How to work with numeric variables....................................42
How to declare and initialize variables...........................................................42
How to code assignment statements...............................................................44
How to code arithmetic expressions...............................................................44
How to work with string variables........................................46
How to create a String object......................................................................... 46
How to join and append strings...................................................................... 46
How to include special characters in strings..................................................48
How to use Java classes, objects, and m eth o d s............... 50
How to create objects and call methods.........................................................50
How to import Java classes............................................................................. 52
How to use the API documentation to research Java classes......................... 54
How to use the console for input and o u tp u t..................... 56
How to use the System.out object to print output to the console.................. 56
How to use the Scanner class to read input from the console....................... 58
Examples that get input from the console......................................................60
How to code simple control sta te m e n ts..............................62
How to compare numeric variables................................................................ 62
How to compare string variables....................................................................62
How to code if/else statements....................................................................... 64
How to code while statements........................................................................ 66
Two illustrative applications.................................................. 68
The Invoice application.................................................................................. 68
The Test Score application............................................................................. 70
How to test and debug an application..................................72
How to test an application.............................................................................. 72
How to debug an application.......................................................................... 72
Perspective...............................................................................74
Section 1 Essential Java skills

Basic coding skills


This chapter starts by introducing you to some basic coding skills. You’ll use
these skills for every Java program you develop.

How to code statements


The statements in a Java program direct the operation of the program. When
you code a statement, you can start it anywhere in a coding line, you can con­
tinue it from one line to another, and you can code one or more spaces anywhere
a single space is valid. In the first example in figure 2-1, the lines that aren’t
shaded are statements.
To end most statements, you use a semicolon. But when a statement requires
a set of braces {}, it ends with the right brace. Then, the statements within the
braces are referred to as a block of code. For example, the InvoiceApp class and
the main method shown in this figure both contain a block of code.
To make a program easier to read, you should use indentation and spacing to
align statements and blocks of code. This is illustrated by the program in this
figure and by all of the programs and examples in this book.

How to code comments


Comments are used in Java programs to document what the program does
and what specific blocks and lines of code do. Since the Java compiler ignores
comments, you can include them anywhere in a program without affecting your
code. In the first example in figure 2-1, the comments are shaded.
A single-line comment is typically used to describe one or more lines of
code. This type of comment starts with two slashes (//) that tell the compiler to
ignore all characters until the end of the current line. In the first example in this
figure, you can see four single-line comments that are used to describe groups of
statements. The other comment is coded after a statement. This type of comment
is sometimes referred to as an end-of-line comment.
The second example in this figure shows how to code a block comment. This
type of comment is typically used to document information that applies to a
block of code. This information can include the author’s name, program comple­
tion date, the purpose of the code, the files used by the code, and so on.
Although many programmers sprinkle their code with comments, that
shouldn’t be necessary if you write code that’s easy to read and understand.
Instead, you should use comments only to clarify code that’s difficult to under­
stand. In this figure, for example, an experienced Java programmer wouldn’t
need any of the single-line comments.
One problem with comments is that they may not accurately represent what
the code does. This often happens when a programmer changes the code, but
doesn’t change the comments that go along with it. Then, it’s even harder to
understand the code because the comments are misleading. So if you change the
code that you’ve written comments for, be sure to change the comments too.
Chapter 2 Introduction to Java Programming

An application consists of statements and comments


import java.util.Scanner;

public class InvoiceApp


{
public static void main(String[] args)
{
// display a welcome message
System.out.println("Welcome to the Invoice Total Calculator");
System.out.println(); // print a blank line

// get the input from the user


Scanner sc = new Scanner(System.in);
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();

// calculate the discount amount and total


double discountPercent = .2;
double discountAmount = subtotal * discountPercent;
double invoiceTotal = subtotal - discountAmount;

// format and display the result


String message ="Discount percent: " + discountPercent + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Invoice total: " + invoiceTotal + "\n";
System.out.println(message);
}
}

A block comment that could be coded at the start of a program


/*
* Author: J. Murach
* Purpose: This program uses the console to get a subtotal from the user,
* and it calculates the discount amount and total and displays them.
*/

Description
• Java statements direct the operations of a program, while comments are used to help
document what the program does.
• You can start a statement at any point in a line and continue the statement from one
line to the next. To make a program easier to read, you should use indentation and
extra spaces to align statements and parts of statements.
• Most statements end with a semicolon. But when a statement requires a set of braces
{ }, the statement ends with the right brace. Then, the code within the braces can be
referred to as a block of code.
• To code a single-line comment, type // followed by the comment. You can code a
single-line comment on a line by itself or after a statement. A comment that’s coded
after a statement is sometimes called an end-of-line comment.
• To code a block comment, type /* at the start of the block and */ at the end. You can
also code asterisks to identify the lines in the block, but that isn’t necessary.

Figure 2-1 How to code statements and comments


Section 1 Essential Java skills

How to create identifiers


As you code a Java program, you need to create and use identifiers. These
are the names in the program that you define. In each program, for example,
you need to create an identifier for the name of the program and for the vari­
ables that are used by the program.
Figure 2-2 shows you how to create identifiers. In brief, you must start each
identifier with a letter, underscore, or dollar sign. After that first character, you
can use any combination of letters, underscores, dollar signs, or digits.
Since Java is case-sensitive, you need to be careful when you create and use
identifiers. If, for example, you define an identifier as CustomerAddress, you
can’t refer to it later as Customeraddress. That’s a common coding error.
When you create an identifier, you should try to make the name both
meaningful and easy to remember. To make a name meaningful, you should use
as many characters as you need, so it’s easy for other programmers to read and
understand your code. For instance, netPrice is more meaningful than nPrice,
and nPrice is more meaningful than np.
To make a name easy to remember, you should avoid abbreviations. If, for
example, you use nwCst as an identifier, you may have difficulty remembering
whether it was nCust, nwCust, or nwCst later on. If you code the name as
newCustomer, though, you won’t have any trouble remembering what it was.
Yes, you type more characters when you create identifiers that are meaningful
and easy to remember, but that will be more than justified by the time you’ll
save when you test, debug, and maintain the program.
For some common identifiers, though, programmers typically use just one
or two lowercase letters. For instance, they often use the letters i,j, and k to
identify counter variables. You’ll see examples of this later in this chapter.
Notice that you can’t create an identifier that is the same as one of the Java
keywords. These 50 keywords are reserved by the Java language and are the
basis for that language. To help you identify keywords in your code, Java IDEs
display these keywords in a different color than the rest of the Java code. For
example, NetBeans displays keywords in blue. As you progress through this
book, you’ll learn how to use almost all of these keywords.
Chapter 2 Introduction to Java Programming

Valid identifiers
InvolceApp $orderTotal 1
Invoice _orderTotal X
InvolceApp2 inputstring TITLE
subtotal gettotal MONTHS PER YEAR
di scountPercent $ 64 Valid

The rules for naming an identifier


• Start each identifier with a letter, underscore, or dollar sign. Use letters, dollar
signs, underscores, or digits for subsequent characters.
• Use up to 255 characters.
• Don’t use Java keywords.

Keywords
boolean if interface class true
char else package volatile false
byte final swi tch while throws
float private case return native
void protected break throw implements
short public default try import
double static for catch synchronized
int new continue finally const
long this do transient goto
abstract super extends instanceof null

Description
• An identifier is any name that you create in a Java program. These can be the
names of classes, methods, variables, and so on.
• A keyword is a word that’s reserved by the Java language. As a result, you can’t use
keywords as identifiers.
• When you refer to an identifier, be sure to use the correct uppercase and lowercase
letters because Java is a case-sensitive language.

Figure 2-2 How to create identifiers


Section 1 Essential Java skills

How to declare a class and a main method


In the last chapter, you learned that if you use NetBeans to create a project, it
can generate a main class with a main method for the project. Although you saw
the code for four different classes and three different main methods in chapter 1,
figure 2-3 now presents the syntax for declaring any class or main method. Even
if you use NetBeans, you should be familiar with this syntax.
To code a class, you begin with a class declaration. In the syntax for declar­
ing a class, the boldfaced words are Java keywords, and the words that aren’t
boldfaced represent code that the programmer supplies. The bar (I) in this syntax
means that you have a choice between the two items that the bar separates. In this
case, the bar means that you can start the declaration with the public keyword or
the private keyword.
The public and private keywords are access modifiers that control the scope
of a class. Usually, a class is declared public, which means that other classes can
access it. Later in this book, you’ll learn when and how to use private classes.
After the public keyword and the class keyword, you code the name of the
class using the basic rules for creating an identifier. When you do, it’s a common
coding convention to start every word within a class name with a capital letter
and to use letters and digits only. We also recommend that you use a noun or a
noun that’s preceded by one or more adjectives for your class names.
After the class name, the syntax summary shows a left brace, the statements
that make up the class, and a right brace. It’s a good coding practice, though, to
type your ending brace right after you type the starting brace to prevent missing
braces. When you use NetBeans, the ending brace is automatically added after
you type the starting brace and then press the Enter key.
The two InvoiceApp classes in this figure show how a class works. Notice
that the only difference between the two classes is where the opening braces for
the class and the block of code within the class are placed. Although either
technique is acceptable, we’ve chosen to use the first technique for this book
whenever possible.
Within a class, you code one or more methods, which are pieces of code that
perform the actions of the application (they’re similar to functions in some
programming languages). As you know, the main method is a special kind of
method that’s automatically executed when the class that contains it is run. All
Java programs contain a main method that starts the program.
To code a main method, you begin by coding a main method declaration
within the class declaration as shown in the two InvoiceApp classes in this figure.
Although I won’t describe this declaration, you should know that all main
method declarations are coded exactly as shown. You’ll learn more about the
keywords used by this declaration later in this book.
To make the structure of the main method clear, it’s indented and its starting
and ending braces are aligned so it’s easy to see where the method begins and
ends. Then, between the braces, you can see the one statement that this main
method performs. This statement displays a message to the user, and you’ll learn
more about it later in this chapter.
Chapter 2 Introduction to Java Programming

The syntax for declaring a class


public Iprivate class ClassName
{
statements
}
The syntax for declaring a main method
public static void main(String[] args)
{
statements
}
A public class named InvoiceApp that contains a main method
// declare the class
// begin the class

System.out.println("Welcome to the Invoice Total Calculator");


}
} // end the class

The same class with different brace placement


public class InvoiceApp { // declare and begin the class

}
The rules for naming a class
• Start the name with a capital letter.
• Use letters and digits only.
• Follow the other rules for naming an identifier.

Recommendations for naming a class


• Start every word within a class name with an initial cap.
• Each class name should be a noun or a noun that’s preceded by one or more adjectives.

Description
• A Java application consists of one or more classes that start with a class declaration. You
write the code for the class within the opening and closing braces of the declaration.
• The public and private keywords are access modifiers that control what parts of the
program can use the class. Most classes are declared public, which means that the class
can be used by all parts of the program.
• The file name for a class is the same as the class name with java as the extension.
• A method is a block of code that performs a task.
• Every Java application contains one main method that you can declare exactly as shown
above. This is called the main method declaration.
• The statements between the braces in a main method declaration are run when the pro­
gram is executed.

Figure 2-3 How to declare a class and a main method


Section 1 Essential Java skills

How to work with numeric variables


In this topic, you’ll learn how to work with numeric variables. This will
introduce you to the use of variables, assignment statements, arithmetic expres­
sions, and two of the eight primitive data types that are supported by Java. Then,
you can learn all the details about working with the primitive data types in the
next chapter.

How to declare and initialize variables


A variable is used to store a value that can change as a program executes.
Before you can use a variable, you must declare its data type and name, and you
must assign a value to it to initialize it. The easiest way to do that is shown in
figure 2-4. Just code the data type, the variable name, the equals sign, and the
value that you want to assign to the variable.
This figure also summarizes two of the eight Java data types. You can use
the int data type to store integers, which are numbers that don’t contain decimal
places (whole numbers), and you can use the double data type to store numbers
that contain decimal places. In the next chapter, you’ll learn how to use the six
other primitive data types, but these are the two that you’ll probably use the
most.
As you can see in the summary, the double data type can be used to store
numbers with up to 16 significant digits. In case you aren’t familiar with
significant digits, they include any digit that identifies the precision of a num­
ber. That includes any non-zero digit as well as any zero digits between two
non-zero digits and any zero digits at the end of a number with decimal places.
For business applications, you’ll rarely need to use numbers with more than 16
significant digits.
To illustrate the declaration of variables, the first example in this figure
declares an int variable named scoreCounter with an initial value of 1. And the
second example declares a double variable named unitPrice with an initial value
of 14.95. When you assign values to double types, it’s a good coding practice to
include a decimal point, even if the initial value is a whole number. If, for
example, you want to assign the number 29 to the variable, you should code the
number as 29.0.
If you follow the naming recommendations in this figure as you name the
variables, it will make your programs easier to read and understand. In particu­
lar, you should capitalize the first letter in each word of the variable name,
except the first word, as in scoreCounter or unitPrice. This is commonly re­
ferred to as camel notation.
When you initialize a variable, you can assign a literal value like 1 or 14.95
to the variable as illustrated by the examples in this figure. However, you can
also initialize a variable to the value of another variable as shown in the second
example in this figure or to the value of an expression like the arithmetic
expressions shown in the next figure.
Chapter 2 Introduction to Java Programming

Two of the eight primitive data types

in t Integers from -2,147,483,648 to 2,147,483,647.


d o u b le Numbers with decimal places and up to 16 significant digits.

How to declare and initialize a variable in one statement


Syntax
type variableName = value;

Examples
int scoreCounter = 1; // initialize an integer variable
double unitPrice = 14.95; // initialize a double variable

How to code assignment statements


int quantity = 0; // initialize an integer variable
int maxQuantity = 100; // initialize another integer variable

// two assignment statements


quantity = 10; // quantity is now 10
quantity = maxQuantity; // quantity is now 100

Description
• A variable stores a value that can change as a program executes.
• Java provides for eight primitive data types that you can use for storing values in
memory. The two that you’ll use the most are the int and double data types. In the
next chapter, you’ll learn how to use the other primitive data types.
• The int data type is used for storing integers (whole numbers). The double data
type is used for storing numbers that can have one or more decimal places.
• Before you can use a variable, you must declare its data type and assign an initial
value to the variable. It’s common to initialize integer variables to 0 and double
variables to 0.0.
• An assignment statement assigns a value to a variable. This value can be a literal
value, another variable, or an expression like the arithmetic expressions that you’ll
learn how to code in the next figure. If a variable has already been declared, the
assignment statement doesn’t include the data type of the variable.

Naming recommendations for variables


• Start variable names with a lowercase letter and capitalize the first letter in all
words after the first word.
• Each variable name should be a noun or a noun preceded by one or more
adjectives.
• Try to use meaningful names that are easy to remember.

Figure 2-4 How to declare and initialize variables


Section 1 Essential Java skills

How to code assignment statements


After you declare a variable, you can assign a new value to it. To do that,
you code an assignment statement. In a simple assignment statement, you code
the variable name, an equals sign, and a new value. The new value can be a
literal value or the name of another variable as shown in figure 2-4. Or, the new
value can be the result of an expression like the arithmetic expressions shown in
figure 2-5.

How to code arithm etic expressions


To code simple arithmetic expressions, you can use the four arithmetic
operators that are summarized in figure 2-5. As the first group of statements
shows, these operators work the way you would expect them to with one
exception. If you divide one integer into another integer, any decimal places are
truncated. In contrast, if you divide a double into a double, the decimal places
are included in the result.
When you code assignment statements, it’s common to code the same
variable on both sides of the equals sign. For example, you can add 1 to the
value of a variable named counter with a statement like this:
counter = counter + 1;
In this case, if counter has a value of 5 when the statement starts, it will have a
value of 6 when the statement finishes. This concept is illustrated by the second
and third groups of statements.
What happens when you mix integer and double variables in the same
arithmetic expression? The integers are cast (converted) to doubles so the
decimal places can be included in the result. To retain the decimal places,
though, the result variable must be a double. This is illustrated by the fourth
group of statements.
Although it’s not shown in this figure, you can also code expressions that
contain two or more operators. When you do that, you need to be sure that the
operations are done in the correct sequence. You’ll learn more about that in the
next chapter.
Chapter 2 Introduction to Java Programming

The basic operators that you can use in arithmetic expressions


Operator Name Description
+ Addition Adds two operands.
- Subtraction Subtracts the right operand from the left operand.
* Multiplication Multiplies the right operand and the left operand.
/ Division Divides the right operand into the left operand. If both
operands are integers, then the result is an integer.

Statements that use simple arithmetic expressions


// integer arithmetic
int x = 14;
int y = 8;
int resultl = x + y; // resultl = 22
int result2 = x - y; // result2 = 6
int result3 = x * y; // result3 = 112
int result4 = x / y; // result4 = 1

// double arithmetic
double a = 8.5;
double b = 3.4;
double result5 = a + b; // results 11.9
double result6 = a - b; // résulte = 5.1
double result7 = a * b; // result7 = 28.9
double résulte = a / b; // résulte = 2.5

Statements that increment a counter variable


int invoiceCount = 0;
invoiceCount = invoiceCount + 1; // invoiceCount = 1
invoiceCount = invoiceCount + 1 ; // invoiceCount = 2

Statements that add amounts to a total


double invoiceAmountl = 150.25;
double invoiceAmount2 = 100.75;
double invoiceTotal = 0.0;
invoiceTotal = invoiceTotal + invoiceAmountl; // invoiceTotal = 150.25
invoiceTotal = invoiceTotal + invoiceAmount2; // invoiceTotal = 251.00

Statements that mix int and double variables


int result9 = invoiceTotal / invoiceCount // result9 = 125
double resultlO = invoiceTotal / invoiceCount // resultlO = 125.50

Description
• An arithmetic expression consists of one or more operands and arithmetic
operators.
• When an expression mixes the use of int and double variables, Java automatically
casts the int types to double types. To retain the decimal places, the variable that
receives the result must be a double.
• In the next chapter, you’ll learn how to code expressions that contain two or more
operators.

Figure 2-5 How to code arithmetic expressions


Section 1 Essential Java skills

How to work with string variables


In the topics that follow, you’ll learn some basic skills for working with
strings. For now, these skills should be all you need for many of the programs
you develop. Keep in mind, though, that many programs require extensive string
operations. That’s why chapter 13 covers strings in more detail.

How to create a String object


A string can consist of any letters, numbers, and special characters. To
declare a string variable, you use the syntax shown in figure 2-6. Although this
is much like the syntax for declaring a numeric variable, a string is an object
that’s created from the String class when a string variable is declared. Then, the
String object refers to string data. When you declare a string variable, you must
capitalize the String keyword because it is the name of a class, not a primitive
data type.
In the next topic and in chapter 7, you’ll learn more about classes and
objects. For now, though, all you need to know is that string variables work
much like numeric variables, except that they store string data instead of nu­
meric data.
When you declare a String object, you can assign a string literal to it by
enclosing the characters within double quotes. You can also assign an empty
string to it by coding a set of quotation marks with nothing between them.
Finally, you can use the null keyword to assign a null value to a String object.
That indicates that the value of the string is unknown.

How to join and append strings


If you want to join, or concatenate, two or more strings into one, you can
use the + operator. For example, you can join a first name, a space, and a last
name as shown in the second example in figure 2-6. Then, you can assign that
string to a variable. Notice that when concatenating strings, you can use string
variables or string literals.
You can also join a string with a primitive data type. This is illustrated in the
third example in this figure. Here, a variable that’s defined with the double data
type is appended to a string. When you use this technique, Java automatically
converts the double value to a string.
You can use the + and += operators to append a string to the end of a string
that’s stored in a string variable. If you use the + operator, you need to include
the variable on both sides of the = operator. Otherwise, the assignment state­
ment will replace the old value with the new value instead of appending the old
value to the new value. Since the += operator provides a shorter and safer way
to append strings, this operator is commonly used.
Chapter 2 Introduction to Java Programming

The syntax for declaring and initializing a string variable


String variableName = value;

Example 1: How to declare and initialize a string


String messagel = "Invalid data entry.";
String message2 =
String message3 = null;

Example 2: How to join strings


String firstName = "Bob"; // firstName is Bob
String lastName = "Smith"; // lastName is Smith
String name = firstName + " " + lastName; // name is Bob Smith

Example 3: How to join a string and a number


double price = 14.95;
String priceString = "Price: + price;

Example 4: How to append one string to another with the + operator


firstName = "Bob"; // firstName is Bob
lastName = "Smith"; // lastName is Smith
name = firstName + " "; // name is Bob followed by a space
name = name + lastName; // name is Bob Smith

Example 5: How to append one string to another with the += operator


firstName = "Bob"; // firstName is Bob
lastName = "Smith"; // lastName is Smith
name = firstName + 1 // name is Bob followed by a space
name += lastName; // name is Bob Smith

Description
• A string can consist of any characters in the character set including letters, num­
bers, and special characters like *, &, and #.
• In Java, a string is actually a String object that’s created from the String class that’s
part of the Java API (.Application Programming Interface). The API provides all the
classes that are included as part of the JDK.
• To specify the value of a string, you can enclose text in double quotation marks.
This is known as a string literal.
• To assign a null value to a string, you can use the null keyword. This means that the
value of the string is unknown.
• To assign an empty string to a String object, you can code a set of quotation marks
with nothing between them. This means that the string doesn’t contain any
characters.
• To join (or concatenate) a string with another string or a data type, use a plus sign.
Whenever possible, Java will automatically convert the data type so it can be used
as part of the string.
• When you append one string to another, you add one string to the end of another.
To do that, you can use assignment statements.
• The += operator is a shortcut for appending a string expression to a string variable.

Figure 2-6 How to create and use strings


Section 1 Essential Java skills

How to include special characters in strings


Figure 2-7 shows how to include certain types of special characters within a
string. In particular, this figure shows how to include backslashes, quotation
marks, and control characters such as new lines, tabs, and returns in a string. To
do that, you can use the escape sequences shown in this figure.
As you can see, each escape sequence starts with a backslash. The
backslash tells the compiler that the character that follows should be treated as a
special character and not interpreted as a literal value. If you code a backslash
followed by the letter n, for example, the compiler will include a new line
character in the string. You can see how this works in the first example in this
figure. If you omitted the backslash, of course, the compiler would just include
the letter n in the string value. The escape sequences for the tab and return
characters work similarly, as you can see in the second example.
To code a string literal, you enclose it in double quotes. If you want to
include a double quote within a string literal, then, you must use an escape
sequence. This is illustrated in the third example. Here, the \" escape sequence
is used to include two double quotes within the string literal.
Finally, you need to use an escape sequence if you want to include a
backslash in a string literal. To do that, you code two backslashes as shown in
the fourth example. If you code a single backslash, the compiler will treat the
next character as a special character. That will cause a compiler error if the
character isn’t a valid special character. And if the character is a valid special
character, the results won’t be what you want.
Chapter 2 Introduction to Java Programming

Common escape sequences


Sequence Character
\n New line
\t Tab
\r Return
\" Quotation mark
\\ Backslash

Example 1: New line


String
"Code: JSPS\nPrice: $49.50"

Result
Code : JSPS
Price: $49.50

Example 2: Tabs and returns


String
"Joe\tSmith\rKate\tLewi s"

Result
Joe Smith
Kate Lewis

Example 3: Quotation marks


String
"Type \"x\" to exit"

Result
Type "x" to exit

Example 4: Backslash
String
"C:\\j ava\\files"

Result
C:\java\files

Description
• Within a string, you can use escape sequences to include certain types of special
characters.

Figure 2-7 How to include special characters in strings


Section 1 Essential Java skills

How to use Java classes, objects,


and methods
So far, you’ve learned how to create String objects from the String class in
the Java API. As you develop Java applications, though, you need to use dozens
of different Java classes and objects. To do that, you need to know how to create
objects from Java classes, how to call Java methods, and how to import Java
classes.

How to create objects and call methods


To use a Java class, you usually start by creating an object from the class.
As the syntax in figure 2-8 shows, you do that by coding the Java class name,
the name that you want to use for the object, an equals sign, the new keyword,
and the Java class name again followed by a set of parentheses. Within the
parentheses, you code any arguments that are required by the constructor of the
object that’s defined in the class.
In the examples, the first statement shows how to create a Scanner object
named sc. The constructor for this object requires just one argument
(System.in), which represents console input. In contrast, the second statement
creates a Date object named now that represents the current date, but its con­
structor doesn’t require any arguments. As you go through this book, you’ll
learn how to create objects with constructors that require two or more argu­
ments, and you’ll see that a single class can provide more than one constructor
for creating objects.
When you create an object, you can think of the class as the template for the
object. That’s why the object can be called an instance of the class, and the
process of creating the object can be called instantiation. Whenever necessary,
you can create more than one object or instance from the class. For instance,
you often use several String objects in a single program.
Once you’ve created an object from a class, you can use the methods of the
class. To call one of these methods, you code the object name, a dot (period),
and the method name followed by a set of parentheses. Within the parentheses,
you code the arguments that are required by the method.
In the examples, the first statement calls the nextDouble method of the
Scanner object named sc to get data from the console. The second statement
calls the toString method of the Date object named now to convert the date and
time that’s stored in the object to a string. Neither one of these methods requires
an argument, but you’ll soon see some that do.
Besides methods that you can call from an object, some classes provide
static methods that can be called directly from the class. To do that, you substi­
tute the class name for the object name as illustrated by the third set of ex­
amples. Here, the first statement calls the toString method of the Double class,
and the second statement calls the parseDouble method of the Double class.
Both of these methods require one argument.
Chapter 2 Introduction to Java Programming

How to create an object from a class


Syntax
ClassName objectName = new ClassName(arguments);
Examples
Scanner sc = new Scanner(System.in); // creates a Scanner object named sc
Date now = new Date(); // creates a Date object named now

How to call a method from an object


Syntax
objectName.methodName(arguments)

Examples
double subtotal = sc.nextDouble(); // get a double entry from the console
String currentDate = now.toString(); // convert the date to a string

How to call a static method from a class


Syntax
ClassName.methodName(arguments)

Examples
String sPrice = Double.toString(price); // convert a double to a string
double total = Double.parseDouble(userEntry); // convert a string to a double

Description
• When you create an object from a Java class, you are creating an instance of the
class. Then, you can use the methods of the class by calling them from the object.
• Some Java classes contain static methods. These methods can be called directly
from the class without creating an object.
• When you create an object from a class, the constructor may require one or more
arguments. These arguments must have the required data types, and they must be
coded in the correct sequence separated by commas.
• When you call a method from an object or a class, the method may require one or
more arguments. Here again, these arguments must have the required data types
and they must be coded in the correct sequence separated by commas.
• Although you can use the syntax shown in this figure to create a String object, the
syntax in figure 2-6 is the preferred way to do that. Once a String object is created,
though, you call its methods from the object as shown above.
• In this book, you’ll leam how to use dozens of the Java classes and methods. You
will also leam how to create your own classes and methods.

Figure 2-8 How to create objects and call methods


Section 1 Essential Java skills

Incidentally, you can also use the syntax shown in this figure to create a
String object. However, the preferred way to create a String object is to use the
syntax shown in figure 2-6. Once a String object is created, though, you use the
syntax in this figure to call one of its methods. You’ll see examples of this later
in this chapter.
In the pages and chapters that follow, you’ll learn how to use dozens of
classes and methods. For now, though, you just need to focus on the syntax for
creating an object from a class, for calling a method from an object, and for
calling a static method from a class. Once you understand that, you’re ready to
learn how to import the Java classes you need for your programs.

How to import Java classes


In the API for the Java SE, groups of related classes are organized into
packages. In figure 2-9, you can see a list of some of the commonly used
packages. Since the java.lang package contains the classes that are used in
almost every Java program (such as the String class), this package is automati­
cally made available to all programs.
To use a class from a package other than java.lang, though, you’ll typically
include an import statement for that class at the beginning of the program. If
you don’t, you’ll still be able to use the class, but you’ll have to qualify it with
the name of the package that contains it each time you refer to it. Since that can
lead to a lot of unnecessary typing, we recommend that you always code an
import statement for the classes you use.
When you code an import statement, you can import a single class by
specifying the class name, or you can import all of the classes in the package by
typing an asterisk (*) in place of the class name. The first two statements in this
figure, for example, import a single class, while the next two import all of the
classes in a package. Although it requires less code to import all of the classes
in a package at once, importing one class at a time clearly identifies the classes
you’re using.
As this figure shows, Java provides two different technologies for building a
graphical user interface (GUI) that contains text boxes, command buttons,
combo boxes, and so on. The older technology, known as the Abstract Window
Toolkit (AWT), was used with versions 1.0 and 1.1 of Java. Its classes are stored
in the java.awt package. Since version 1.2 of Java, though, a new technology
known as Swing has been available. The Swing classes are stored in the
javax. swing package. In general, many of the newer package names begin with
javax instead of java. Here, the x indicates that these packages can be consid­
ered extensions to the original Java API.
In addition to the packages provided by the Java API, you can get packages
from third party sources, either as open-source code or by purchasing them. For
more information, check the Java web site. You can also create packages that
contain classes that you’ve written. You’ll learn how to do that in chapter 10.
Chapter 2 Introduction to Java Programming

Common packages
Package name Description
java.lang Provides classes fundamental to Java, including classes that work with
primitive data types, strings, and math functions.
java.text Provides classes to handle text, dates, and numbers.
java.util Provides various utility classes including those for working with collections.
java.io Provides classes to read data from files and to write data to files.
java.sgl Provides classes to read data from databases and to write data to databases.
java.applet An older package that provides classes to create an applet.
java.awt An older package called the Abstract Window Toolkit (AWT) that provides
classes to create graphical user interfaces.
java.awt.event A package that provides classes necessary to handle events.
javax.swing A newer package called Swing that provides classes to create graphical user
interfaces and applets.

The syntax of the import statement


import packagename.ClassName;
or
import packagename.* ;

Examples
import java.text.NumberFormat;
import java.uti1.Scanner;
import java.util.*;
import javax.swing.*;

How to use the Scanner class to create an object


With an import statement
Scanner sc = new Scanner(System.in);

Without an import statement


java.util.Scanner sc = new java.util.Scanner(System.in);

Description
• The API for the Java SE provides a large library of classes that are organized into
packages.
• All classes stored in the java.lang package are automatically available to all Java
programs.
• To use classes that aren’t in the java.lang package, you can code an import state­
ment as shown above. To import one class from a package, specify the package
name followed by the class name. To import all classes in a package, specify the
package name followed by an asterisk (*).
• If you don’t code an import statement for a class, you must qualify the class name
with the name of the package that contains it each time you refer to the class.

Figure 2-9 How to import Java classes


Section 1 Essential Java skills

How to use the API documentation


to research Java classes
If you refer back to figure 2-2, you can see that the Java language consists
of just 50 keywords that you can master with relative ease. What’s difficult
about using Java, though, is mastering the hundreds of classes and methods that
your applications will require. To do that, you frequently need to study the API
documentation that comes with Java, and that is one of the most time-consum­
ing aspects of Java programming.
Figure 2-10 summarizes some of the basic techniques for navigating
through the API documentation. Here, you can see the start of the documenta­
tion for the Scanner class, which goes on for many pages. To get there, you
click on the package name in the upper left frame and then on the class name in
the lower left frame.
If you scroll through the documentation for this class, you’ll get an idea of
the scale of the documentation that you’re dealing with. After a few pages of
descriptive information, you come to a summary of the eight constructors for
the class. After that, you come to a summary of the dozens of methods that the
class offers. That in turn is followed by more detail about the constructors, and
then by more detail about the methods.
At this point in your development, this is far more information than you can
handle. That’s why one of the goals of this book is to introduce you to the
dozens of classes and methods that you’ll use in most of the applications that
you develop. Once you’ve learned those, the API documentation will make
more sense to you, and you’ll be able to use that documentation to research
classes and methods that aren’t presented in this book. To get you started with
the use of objects and methods, figure 2-12 will show you how to use the
Scanner class.
It’s never too early to start using the documentation, though. So by all
means use the documentation to get more information about the methods that
are presented in this book and to research the other methods that are offered by
the classes that are presented in this book. After you leam how to use the
Scanner class, for example, take some time to do some research on that class.
You’ll get a chance to do that in exercise 2-4.
Chapter 2 Introduction to Java Programming

The documentation for the Scanner class


Scanner {Java Platform SE 7 } - M o z illa Firefox I = I Θ ImÈZml
File Edit V ie w H is to ry B o o km a rks To ols H elp

jfty w C 0 http://dcwnlcad,orade.conVjavase/7/docs/api/index.htrnl "Cl ’ > *! Google P

W S c a n n e r (Java P la tfo rm SE 7 )

java.security,cert Overview Package Use Tree Deprecated Index Help


java.security.interfaces _
java.security.spec Prev Class Hext Class Frames No Frames
java.sql
java.text Summary: Nested i Field : Constr : i.fethod Detail: Field I Constr I Metho-d
java.text.spi
java.util java.util
java.util.concurrent
java.util.concurrent-atomic Class Scanner

Random java.lang.Object
ResourceBundle java.util.Scanner
Res oureeBunci e.ControI All Implemented Interfaces:
jScannen
ServiceLoader CloseaBle, AutoCloseable, lterator<S1ring*
SimpleTimeZone
Stack
StringTokencer p u b lic f in a l c la s s S can n er
Timer e x te n d s O b je c t
TimerTask iir.p ie rp .e n t3 I t e r a t o r < S t r i n g > , C lo s e a fc le
TimeZone
TreeMap A simple text scanner which can parse primitive types and strings using regular expressions.
TreeSet
UUID A S canner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting
Vector tokens may then ce converted into values of different types using the various n e x t methods.
WeaKHashMap
For example, this code allows a userto read a number from S y ste m , in :
Enums
S c a n n e r s o = n ew S c a n n e r ( S y s t e m . i n ) ;
FormatterBigDecimalLayo i n c i = 3 C . nextlnc();
Locale.Category

E xcep tio n s As another example, this code allows lo n g types to be assigned from entries in a fileiryiiiurtoers:
ConcurrentModificationExc . S c a n n e r sc = new S c a n n e r (n ew F i l e ( ',rr.yNurr±;·er3', ) ) ;

http ;//do wnload, oracle,com/javase/7/docs/api/j ava/util/Scanner. html

Description
• The Java SE API contains thousands of classes and methods that can help you do
most of the tasks that your applications require.
• You can use a browser to view the Java SE API on the Internet by going to this
address:
http i//download.oracle.com/javaae/7/docs/api/index.html

• You can select the name of the package in the top left frame to display information
about the package and the classes it contains. Then, you can select a class in the
lower left frame to display the documentation for that class in the right frame.
• Once you display the documentation for a class, you can scroll through it or click
on a hyperlink to get more information.
• To make it easier to access the API documentation, you should bookmark the index
page. Then, you can easily redisplay this page whenever you need it.

Figure 2-10 How to use the API documentation to research Java classes
Section 1 Essential Java skills

How to use the console


for input and output
Most of the applications that you write will require some type of user
interaction. In particular, most applications will get input from the user and
display output to the user. Ever since version 1.5 of Java, the easiest way to get
input is to use the new Scanner class to retrieve data from the console. And the
easiest way to display output is to print it to the console.

How to use the System.out object


to print output to the console
To print output to the console, you can use the println and print methods of
the System.out object as shown in figure 2-11. Here, System.out refers to an
instance of the PrintStream class. Because this object is created automatically
by Java, you don’t have to include code that creates it in your program.
Both the println and print methods accept a string argument that specifies
the data to be printed. The only difference between the two is that the println
method starts a new line after it displays the data, and the print method doesn’t.
If you study the examples in this figure, you shouldn’t have any trouble
using these methods. For instance, the first statement in the first example uses
the println method to print the words “Welcome to the Invoice Total Calculator”
to the console. The second statement prints the string “Total: ” followed by the
value of the total variable (which is automatically converted to a string by this
join). The third statement prints the value of the variable named message to the
console. And the fourth statement prints a blank line since no argument is
coded.
Because the print method doesn’t automatically start a new line, you can
use it to print several data arguments on the same line. For instance, the three
statements in the second example use the print method to print “Total: ”, fol­
lowed by the total variable, followed by a new line character. Of course, you can
achieve the same result with a single line of code like this:
System.out.println("Total: " + total);
This figure also shows an application that uses the println method to print
seven lines to the console. In the main method of this application, the first four
statements set the values for four variables. Then, the next seven statements
print a welcome message, a blank line, the values for the four variables, and
another blank line.
When you work with console applications, you should know that the
appearance of the console may differ slightly depending on the operating
system. Even if the console looks a little different, however, it should work the
same.
Chapter 2 Introduction to Java Programming

Two methods of the System.out object


Method Description
println ( d a ta ) Prints the data argument followed by a new line character to the console,
print ( d a ta ) Prints the data to the console without starting a new line.

Example 1: The println method


System.out.println("Welcome to the Invoice Total Calculator");
System.out.println("Total: " + total);
System.out.println(message);
System.out.println() ; // print a blank line

Example 2: The print method


System.out.print("Total: ") ;
System.out.print(total) ;
System.out.print("\n") ;

Example 3: An application that prints data to the console


public class InvoiceApp
{
public static void main(String[] args)
{
// set and calculate the numeric values
double subtotal = 100; // set subtotal to 100
double discountPercent = .2; // set discountPercent to 20%
double discountAmount = subtotal * discountPercent;
double invoiceTotal = subtotal - discountAmount;

// print the data to the console


System.out.println("Welcome to the Invoice Total Calculator");
System.out.println();
System.out.println("Subtotal: " + subtotal);
System.out.println("Discount percent: " + discountPercent);
System.out.println("Discount amount: " + discountAmount);
System.out.println("Total: " + invoiceTotal);
System.out.printlnO ;

}
The console output
f- ----- *
Welcome to the Invoice Total Calculator

Subtotal: 100.0
Discount percent: 0.2
Discount amount: 20.0
Total: 80.0
W- --------- J

Description
• Although the appearance of a console may differ from one system to another, you
can always use the print and println methods to print data to the console.

Figure 2-11 How to use the System.out object to print output to the console
Section 1 Essential Java skills

How to use the Scanner class


to read input from the console
Figure 2-12 shows how you can use the Scanner class to read input from the
console. To start, you create a Scanner object by using a statement like the one
in this figure. Here, sc is the name of the Scanner object that is created and
Systemen represents console input, which is the keyboard. Like the System.out
object, the System.in object is created by Java automatically. Because of that,
you can use this object with a Scanner object whenever you want to get console
input.
Once you’ve created a Scanner object, you can use the next methods to read
data from the console. The method you use depends on the type of data you
need to read. To read string data, for example, you use the next method. To read
integer data, you use the nextlnt method. To read double data, you use the
nextDouble method. And to read all of the data on a line, you use the nextLine
method.
The examples in this figure illustrate how these methods work. Here, the
first statement gets a string and assigns it to a string variable named name. The
second statement gets an integer and assigns it to an int variable named count.
The third statement gets a double and assigns it to a double variable named
subtotal. And the fourth statement reads any remaining characters on the line.
Each entry that a user makes is called a token, and a user can enter more
than one token before pressing the Enter key. To do that, the user separates the
entries by one or more space, tab, or return characters. This is called
whitespace. Then, each next method gets the next token that has been entered.
If, for example, you press the Enter key (a return character), type 100, press the
Tab key, type 20, and press the Enter key again, the first token is 100 and the
second one is 20.
If you want to get string data that includes whitespace, you can use the
nextLine method. If, for example, the user enters “New York” and presses the
Enter key, you can use the nextLine method to get the entire entry as a single
string.
If the user doesn’t enter the type of data that the next method is looking for,
an error occurs and the program ends. In Java, an error like this is also known as
an exception. If, for example, the user enters a double value but the nextlnt
method is used to get it, an exception occurs. In chapter 5, you’ll learn how to
prevent this type of error.
Although this figure only shows methods for working with String objects
and int and double types, the Scanner class includes methods for working with
most of the other data types that you’ll learn about in the next chapter. It also
includes methods that let you check what type of data the user entered. As
you’ll see in chapter 5, you can use these methods to avoid exceptions by
checking the data type before you issue the next method.
Chapter 2 Introduction to Java Programming

The Scanner class


j ava.util.Scanner

How to create a Scanner object


Scanner sc = new Scanner(System.in);

Common methods of a Scanner object


Method Description
n e x t () Returns the next token stored in the scanner as a String object.
nextlnt() Returns the next token stored in the scanner as an int value.
nextDouble() Returns the next token stored in the scanner as a double value.
nextLine() Returns any remaining input on the current line as a String
object and advances the scanner to the next line.

How to use the methods of a Scanner object


String name = sc.nextO;
int count = sc.nextlnt();
double subtotal = sc.nextDouble();
String cityName = sc.nextLine();

Description
• To create a Scanner object that gets input from the console, specify System.in in the
parentheses.
• When one of the next methods of the Scanner class is run, the application waits for
the user to enter data with the keyboard. To complete the entry, the user presses the
Enter key.
• Each entry that a user makes is called a token. A user can enter two or more tokens
by separating them with whitespace, which consists of one or more spaces, tab
characters, or return characters.
• The entries end when the user presses the Enter key. Then, the first next, nextlnt, or
nextDouble method gets the first token; the second next, nextlnt, or nextDouble
method gets the second token; and so on. In contrast, the nextLine method gets all
of the input or remaining input on the current line.
• If the user doesn’t enter the type of data that the next method expects, an error
occurs and the program ends. In Java, this type of error is called an exception.
You’ll leam more about this in chapter 5.
• Since the Scanner class is in the java.util package, you’ll want to include an import
statement whenever you use this class.

Note
• The Scanner class was introduced in version 1.5 of the JDK.

Figure 2-12 How to use the Scanner class to read input from the console
Section 1 Essential Java skills

Examples that get input from the console


Figure 2-13 presents two examples that get input from the console. The first
example starts by creating a Scanner object. Then, it uses the print method of
the System.out object to prompt the user for three values, and it uses the next
methods of the Scanner object to read those values from the console. Because
the first value should be a string, the next method is used to read this value.
Because the second value should be a double, the nextDouble method is used to
read it. And because the third value should be an integer, the nextlnt method is
used to read it.
After all three values are read, a calculation is performed using the int and
double values. Then, the data is formatted and the println method is used to
display the data on the console. You can see the results of this code in this
figure.
Unlike the first example, which reads one value per line, the second ex­
ample reads three values in a single line. Here, the first statement uses the print
method to prompt the user to enter three integer values. Then, the next three
statements use the nextlnt method to read those three values. This works be­
cause a Scanner object uses whitespace (spaces, tabs, or returns) to separate the
data that’s entered at the console into tokens.
Chapter 2 Introduction to Java Programming

Example 1: Code that gets three values from the user


// create a Scanner object
Scanner sc = new Scanner(System.in);

// read a string
System.out.print("Enter product code: ");
String productCode = sc.nextO;

// read a double value


System.out.print("Enter price: ") ;
double price = sc.nextDouble();

// read an int value


System.out.print("Enter quantity: ");
int quantity = sc.nextlnt();

// perform a calculation and display the result


double total = price * quantity;
System.out.println() ;
System.out.println(quantity + " " + productCode
+ " @ " + price + " = " + total);
System.out.println() ;

The console after the program finishes


/?------------------------------------------------------------------- ----------------------
Enter product code: cshp
Enter price: 49.50
Enter quantity: 2

2 cshp @ 49.5 = 99.0


Vt-----------------------------------------------------------------------------------------4

Example 2: Code that reads three values from one line


// read three int values
System.out.print("Enter three integer values: ");
int il = sc.nextlnt();
int i2 = sc.nextlnt();
int i3 = sc.nextlnt();

// calculate the average and display the result


int total = il + i2 + i3;
int avg = total / 3;
System.out.println("Average: " + avg);
System.out.println() ;

The console after the program finishes


Enter three integer values: 99 88 92

( Average: 93

Figure 2-13 Examples that get input from the console


Section 1 Essential Java skills

How to code simple control statements


As you write programs, you need to determine when certain operations
should be done and how long repetitive operations should continue. To do that,
you code control statements like the if/else and while statements. This topic will
get you started with the use of these statements, but first you need to leam how to
write expressions that compare numeric and string variables.

How to compare numeric variables


Figure 2-14 shows how to code Boolean expressions that use the six rela­
tional operators to compare int and double data types. This type of expression
evaluates to either true or false based on the result of the comparison, and the
operands in the expression can be either variables or literals.
For instance, the first expression in the first set of examples is true if the
value of the variable named discountPercent is equal to the literal value 2.3. The
second expression is true if the value of subtotal is not equal to zero. And the
sixth expression is true if the value of the variable named quantity is less than or
equal to the value of the variable named reorderPoint.
Although you shouldn’t have any trouble coding simple expressions like
these, you must remember to code two equals signs instead of one for the equal­
ity comparison. That’s because a single equals sign is used for assignment
statements. As a result, if you try to code a Boolean expression with a single
equals sign, your code won’t compile.
When you compare numeric values, you usually compare values of the same
data type. However, if you compare different types of numeric values, Java will
automatically cast the less precise numeric type to the more precise type. For
example, if you compare an int type to a double type, the int type will be cast to
the double type before the comparison is made.

How to compare string variables


Because a string is an object, not a primitive data type, you can’t use the
relational operators to compare strings. Instead, you must use the equals or
equalsIgnoreCase methods of the String class that are summarized in figure 2-14.
As you can see, both of these methods require an argument that provides the
String object or literal that you want to compare with the current String object.
In the examples, the first expression is true if the value in the string named
userEntry equals the literal value “Y”. In contrast, the second expression uses the
equalsIgnoreCase method, so it’s true whether the value in userEntry is “Y” or
“y”. Then, the third expression shows how you can use the not operator (!) to
reverse the value of a Boolean expression that compares two strings. Here, the
expression will evaluate to true if the lastName variable is not equal to “Jones”.
The fourth expression is true if the string variable named code equals the string
variable named productCode.
Chapter 2 Introduction to Java Programming

Relational operators
Operator Name Description
== Equality Returns a true value if both operands are equal.
1- Inequality Returns a true value if the left and right operands
are not equal.
> Greater Than Returns a true value if the left operand is greater
than the right operand.
< Less Than Returns a true value if the left operand is less
than the right operand.
>= Greater Than Or Equal Returns a true value if the left operand is greater
than or equal to the right operand.
<= Less Than Or Equal Returns a true value if the left operand is less
than or equal to the right operand.

Examples of conditional expressions


discountPercent = = 2 . 3 // equal to a numeric literal
subtotal 1= 0 // not equal to a numeric literal
years > 0 // greater than a numeric literal
i < months // less than a numeric variable
subtotal >= 500 // greater than or equal to a numeric literal
quantity <= reorderPolnt // less than or equal to a numeric variable

Two methods of the String class


Method Description
equals(String) Compares the value of the String object with a String
argument and returns a true value if they are equal.
This method makes a case-sensitive comparison.
equalsIgnoreCase(String) Works like the equals method but is not case-sensitive.

Examples
userEntry.equals("Y") // equal to a string literal
userEntry.equalsIgnoreCase("Y") // equal to a string literal
(llastName.equals("Jones")) // not equal to a string literal
code.equalsIgnoreCase(productCode) // equal to another string variable

Description
• You can use the relational operators to compare two numeric operands and return a
Boolean value that is either true or false.
• To compare two numeric operands for equality, make sure to use two equals signs.
If you only use one equals sign, you’ll code an assignment statement, and your
code won’t compile.
• If you compare an int with a double, Java will cast the int to a double.
• To test two strings for equality, you must call one of the methods of the String
object. If you use the equality operator, you will get unpredictable results (more
about this in chapter 4).

Figure 2-14 How to compare numeric and string variables


Section 1 Essential Java skills

How to code if/else statements


Figure 2-15 shows how to use the if/else statement (or just if statement) to
control the logic of your applications. This statement is the Java implementation
of a control structure known as the selection structure because it lets you select
different actions based on the results of a Boolean expression.
As you can see in the syntax summary, you can code this statement with
just an if clause, you can code it with one or more else if clauses, and you can
code it with a final else clause. In any syntax summary, the ellipsis (...) means
that the preceding element (in this case the else if clause) can be repeated as
many times as it is needed. And the brackets [ ] mean that the element is op­
tional.
When an if statement is executed, Java begins by evaluating the Boolean
expression in the if clause. If it’s true, the statements within this clause are
executed and the rest of the if/else statement is skipped. If it’s false, Java
evaluates the first else if clause (if there is one). Then, if its Boolean expression
is true, the statements within this else if clause are executed, and the rest of the
if/else statement is skipped. Otherwise, Java evaluates the next else if clause.
This continues with any remaining else if clauses. Finally, if none of the
clauses contains a Boolean expression that evaluates to true, Java executes the
statements in the else clause (if there is one). However, if none of the Boolean
expressions are true and there is no else clause, Java doesn’t execute any
statements.
If a clause only contains one statement, you don’t need to enclose that
statement in braces. This is illustrated by the first statement in the first example
in this figure. However, if you want to code two or more statements within a
clause, you need to code the statements in braces. The braces identify the block
of statements that is executed for the clause.
If you declare a variable within a block, that variable is available only to the
other statements in the block. This can be referred to as block scope. As a result,
if you need to access a variable outside of the block, you should declare it
before the if statement. You’ll see this illustrated by the program at the end of
this chapter.
Chapter 2 Introduction to Java Programming

The syntax of the if/else statement


if (booleanExpression) {statements}
[else if (booleanExpression) {statements}] ...
[else {statements}]

Example 1: If statements without else if or else clauses


With a single statement
if (subtotal >= 100)
discountPercent = .2;

With a block of statements


if (subtotal >= 100)
{
discountPercent = .2;
status = "Bulk rate";
}

Example 2: An if statement with an else clause


if (subtotal >= 100)
discountPercent = .2;
else
discountPercent = .1;

Example 3: An if statement with else if and else clauses


if (eustomerType.equals ("T"))
discountPercent = .4;
else if (eustomerType.equals("C"))
discountPercent = .2;
else if (subtotal >= 100)
discountPercent = .2;
else
discountPercent = .1;

Description
• An if/else statement, or just if statement, always contains an if clause. In addition, it
can contain one or more else if clauses, and a final else clause.
• If a clause requires just one statement, you don’t have to enclose the statement in
braces.
• If a clause requires more than one statement, you enclose the block of statements in
braces.
• Any variables that are declared within a block have block scope so they can only be
used within that block.

Figure 2-15 How to code if/else statements


Section 1 Essential Java skills

How to code while statements


Figure 2-16 shows how to code a while statement. This is one way that Java
implements a control structure know as the iteration structure because it lets
you repeat a block of statements. As you will see in chapter 4, though, Java also
offers other implementations of this structure.
When a while statement is executed, the program repeats the statements in
the block of code within the braces while the expression in the statement is true.
In other words, the statement ends when the expression becomes false. If the
expression is false when the statement starts, the statements in the block of code
are never executed.
Because a while statement loops through the statements in the block as
many times as needed, the code within a while statement is often referred to as a
while loop. Here again, any variables that are defined within the block have
block scope, which means that they can’t be accessed outside the block.
The first example in this figure shows how to code a loop that executes a
block of statements while a variable named choice is equal to either “y” or “Y”.
In this case, the statements within the block get input from the console, process
it, and display output. This is a common way to control the execution of a
program, and you’ll see this illustrated in detail in the next figure.
The second example shows how to code a loop that adds the numbers 1
through 4 and stores the result in a variable named sum. Here, a counter vari­
able (or just counter) named i is initialized to 1 and the sum variable is initial­
ized to zero before the loop starts. Then, each time through the loop, the value
of i is added to sum and one is added to i. Because the value of i is 1 the first
time through the loop, for example, 1 is added to sum so its value becomes 1.
The second time through the loop, 2 is added to sum so its value becomes 3.
The third time through the loop, 3 is added to sum so its value becomes 6. And
the fourth time through the loop, 4 is added to sum so its value becomes 10.
When the value of i becomes 5, though, the expression in the while statement is
no longer true and the loop ends. The use of a counter like this is a common
coding practice, and single letters like i, j, and k are commonly used as the
names of counters.
When you code loops, you must be careful to avoid infinite loops. If, for
example, you forget to code a statement that increments the counter variable in
the second example, the loop will never end because the counter will never get
to 5. Then, you have to cancel the application so you can debug your code. In
NetBeans, you can do that by clicking on the Stop button that’s available from
the Output window when a console application is running.
Chapter 2 Introduction to Java Programming

The syntax of the while loop


while (booleanExpression)
{
statements
}

Example 1: A loop that continues while choice is "y" or "Y"


String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get the invoice subtotal from the user
Scanner sc = new Scanner(System.in);
System.out.print("Enter subtotal: ■) ;
double subtotal = sc.nextDouble();

// the code that processes the user's entry goes here

// see if the user wants to continue


System.out.print("Continue? (y/n): ");
choice = sc.nextO;
System.out.println();
}

Example 2: A loop that calculates the sum of the numbers 1 through 4


int i = 1;
int sum = 0 ;
while (i < 5)
{
sum = sum + i ;
i = i + 1;
}

Description
• A while statement executes the block of statements within its braces as long as the
Boolean expression is true. When the expression becomes false, the while state­
ment skips its block of statements so the program continues with the next statement
in sequence.
• The statements within a while statement can be referred to as a while loop.
• Any variables that are declared in the block of a while statement have block scope.
• If the Boolean expression in a while statement never becomes false, the statement
never ends. Then, the program goes into an infinite loop. In NetBeans, you can
cancel an infinite loop by clicking on the Stop button in the Output window.

Figure 2-16 How to code while loops


Section 1 Essential Java skills

Two illustrative applications


You have now learned enough about Java to write simple applications of
your own. To show you how you can do that, this chapter ends by presenting two
illustrative applications.

The Invoice application


In chapter 1, you saw how the console looks when displayed by NetBeans.
Now, this figure shows the console in a platform-neutral format that’s easy to
read. This is the format that will be used to display console output for the rest of
this book.
Figure 2-17 shows the console and code for an Invoice application. Although
this application is simple, it gets input from the user, performs calculations that
use this input, and displays the results of the calculations. It continues until the
user enters anything other than “Y” or “y” in response to the Continue prompt.
The Invoice application starts by displaying a welcome message at the
console. Then, it creates a Scanner object named sc that will be used in the while
loop of the program. Although this object could be created within the while loop,
that would mean that the object would be recreated each time through the loop,
and that would be inefficient.
Before the while statement is executed, a String object named choice is
initialized to “y”. Then, the loop starts by getting a double value from the user
and storing it in a variable named subtotal. After that, the loop uses an if/else
statement to calculate the discount amount based on the value of subtotal. If, for
example, subtotal is greater than or equal to 200, the discount amount is .2 times
the subtotal (a 20% discount). If that condition isn’t true but subtotal is greater
than or equal to 100, the discount is .1 times the subtotal (a 10% discount).
Otherwise, the discount amount is zero. When the if/else statement is finished,
an assignment statement calculates the invoice total by subtracting
discountAmount from subtotal.
At that point, the program displays the discount percent, discount amount,
and invoice total on the console. Then, it displays a message that asks the user if
he or she wants to continue. If the user enters “y” or “Y”, the loop is repeated.
Otherwise, the program ends.
Although this application illustrates most of what you’ve learned in this
chapter, it has a couple of shortcomings. First, the numeric values that are
displayed should be formatted with two decimal places since these are currency
values. In the next chapter, you’ll learn how to do that type of formatting.
Second, an exception will occur and the program will end prematurely if the
user doesn’t enter one valid double value for the subtotal each time through the
loop. This is a serious problem that isn’t acceptable in a professional program,
and you’ll learn how to prevent problems like this in chapter 5.
In the meantime, if you’re new to programming, you can learn a lot by
writing simple programs like the Invoice program. That will give you a chance to
become comfortable with the coding for input, calculations, output, if/else
statements, and while statements.
Chapter 2 Introduction to Java Programming

The console input and output for a test run


(r - Welcome to the Invoice Total Calculator ----- Λ

Enter subtotal: 150


Discount percent: 0.1
Discount amount: 15.0
Invoice total: 135.0

Continue? (y/n):
V --------- 1
The code for the application
import java.util.Scanner;

public class InvoiceApp


{
public static void main(String[] args)
{
System.out.println("Welcome to the Invoice Total Calculator");
System.out.println(); // print a blank line

Scanner sc = new Scanner(System.in);

// perform invoice calculations until choice isn't equal to "y" or "Y"


String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get the invoice subtotal from the user
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();

// calculate the discount amount and total


double discountPercent = 0.0;
if (subtotal >= 200)
discountPercent = .2;
else if (subtotal >= 100)
discountPercent = .1;
else
discountPercent = 0.0;

double discountAmount = subtotal * discountPercent;


double total = subtotal - discountAmount;

// display the discount amount and total


String message = "Discount percent: " + discountPercent + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Invoice total: " + total + "\n";
System.out.println(message);

// see if the user wants to continue


System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.printlnO ;
}
}
}

Figure 2-17 The Invoice application


Section 1 Essential Java skills

The Test Score application


Figure 2-18 presents another Java application that will give you more ideas
for how you can apply what you’ve learned so far. If you look at the console
input and output for this application, you can see that it lets the user enter one or
more test scores. To end the application, the user enters a value of 999. Then,
the application displays the number of test scores that were entered, the total of
the scores, and the average of the scores.
If you look at the code for this application, you can see that it starts by
displaying the instructions for using the application. Then, it declares and
initializes three variables, and it creates a Scanner object that will be used to get
console input.
The while loop in this program continues until the user enters a test score
that’s greater than 100. To start, this loop gets the next test score. Then, if that
test score is less than or equal to 100, the program adds one to scoreCount,
which keeps track of the number of scores, and adds the test score to scoreTotal,
which accumulates the total of the scores. The if statement that does this is
needed, because you don’t want to increase scoreCount and scoreTotal if the
user enters 999 to end the program. When the loop ends, the program calculates
the average score and displays the score count, total, and average.
To include decimal places in the score average, this program declares
scoreTotal and averageScore as a double data types. Declaring scoreTotal as a
double type causes the score average to be calculated with decimal places.
Declaring the averageScore variable as a double type allows it to store those
decimal places.
To allow statements outside of the while loop to access the scoreTotal and
scoreCount variables, this program declares these variables before the while
loop. If these variables were declared inside the while loop, they would only be
available within that block of code and couldn’t be accessed by the statements
that are executed after the while loop. In addition, the logic of the program
wouldn’t work because these variables would be reinitialized each time through
the loop.
Here again, this program has some obvious shortcomings that will be
addressed in later chapters. First, the data isn’t formatted properly, but you’ll
learn how to fix that in the next chapter. Second, an exception will occur and the
program will end prematurely if the user enters invalid data, but you’ll learn
how to fix that in chapter 5.
Chapter 2 Introduction to Java Programming

The console input and output for a test run


(r~ -- ^
Please enter test scores that range from 0 to 100.
To end the program enter 999.

Enter score: 90
Enter score: 80
Enter score: 75
Enter score: 999

Score count: 3
Score total: 245.0
Average score: 81.66666666666667
V — 1

The code for the application


import java.util.Scanner;

public class TestScoreApp


{
public static void main(String[] args)
{
System.out.println(
"Please enter test scores that range from 0 to 100.");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line

// initialize variables and create a Scanner object


double scoreTotal = 0.0;
int scoreCount = 0;
int testScore = 0;
Scanner sc = new Scanner(System.in);

// get a series of test scores from the user


while (testScore <= 100)
{
// get the input from the user
System.out.print("Enter score: ");
testScore = sc.nextlnt();

// accumulate score count and score total


if (testScore <= 100)
{
scoreCount = scoreCount + 1;
scoreTotal = scoreTotal + testScore;
}
}
// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
String message = "\n"
+ "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
}
}

Figure 2-18 The Test Score application


Section 1 Essential Java skills

How to test and debug an application


In chapter 1, you were introduced to errors that are detected by NetBeans as
you enter code, called syntax errors. Because syntax errors keep an application
from being compiled, they are also commonly referred to as compile-time errors.
Once you’ve fixed the syntax errors, you’re ready to test and debug the applica­
tion as described in this topic. Then, in the next two chapters, you’ll learn several
more debugging techniques. And when you do the exercises, you’ll get lots of
practice testing and debugging.

How to test an application


When you test an application, you run it to make sure the application works
correctly. As you test, you should try every possible combination of valid and
invalid data to be certain that the application works correctly under every set of
conditions. Remember that the goal of testing is to find errors, or bugs, not to
show that an application works correctly.
As you test, you will encounter two types of bugs. The first type of bug
causes a runtime error also known as a runtime exception. A runtime error
causes the application to end prematurely, which programmers often refer to as
“crashing” or “blowing up.” In this case, an error message like the one in the first
example in figure 2-19 is displayed, and this message shows the line number of
the statement that was being executed when the error occurred.
The second type of bug produces inaccurate results when an application
runs. These bugs occur due to logic errors in the source code. For instance, the
second example in this figure shows output for the Test Score application. Here,
the final totals were displayed and the application ended before any input was
entered. This type of bug can be more difficult to find and correct than a runtime
error.

How to debug an application


When you debug a program, you find the cause of the bugs, fix them,
recompile, and test again. As you progress through this book and your programs
become more complex, you’ll see that debugging can be one of the most time-
consuming aspects of programming.
To find the cause of runtime errors, you can start by finding the source
statement that was running when the program crashed. You can usually do that
by studying the error message that’s displayed. In the first console in this figure,
for example, you can see that the statement at line 20 in the main method of the
InvoiceApp class was running when the program crashed. That’s the statement
that used the nextDouble method of the Scanner object, and that indicates that
the problem is invalid input data. In chapter 5, you’ll learn how to fix this bug.
To find the cause of incorrect output, you can start by figuring out why the
application produced the output that it did. For instance, you can start by asking
why the second application in this figure didn’t prompt the user to enter any test
scores. Once you figure that out, you’re well on your way to fixing the bug.
Chapter 2 Introduction to Java Programming

A runtime error that occurred while testing the Invoice application


Output - ch02Jnvoice (run) 9 :

u> run.:
Welcome to the Invoice Total Calculator

Enter subtotal: $100


Ex c e p t i o n in th r e a d " m ain” 3 a v a . u t i l .I n p u t M i s m a t c h S x c e p t i o n
et 3 a v a .u t i l - S c s n n e r .throwFor <S c a n n e r .3 a v a :909)
at 3 a v a .u t i l .S c a n n e r . n e x t (S c a n n e r .3 a v a :1 5 3 0 )
at 3 a v a . u t i l . S c a n n e r . n e x t D o u b l e {S c a n n e r .3 a v a :2 4 5 6 )
at I n v o i c e A p p . m a i n ,I n v o i c e A p p .3 a v a :20
Java Result: 1
BUI L D SUCCES S F U L {total tine: 3 seconds)

Incorrect output produced by the Test Score application


: Output - ch02_TestScore (run) ^ 83

H> ru n : >

to ToPlease enter test scores


end the program enter
that range from 0 to 100.
999.

Score count: 0
Score total: 0.0
Average score: NaN

BU ILD SUCCESSFUL { to ta l tim e : 1 second)

Description
• A syntax or compile-time error occurs when a statement can’t be compiled. Before
you can test an application, you must fix the syntax errors.
• To test an application, you run it to make sure that it works properly no matter what
combinations of valid and invalid data you enter. The goal of testing is to find the
errors (or bugs) in the application.
• To debug an application, you find the causes of the bugs and fix them.
• One type of bug leads to a runtime error (also known as a runtime exception) that
causes the program to end prematurely. This type of bug must be fixed before
testing can continue.
• Even if an application runs to completion, the results may be incorrect due to logic
errors. These bugs must also be fixed.

Debugging tips
• For a runtime error, go to the line in the source code that was running when the
program crashed. In NetBeans, you can do that by clicking on the link to the line of
source code. That should give you a strong indication of what caused the error.
• For a logical error, first figure out how the source code produced that output. Then,
fix the code and test the application again.

Figure 2-19 How to test and debug an application


Section 1 Essential Java skills

Perspective
The goal of this chapter has been to get you started with Java program­
ming and to get you started fast. Now, if you understand how the Invoice and
Test Score applications in figures 2-17 and 2-18 work, you’ve come a long
way. You should also be able to write comparable programs of your own.
Keep in mind, though, that this chapter is just an introduction to Java
programming. So in the next chapter, you’ll learn the details about working
with data. In chapter 4, you’ll learn the details about using control statements.
And in chapter 5, you’ll learn how to prevent and handle runtime exceptions.

Summary
• The statements in a Java program direct the operation of the program. The com­
ments document what the program does.
• You must code at least one public class for every Java program that you write. The
main method of this class is executed when you run the class.
• Variables are used to store data that changes as a program runs, and you use
assignment statements to assign values to variables. Two of the most common data
types for numeric variables are the int and double types.
• A string is an object that’s created from the String class, and it can contain any
characters in the character set. You can use the plus sign to join a string with
another string or a data type, and you can use assignment statements to append one
string to another. To include special characters in strings, you can use escape
sequences.
• When you use a constructor to create an object from a Java class, you are creating
an instance of the class. There may be more than one constructor for a class, and a
constructor may require one or more arguments.
• You call a method from an object and you call a static method from a class. A
method may require one or more arguments.
• Before you use many of the classes in the Java API, you should code an import
statement for the class or for the package that contains it.
• You can use the methods of a Scanner object to read data from the console, and
you can use the print and println methods of the System.out object to print data to
the console.
• You can code if statements to control the logic of a program based on the true or
false values of Boolean expressions. You can code while statements to repeat a
series of statements until a Boolean expression becomes false.
• Testing is the process of finding the errors or bugs in an application. Debugging is
the process of locating and fixing the bugs.
Chapter 2 Introduction to Java Programming

Before you do the exercises for this chapter


If you haven’t done it already, you should install and configure the JDK, the
NetBeans IDE, and the source code for this book as described in the
appendixes.

Exercise 2-1 Test the Invoice application


In this exercise, you’ll test the Invoice application that’s presented in figure
2-17. That will give you a better idea of how this program works.
1. Start the NetBeans IDE and open the project named ch02_exl_Invoice. This
project should be in this directory:
C:\murach\java\netbeans\ex_starts

2. Open the file named InvoiceApp.java. Review the code for this file and note
that NetBeans doesn’t display any errors.
3. Test this application with valid subtotal entries like 50,150,250, and 1000 so
it’s easy to see whether or not the calculations are correct.
4. Test the application with a subtotal value like 233.33. This will show that the
application doesn’t round the results to two decimal places. But in the next
chapter, you’ll learn how to do that.
5. Test the application with an invalid subtotal value like $1000. This time, the
application should crash. Study the error message that’s displayed and
determine which line of source code in the InvoiceApp class was running
when the error occurred. Then, jump to this line by clicking on the link to it.
6. Restart the application, enter a valid subtotal, and enter 20 when the program
asks you whether you want to continue. What happens and why?
7. Restart the application and enter two values separated by whitespace (like
1000 20) before pressing the Enter key. What happens and why?

Exercise 2-2 Modify the Test Score application


In this exercise, you’ll modify the Test Score application that’s presented in
figure 2-18. That will give you a chance to write some code of your own.
1. Start NetBeans and open the project named ch02_ex2_TestScore that’s in the
ex_starts directory shown in the previous exercise.
2. Test this application with valid data to see how it works. Then, test the
application with invalid data to see what will cause exceptions. Note that if
you enter a test score like 125, the program ends, even though the instructions
say that the program ends when you enter 999.
Section 1 Essential Java skills

3. Open the file named TestScoreApp.java and modify the while statement so
the program only ends when you enter 999. Then, test the program to see how
this works.
4. Modify the if statement so it displays an error message like “Invalid entry, not
counted” if the user enters a score that’s greater than 100 but isn’t 999. Then,
test this change.

Exercise 2-3 Modify the Invoice application


In this exercise, you’ll modify the Invoice application. When you’re through
with the modifications, a test run should look something like this:
f- —
Welcome to the Invoice Total Calculator

Enter subtotal: 100


Discount percent: 0.1
Discount amount: 10.0
Invoice total: 90.0

Continue? (y/n): y

Enter subtotal: 500


Discount percent: 0.25
Discount amount: 125.0
Invoice total: 375.0

Continue? (y/n): n

Number of invoices: 2
Average invoice: 232.5
Average discount: 67.5
^
1. Open the project named ch02_ex3_Invoice that’s in the ex_starts directory.
Then, open the file named InvoiceApp.java.
2. Modify the code so the application ends only when the user enters “n” or “N”.
As it is now, the application ends when the user enters anything other than “y”
or “Y”. To do this, you need to use a not operator (!) with the
equalsIgnoreCase method. This is illustrated by the third example in figure
2-14. Then, compile this class and test this change by entering 0 at the
Continue prompt.
3. Modify the code so it provides a discount of 25 percent when the subtotal is
greater than or equal to 500. Then, test this change.
4. Modify the code so it displays the number of invoices, the average invoice
amount, and the average discount amount when the user ends the program.
Then, test this change.
Chapter 2 Introduction to Java Programming

Exercise 2-4 Use the Java API documentation


This exercise steps you through the Java API documentation for the Scanner,
String, and Double classes. That will give you a better idea of how extensive the
Java API is.
1. Open a browser and display the Java API documentation as described in
figure 2-10.
2. Click the java.util package in the upper left frame and the Scanner class in the
lower left frame to display the documentation for the Scanner class. Then,
scroll through this documentation to get an idea of its scope.
3. Review the constructors for the Scanner class. The constructor that’s
presented in this chapter has just an InputStream object as its argument. When
you code that argument, remember that System.in represents the InputStream
object for the console.
4. Review the methods of the Scanner class with special attention to the next,
nextlnt, and nextDouble methods. Note that there are three next methods and
two nextlnt methods. The ones used in this chapter have no arguments. Then,
review the has methods in the Scanner class. You’ll learn how to use some of
these methods in chapter 5.
5. Go to the documentation for the String class, which is in the java.lang
package, and note that it offers a number of constructors. In this chapter,
though, you learned the shortcut for creating String objects because that’s the
best way to do that. Now, review the methods for this class with special
attention to the equals and equalsIgnoreCase methods.
6. Go to the documentation for the Double class, which is also in the java.lang
package. Then, review the static parseDouble and toString methods that you’ll
learn how to use in the next chapter.
If you find the documentation difficult to follow, rest assured that you’ll become
comfortable with it before you finish this book. Once you learn how to create
your own classes, constructors, and methods, it will make more sense.
3
How to work with data
In chapter 2, you learned how to use two of the eight primitive data types as
you declared and initialized variables and coded assignment statements that
used simple arithmetic expressions. Now, you’ll learn all of the details that
you need for working with variables and data types at a professional level.

Basic skills for working with data........................................ 80


The eight primitive data types.........................................................................80
How to declare and initialize variables.........................................................82
How to declare and initialize constants........................................................84
How to code assignment statements and arithmetic expressions................ 86
How to use the shortcut assignment operators.............................................88
How to work with the order of precedence..................................................90
How to work with casting............................................................................. 92
How to use Java classes for working with data types..... 94
How to use the NumberFormat class............................................................94
How to use the Math class............................................................................ 96
How to use the Integer and Double classes..................................................98
The formatted Invoice application......................................100
The code for the application..........................................................................100
A bug in the arithmetic.................................................................................. 102
How to debug the application........................................................................102
How to use the BigDecimal class.......................................104
The constructors and methods.......................................................................104
How to use BigDecimal arithmetic...............................................................106
Perspective............................................................................108
Section 1 Essential Java skills

Basic skilis for working with data


In this topic, you’ll leam about the six primitive data types that weren’t
presented in chapter 2. Then, you’ll leam the fundamentals for working with all
of the data types.

The eight primitive data types


Figure 3-1 shows the eight primitive data types provided by Java. You can
use these eight data types to store six types of numbers, characters, and true or
false values.
In chapter 2, you learned how to use the int data type for storing integers
(whole numbers). But as this figure shows, you can also use three other data
types for integers. If a value is too big for the int type, for example, you can use
the long type. Although the use of the short and byte types is less common, you
can use them when you’re working with smaller integers and you need to save
system resources.
In chapter 2, you also learned how to use the double data type for storing
numbers with decimal places. But as this figure shows, you can also use the
float data type for those numbers. The values in both of these data types are
stored as floating-point numbers that can hold very large and very small values,
but with a limited number of significant digits. For instance, the double type
with its 16 significant digits provides for numbers like 12,345,678,901,234.56
or 12,345,678.90123456 or 12.34567890123456. Since the double type has
more significant digits than the float type, you’ll use the double type for most
floating-point numbers.
To express the value of a floating-point number, you can use scientific
notation. This lets you express very large and very small numbers in a sort of
shorthand. To use this notation, you type the letter e or E followed by a power of
10. For instance, 3.65e+9 is equal to 3.65 times 109 (or 3,650,000,000), and
3.65e-9 is equal to 3.65 times 10 9 (or .00000000365).
You can use the char type to store one character. Since Java uses the two-
byte Unicode character set, it can store practically any character from any
language around the world. As a result, you can use Java to create programs that
read and print Greek or Chinese characters. In practice, though, you’ll usually
work with the characters that are stored in the older one-byte ASCII character
set. These characters are the first 256 characters of the Unicode character set.
Last, you can use the boolean type to store a true value or a false value. This
data type is typically used to represent a condition that can be true or false.
Chapter 3 How to work with data

The eight primitive data types


Type Bytes Use
byte 1 Very short integers from -128 to 127.
short 2 Short integers from -32,768 to 32,767.
Int 4 Integers from -2,147,483,648 to 2,147,483,647.
long 8 Long integers from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807.
float 4 Single-precision, floating-point numbers from
-3.4E38 to 3.4E38 with up to 7 significant digits.
double 8 Double-precision, floating-point numbers from
-1.7E308 to 1.7E308 with up to 16 significant digits.
char 2 A single Unicode character that’s stored in two bytes.
boolean 1 A true or false value.

Description
• A bit is a binary digit that can have a value of one or zero. A byte is a group of eight
bits. As a result, the number of bits for each data type is the number of bytes multi­
plied by 8.
• Integers are whole numbers, and the first four data types above provide for integers of
various sizes.
• Floating-point numbers provide for very large and very small numbers that require
decimal positions, but with a limited number of significant digits. A single-precision
number provides for numbers with up to 7 significant digits. A double-precision
number provides for numbers with up to 16 significant digits.
• The double data type is commonly used for business programs because it provides
the precision (number of significant digits) that those programs require.
• The Unicode character set provides for over 65,000 characters with two bytes used
for each character.
• The older ASCII character set that’s used by most operating systems provides for 256
characters with one byte used for each character. In the Unicode character set, the
first 256 characters correspond to the 256 ASCII characters.
• A boolean data type holds a true or false value.

Technical notes
• To express the value of a floating-point number, you can use scientific notation like
2.382E+5, which means 2.382 times 105 (a value of 238,200), or 3.25E-8, which
means 3.25 times 10'8 (a value of .0000000325). Java will sometimes use this nota­
tion to display the value of a float or double data type.
• Because of the way floating-point numbers are stored internally, they can’t represent
the exact value of the decimal places in some numbers. This can cause a rounding
problem in some business applications. Later in this chapter, you’ll learn how to use
the BigDecimal class to solve these rounding problems.

Figure 3-1 The eight primitive data types


Section 1 Essential Java skills

How to declare and initialize variables


In chapter 2, you learned how to declare and initialize a variable. This
information is repeated in figure 3-2, but with some new information. In par­
ticular, it shows how to use separate statements to declare and initialize the
variable. It also shows how to declare and initialize some of the data types that
weren’t presented in chapter 2.
Although you usually declare and initialize a variable in one statement, it
occasionally makes sense to do it in two. For instance, you may want to declare
a variable at the start of a coding routine without giving it a starting value
because its value won’t be set until later on.
The one-statement examples in this figure show how to declare and initial­
ize various types of variables. Here, the third and fourth examples show how to
assign values to the float and long types. To do that, you need to add a letter
after the value. For a float type, you add an / o r F after the value. For a long
type, you add an L. You can also use a lowercase I, but it’s not a good coding
practice since the lowercase L can easily be mistaken for the number 1. If you
omit the letter in one of these assignments, you’ll get a compile-time error.
The fifth and sixth statements show how to assign an integer value that has
seven digits. Although these statements assign the same value, the second
statement uses underscores to separate each group of three digits. Since you
can’t use commas in numeric literals, you’ll want to use underscores whenever
that improves the readability of your code. And you can use this technique with
all types of numeric literals including double, float, and long values. However,
since this feature was introduced with version 1.7 of the JDK, you should only
use it if you’re sure your code will be run by version 1.7 or later.
The seventh example shows how you can use scientific notation as you
assign a value to a variable. Then, the eighth and ninth examples show that you
can assign a character to the char type by enclosing a character in single quotes
or by supplying the integer that corresponds to the character in the Unicode
character set. And the tenth example shows how to initialize a variable named
valid as a boolean type with a false value.
The last example shows that you can declare and initialize two or more
variables in a single statement. Although you may occasionally want to do this,
it’s usually better to declare and initialize one variable per statement. That way,
it’s easier to read your code and to modify it later on.
Chapter 3 How to work with data

How to declare and initialize a variable in two statements


Syntax
type variableName;
variableName = value;

Example
int counter; // declaration statement
counter = 1 ; // assignment statement

How to declare and initialize a variable in one statement


Syntax
type variableName = value;

Examples
int counter = 1; // initialize an int variable
double price = 14.95; // initialize a double variable
float interestRate = 8.125F; // F indicates a floating-point value
long numberOfBytes = 20000L; // L indicates a long integer
int population = 1734323; // initialize an int variable
int population = 1 7 3 4 3 2 3 ; // underscores improve readability
double distance = 3.65e+9; // scientific notation
char letter = Ά 1; // stored as a two-digit Unicode character
char letter = 65; // integer value for a Unicode character
boolean valid = false; // where false is a keyword
int x = 0, y = 0; // initialize 2 variables with 1 statement

Description
• A variable stores a value that can change as a program executes.
• Before you can use a variable, you must declare its data type and initialize it by
assigning a value to it. As default values, it’s common to initialize integer variables
to 0, floating-point variables to 0.0, and boolean variables to false.
• To declare and initialize more than one variable for a single data type in a single
statement, use commas to separate the assignments.
• To identify float values, you must type a n /o r F after the number. To identify long
values, you must type an I or L after the number.

Naming conventions
• Start variable names with a lowercase letter and capitalize the first letter in all
words after the first word.
• Try to use meaningful names that are easy to remember as you code.

Note
• The use of underscores in numeric literals was introduced in version 1.7 of the
JDK.

Figure 3-2 How to declare and initialize variables


Section 1 Essential Java skills

How to declare and initialize constants


A constant stores a value that can’t be changed as the program executes.
Most of the skills for declaring and initializing variables also apply to declaring
and initializing constants. However, you begin the declaration statement for a
constant with the final keyword. As a result, constants are sometimes called
final variables. In addition, it’s a common coding convention to use all upper­
case letters for the name of a constant and to separate the words in the name
with an underscore as shown in figure 3-3.
Chapter 3 How to work with data 85

How to declare and initialize a constant


Syntax
final type CONSTANT_NAME = value;

Examples
final int D A Y S I N N O V E M B E R = 30;
final float S A L E S T A X = .075F;
final double L I G H T Y E A R M I L E S = 5.879e+12

Description
• A constant stores a value that cannot change as a program executes.
• The skills for initializing variables also apply to constants.

Naming conventions
• Capitalize all of the letters in constants and separate words with underscores.
• Try to use meaningful names that are easy to remember.

Figure 3-3 How to declare and initialize constants


Section 1 Essential Java skills

How to code assignment statements


and arithm etic expressions
In chapter 2, you learned how to code assignment statements that used
simple arithmetic expressions to assign the value of the expression to a variable.
These expressions used the first four arithmetic operators in figure 3-4. Now,
this figure summarizes all of the Java arithmetic operators. These operators
indicate what operations are to be performed on the operands in the expression,
which can be either literals or variables.
In this figure, the first five operators work on two operands. As a result,
they’re referred to as binary operators. For example, when you use the subtrac­
tion operator (-), you subtract one operand from another.
In contrast, the last four operators work on one operand. As a result, they’re
referred to as unary operators. For example, you can code the negative sign
operator (-) in front of an operand to reverse the value of the operand. Although
you can also code the positive sign operator (+) in front of an operand, it doesn’t
change the value of the operand so it’s rarely used as a unary operator.
While the addition (+), subtraction (-), and multiplication (*) operators are
easy to understand, the division (/) and modulus (%) operators are more diffi­
cult. If you’re working with integer data types, the division operator returns an
integer value that represents the number of times the right operand will fit into
the left operand. Then, the modulus operator returns an integer value that
represents the remainder (which is the amount that’s left over after dividing the
left operand by the right operand). However, if you’re working with non-integer
data types, the division operator returns a value that uses decimal places to
indicate the result of the division, and that’s usually what you want.
When you code an increment (++) or decrement (—) operator, you can prefix
the operand by coding the operator before the variable. Then, the increment or
decrement operation is performed before the rest of the statement is executed.
Conversely, you can postfix the operand by coding the operator after the vari­
able. Then, the increment or decrement operation isn’t performed until after the
statement is executed.
Often, an entire statement does nothing more than increment a variable like
this:
counter++;
Then, both the prefix and postfix forms will yield the same result. However, if
you use the increment and decrement operators as part of a larger statement,
you’ll need to use the prefix and postfix forms of these operators to control
when the operation is performed. More about that in a moment.
Since each char type is a Unicode character that has a numeric code that
maps to an integer, you can perform some integer operations on char types. For
instance, this figure shows an example of how you can use the increment
operator to change the numeric value for a char variable from 67 to 68, which
changes the character from C to D.
Chapter 3 How to work with data

Arithmetic operators
Operator Name Description
+ Addition Adds two operands.
- Subtraction Subtracts the right operand from the left operand.
* Multiplication Multiplies the right operand and the left operand.
/ Division Divides the right operand into the left operand. If both
operands are integers, then the result is an integer.
% Modulus Returns the value that is left over after dividing the right
operand into the left operand.
++ Increment Adds 1 to the operand (x = x + 1).
-- Decrement Subtracts 1 from the operand (x = x -1).
+ Positive sign Indicates that the value is positive.
- Negative sign Changes a positive value to negative, and vice versa.

Examples of simple assignment statements


int x = 14;
int y = 8;
int resultl = x + y; // resultl = 22
int result2 = x - y; // result2 = 6
int result3 = x * y; // result3 = 112
int result4 = x / y; // result4 = 1
int result5 = x % y; // result5 = 6
int résulte = -y + x; // résulte = 6
int result7 = --y; // result7 = 7, y :
int résulte = ++x; // résulte = 15, x

double a = 8.5;
double b = 3.4;
double result9 = a + b; // result9 = 11.9
double resultlO = a - b; // resultlO = 5.1
double resultll = a * b; // resultll = 28.
double resultl2 = a / b; // resultl2 = 2.5
double resultl3 = a % b; // resultl3 = 1.7
double resultl4 = -a + b; // resultl4 = -5.
double resultl5 = --a; // resultl5 = 7.5
double resultl6 = ++b; // resultl6 = 4.4

// character arithmetic
char letterl = 'C1; // letterl = 'C' Unicode integer is 67
char letter2 = ++letterl; // letter2 = 1D 1 Unicode integer is 68

Description
• An arithmetic expression consists of operands and arithmetic operators. The first
five operators above are called binary operators because they operate on two
operands. The next four are called unary operators because they operate on just
one operand.
• An assignment statement consists of a variable, an equals sign, and an expression.
When the assignment statement is executed, the value of the expression is deter­
mined and the result is stored in the variable.
Figure 3-4 How to code assignment statements and arithmetic expressions
Section 1 Essential Java skills

How to use the shortcut assignment operators


When coding assignment statements, it’s common to code the same variable
on both sides of the equals sign. This is illustrated by the first group of state­
ments in figure 3-5. That way, you can use the current value of the variable in an
expression and update the variable by assigning the result of the expression to it.
You saw this illustrated in chapter 2.
Since it’s common to write statements like this, the Java language provides
the five shorthand assignment operators shown in this figure. Although these
operators don’t provide any new functionality, you can use them to write shorter
code.
If, for example, you need to increment or decrement a variable by a value of
1, you can use a shortcut operator. For example:
month = month + 1;
can be coded with a shortcut operator as
month += 1;
which is equivalent to
month++;
Similarly, if you want to add the value of a variable named nextNumber to a
summary field named sum, you can do it like this:
sum += nextNumber;
which is equivalent to
sum = sum + nextNumber;
The techniques that you use are mostly a matter of preference because the
statements are easy to read and maintain however you code them.
Chapter 3 How to work with data

Assignment operators
Operator Name Description
= Assignment Assigns a new value to the variable.
+= Addition Adds the operand to the starting value of the variable
and assigns the result to the variable.
-= Subtraction Subtracts the operand from the starting value of the
variable and assigns the result to the variable.
*= Multiplication Multiplies the operand by the starting value of the
variable and assigns the result to the variable.
/= Division Divides the starting value of the variable by the
operand and assigns the result to the variable. If the
operand and the value of the variable are both
integers, the result is an integer.
%= Modulus Derives the value that is left over after dividing the
right operand by the value in the variable, and then
assigns this value to the variable.

Statements that use the same variable on both sides of the equals sign
count = count + 1 ; // count Is increased by 1
count = count - 1; // count is decreased by 1
total = total + 100.0; // total is increased by 100.0
total = total - 100.0; // total is decreased by 100.0
price = price * .8; // price is multiplied by .8
sum = sum + nextNumber; // sum is increased by value ofnextNumber

Statements that use the shortcut operators to get the same results
count + = 1 ; // count is increased by 1
count -= 1; // count is decreased by 1
total += 100.0; // total is increased by 100.0
total -= 100.0; // total is decreased by 100.0
price *= .8; // price is multipled by .8
sum += nextNumber; // sum is increased by the value of nextNumber

Description
• Besides the equals sign, Java provides for the five other assignment operators
shown above. These operators provide a shorthand way to code common assign­
ment operations.

Figure 3-5 How to use the shortcut assignment operators


Section 1 Essential Java skills

How to work with the order of precedence


Figure 3-6 gives more information about coding arithmetic expressions. In
particular, it gives the order o f precedence of the arithmetic operations. This
means that all of the prefixed increment and decrement operations in an expres­
sion are done first, followed by all of the positive and negative operations, and
so on. If there are two or more operations at the same order of precedence, the
operations are done from left to right.
Because this sequence of operations doesn’t always work the way you want
it to, you may need to override the sequence by using parentheses. Then, the
expressions in the innermost sets of parentheses are done first, followed by the
next sets of parentheses, and so on. Within the parentheses, though, the opera­
tions are done left to right by the order of precedence. In general, you should
use parentheses to dictate the sequence of operations whenever there’s any
doubt about it.
The need for parentheses is illustrated by the first example in this figure.
Because parentheses aren’t used in the first expression that calculates the price,
the multiplication operation is done before the subtraction operation, which
gives an incorrect result. In contrast, because the subtraction operation is
enclosed in parentheses in the second expression, this operation is performed
before the multiplication operation, which gives a correct result.
The second example in this figure shows how parentheses can be used in a
more complicated expression. Here, three sets of parentheses are used to
calculate the current value of an investment account after a monthly investment
amount is added to it, monthly interest is calculated, and the interest is added to
it. If you have trouble following this, you can plug the initial values into the
expression and evaluate it one set of parentheses at a time:
(5000 + 100) * (1 + (.12 / 12))
(5000 + 100) * (1 + .01)
5100 * 1.01
5151
If you have trouble creating an expression like this for a difficult calcula­
tion, you can often break the expression down into a series of statements. To
illustrate, this figure shows another way to calculate the current value. Here, the
first statement adds the monthly investment amount to the current value. The
second statement calculates the monthly interest rate. The third statement
calculates the monthly interest amount. And the fourth statement adds the
interest to the current value. This not only takes away the need for parentheses,
but also makes the code easier to read and debug.
The third example in this figure shows the differences between the use of
prefixed and postfixed increment and decrement operators. With prefixed
operators, the variable is incremented or decremented before the result is
assigned. With postfixed operators, the result is assigned before the operations
are done. Because this can get confusing, it’s best to limit these operators to
simple expressions.
Chapter 3 How to work with data

The order of precedence for arithmetic operations


1. Increment and decrement
2. Positive and negative
3. Multiplication, division, and remainder
4. Addition and subtraction

Example 1: Code that calculates a discounted price


Using the default order of precedence
double discountPercent = .2; // 20% discount
double price = 100; // $100 price
price = price * 1 - discountPercent; // price = $99.8

Using parentheses that specify the order of precedence


price = price * (1 - discountPercent); //price = $80

Example 2: Code that calculates thecurrent valueof a monthly


investment
Using parentheses that specify the order of precedence
double currentValue = 5000; // current value of investment account
double monthlylnvestment = 100; // amount added each month
double yearlylnterestRate = .12; // yearly interest rate

currentValue = (currentValue + monthlylnvestment) *


(1 + (yearlyInterestRate/12) ) ;

Without using parentheses


currentValue += monthlylnvestment; // add investment
double monthlylnterestRate = yearlylnterestRate / 12;
double monthlylnterest = currentValue * monthlylnterestRate;
currentValue + = monthlylnterest; // add interest

Example 3: Prefixed and postfixed increment and decrement operators


int a = 5;
int b = 5;
int y = ++a; // a = 6, y = 6
int z = b++; // b = 6, z = 5

Description
• Unless parentheses are used, the operations in an expression take place from left to
right in the order o f precedence.
• To specify the sequence of operations, you can use parentheses. Then, the opera­
tions in the innermost sets of parentheses are done first, followed by the operations
in the next sets, and so on.
• When you use an increment or decrement operator as a prefix to a variable, the
variable is incremented or decremented and then the result is assigned. But when
you use an increment or decrement operator as a postfix to a variable, the result is
assigned and then the variable is incremented or decremented.

Figure 3-6 How to work with the order of precedence


Section 1 Essential Java skills

How to work with casting


As you develop Java programs, you’ll frequently need to convert data from
one data type to another. To do that, you use a technique called casting, which is
summarized in figure 3-7.
As you can see, Java provides for two types of casting. Implicit casts are
performed automatically and can be used to convert data with a less precise type
to a more precise type. This is called a widening conversion because the new
type is always wide enough to hold the original value. For instance, the first
statement in this figure causes an integer value to be converted to a double
value.
Java will also perform an implicit cast on the values in an arithmetic expres­
sion if some of the values have more precise data types than other values. This
is illustrated by the next three statements in this figure. Here, the variables d, i,
and j are used in an arithmetic expression. Notice that d is declared with the
double data type, while i and j are declared with the int data type. Because of
that, both i and j will be converted to double values when this expression is
evaluated.
A narrowing conversion is one that casts data from a more precise data type
to a less precise data type. With this type of conversion, the less precise data
type may not be wide enough to hold the original value. In that case, you must
use an explicit cast.
To perform an explicit cast, you code the data type in parentheses before the
variable that you want to convert. When you do this, you should realize that you
may lose some information. This is illustrated by the first example in this figure
that performs an explicit cast. Here, a double value of 93.75 is cast to an int
value of 93. An explicit cast is required in this example, however, because Java
won’t automatically cast a double value to an integer value since an integer
value is less precise.
When you use explicit casting in an arithmetic expression, the casting is
done before the arithmetic operations. This is illustrated by the last two ex­
amples of explicit casts. In the last example, two integer types are cast to double
types before the division is done so the result will have decimal places if they
are needed. Without explicit casting, the expression would return an integer
value that would then be cast to a double.
When you code an explicit cast, an exception may occur at runtime if the
JRE isn’t able to perform the cast. As a result, you should use an explicit cast
only when you’re sure that the JRE will be able to perform the cast.
Although you typically cast between numeric data types, you can also cast
between the int and char types. That’s because every char value corresponds to
an int value that identifies it in the Unicode character set. Since there’s no
possible loss of data, you can implicitly cast between these data types. However,
if you prefer, you can also code these casts explicitly.
Chapter 3 How to work with data

How implicit casting works


Casting from less precise to more precise data types
byte->short->int->long-> float-^double
Examples
double grade = 93 ; // convert int to double

double d = 95.0;
int i = 86, j = 91;
double average = (d+i+j)/3; // convert i and j to double values
// average = 90.666666...

How to code an explicit cast


Syntax
(type) expression

Examples
int grade = (int) 93.75; // convert double to int (grade = 93)

double d = 95.0;
int i = 86, j = 91;
double average = ( (int)d+i+j)/3; // convert d to int value (average = 90)

double result = (double) i / (double) j; // result has decimal places

How to cast between char and int types


char letterChar = 65; //
// convert int to char (letterChar = Ά 1)
char letterChar2 = (char) 65; //
// this works too
int letterlnt = Ά 1; //
// convert char to int (letterlnt = 65)
int letterlnt2 = (int) 'A'; //
// this works too

Description
• If you assign a less precise data type to a more precise data type, Java automatically
converts the less precise data type to the more precise data type. This can be
referred to as an implicit cast or a widening conversion.
• When you code an arithmetic expression, Java implicitly casts the less precise data
types to the most precise data type.
• To code an assignment statement that assigns a more precise data type to a less
precise data type, you must use parentheses to specify the less precise data type.
This can be referred to as an explicit cast or a narrowing conversion.
• You can also use an explicit cast in an arithmetic expression. Then, the casting is
done before the arithmetic operations.
• Since each char value has a corresponding int value, you can implicitly or explicitly
cast between these types.

Figure 3-7 How to work with casting


Section 1 Essential Java skills

How to use Java classes


for working with data types
As you learned in chapter 2, Java provides hundreds of classes that include
methods that you can use in your programs. Now, you’ll learn about four of the
classes that you’ll use often when working with data types.

How to use the NumberFormat class


When you use numeric values in a program, you often need to format them.
For example, you may want to apply a standard currency format to a double
value. To do that, you need to add a dollar sign and commas and to display just
two decimal places. Similarly, you may want to display a double value in a
standard percent format. To do that, you need to add a percent sign and move the
decimal point two digits to the right.
To do this type of formatting, Java provides the NumberFormat class, which
is summarized in figure 3-8. Since this class is part of the java.text package,
you’ll usually want to include an import statement for this class before you begin
working with it.
Once you import this class, you can call one of its static methods to return a
NumberFormat object. As you learned in chapter 2, you can call static methods
directly from a class. In other words, you code the name of the class, followed by
the dot operator, followed by the method. For instance, the first example calls the
static getCurrencylnstance method directly from the NumberFormat class.
Once you use a static method to return a NumberFormat object, you can call
non-static methods from that object. To do that, you code the name of the object,
followed by the dot operator, followed by the method. For instance, the first
example calls the non-static format method from the NumberFormat object
named currency. This returns a string that consists of a dollar sign plus the value
of the price variable with two decimal places. In this format, negative numbers
are enclosed in parentheses.
The second example shows how to format numbers with the percent format.
The main difference between the first and second examples is that you use the
getPercentlnstance method to create a NumberFormat object that has the default
percent format. Then, you can use the format method of this object to format a
number as a percent. In this format, negative numbers have a leading minus sign.
The third example shows how to format numbers with the number format,
and how to set the number of decimal places for a NumberFormat object. Here,
the format is changed from the default of three decimal places to just one decimal
place. In this format, negative numbers also have a leading minus sign.
The fourth example shows how you can use one statement to create a
NumberFormat object and use its format method. Although this example accom­
plishes the same task as the second example, it doesn’t create a variable for the
NumberFormat object that you can use later in the program. As a result, you
should only use code like this when you need to format just one number.
Chapter 3 How to work with data

The NumberFormat class


j ava.text.NumberFormat

Three static methods of the NumberFormat class


Method Returns a NumberFormat object th a t...
getCurrencylnstance() Has the default currency format ($99,999.99).
getPercentlnstance() Has the default percent format (99%).
getNumberInstance() Has the default number format (99,999.999).

Three methods of a NumberFormat object


Method Description
format(anyNumberType) Returns a String object that has the format
specified by the NumberFormat object.
setMinimumFractionDigits ( i n t ) Sets the minimum number of decimal places.
setMaximumFractionDigits ( i n t ) Sets the maximum number of decimal places.

Example 1: The currency format


double price = 11.575;
NumberFormat currency = NumberFormat.getCurrencylnstance();
String priceString = currency.format(price); // returns $11.58

Example 2: The percent format


double majority = .505;
NumberFormat percent = NumberFormat.getPercentlnstance();
String majorityString = percent.format(majority); // returns 50%

Example 3: The number format with one decimal place


double miles = 15341.253;
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1) ;
String milesString = number.format(miles); // returns 15,341.3

Example 4: Two NumberFormat methods that are coded in one statement


String majorityString = NumberFormat.getPercentlnstance().format(majority)

Description
• You can use one of the three static methods of the NumberFormat class to create a
NumberFormat object. Then, you can use the methods of that object to format one
or more numbers.
• When you use the format method, the result is automatically rounded by using a
rounding technique called half-even. This means that the number is rounded up if
the preceding digit is odd, but the extra decimal places are truncated if the preced­
ing digit is even.
• Since the NumberFormat class is in the java.text package, you’ll want to include an
import statement when you use this class.
Figure 3-8 How to use the NumberFormat class
Section 1 Essential Java skills

When you use the format method of a NumberFormat object, the numbers
are automatically rounded using a technique called half-even. This technique
rounds up if the preceding digit is odd, but rounds down if the preceding digit is
even. If, for example, the currency format is used for a value of 123.455, the
formatted result is $123.46, which is what you would expect. But if the value is
123.445, the result is $123.44. Although this is okay for many applications, it
can cause problems in others. You’ll learn more about this later in this chapter.

How to use the Math class


The Math class provides a few dozen methods for working with numeric
data types. Some of the most useful ones for business applications are presented
in figure 3-9.
The first group of examples shows how to use the round method. Here, the
first statement rounds a double type to a long type, and the second statement
rounds a float type to an int type. Note, however, that this method only rounds
to an integer value so it’s not that useful.
The second group of examples shows how to use the pow method to raise
the first argument to the power of the second argument. This method returns a
double value and accepts two double arguments. However, since Java automati­
cally converts any arguments of a less precise numeric type to a double, the pow
method accepts all of the numeric types. In this example, the first statement is
equal to 22, the second statement is equal to 23, and the third and fourth state­
ments are equal to 52.
In general, the methods of the Math class work the way you would expect.
Sometimes, though, you may need to cast numeric types to get the methods to
work the way you want them to. For example, the pow method returns a double
type. So if you want to return an int type, you need to cast the double type to an
int type as shown in the fourth pow example.
The third group of examples shows how to use the sqrt method to get the
square root of a number, and the fourth group shows how to use the max and
min methods to return the greater or lesser of two values. If you study these
examples, you shouldn’t have any trouble understanding how they work.
The fifth group of examples shows how to use the random method to
generate random numbers. Since this method returns a random double value
greater than or equal to 0.0 and less than 1.0, you can return any range of values
by multiplying the random number by another number. In this example, the first
statement returns a random double value greater than or equal to 0.0 and less
than 100.0. Then, the second statement casts this double value to a long data
type. A routine like this can be useful when you want to generate random values
for testing a program.
If you have the right mathematical background, you shouldn’t have any
trouble using these or any of the other Math methods. If you’ve taken a course
in trigonometry, for example, you should be able to understand the trigonomet­
ric methods that the Math class provides.
Chapter 3 How to work with data

The Math class


java.lang.Math

Common static methods of the Math class


Method Description
round(floatOrDouble) Returns the closest long value to a double value or the closest
int value to a float value. The result has no decimal places.
p o w (nu m b er, pow er) Returns a double value of a double argument (number) that is
raised to the power of another double argument (power).
sqrt (num ber) Returns a double value that’s the square root of the double
argument.
max(a, b) Returns the greater of two float, double, int, or long arguments.
min(a, b) Returns the lesser of two float, double, int, or long arguments.
random () Returns a random double value greater than or equal to 0.0
and less than 1.0.

Example 1: The round method


long result = Math.round(1.667); // result Is 2
int result = Math.round(1.49F); // result is 1

Example 2: The pow method


double result = Math.pow(2, 2); // result is 4.0 (2*2)
double result = Math.pow(2, 3); // result is 8.0 (2*2*2)
double result = Math.pow(5, 2); // result is 25. 0 (5 squared)
int result = (int) Math.pow(5, 2) ; // result is 25 (5 squared)

Example 3: The sqrt method


double result = Math.sqrt(20.25); // result is 4.5

Example 4: The max and min methods


int x = 67;
int y = 23;
int max = Math.max(x, y ) ; // max is 67
int min = Math.min(x, y ) ; // min is 23

Example 5: The random method


double x = Math.randomO * 100; // result is a value >= 0.0 and < 100.0
long result = (long) x; // converts the result from double to long

Description
• You can use the static methods of the Math class to perform common arithmetic
operations. This figure summarizes the methods that are the most useful for busi­
ness applications.
• When a method requires one or more arguments, you code them between the
parentheses, separating multiple arguments with commas.
• In some cases, you need to cast the result to the data type that you want.

Figure 3-9 How to use the Math class


Section 1 Essential Java skills

How to use the Integer and Double classes


Figure 3-10 shows how to use a few of the constructors and static methods
that are provided by the Integer and Double classes. Since these classes can be
used to create objects that wrap around the primitive types, they are sometimes
referred to as wrapper classes. Wrapper classes also exist for the other six
primitive data types.
The first group of statements in this figure shows how to create Integer and
Double objects that can store int and double data types. This is useful when you
want to provide an int or double data type as an argument to a method, but the
method requires that the argument be an object, not a data type. You’ll see how
this works in a later chapter. Once you create an Integer or Double object, you
can use any of the methods of these classes to work with the data it contains.
Note, however, that these classes also provide static methods that you can
use without creating objects. For instance, the second group of statements in
this figure shows how to use the static toString method to convert a primitive
type to a string. Here, the first statement converts the int variable named counter
to a string and returns the value to a string variable named counterString. The
second statement converts the double variable named price to a string and
returns that value to the string variable named priceString.
Similarly, the third group of statements shows how to use the static parse
methods to convert strings to primitive types. Here, the first statement uses the
parselnt method of the Integer class to convert a string to an int data type. The
second statement uses the parseDouble method of the Double class to convert a
string to a double data type. Once these statements have been executed, you can
use the quantity and price variables in arithmetic expressions.
But what happens if the string contains a non-numeric value like “ten” that
can’t be parsed to an int or double type? In that case, the parselnt or
parseDouble method will cause a runtime error known as an exception. Using
Java terminology, you can say that the method will throw an exception. In
chapter 5, you’ll learn how to catch the exceptions that are thrown by these
methods.
Chapter 3 How to work with data

Constructors for the Integer and Double classes


Constructor Description
Integer ( I n t ) Creates an Integer object from an int data type.
Double (d o u b le ) Creates a Double object from a double data type.

Two static methods of the Integer class


Method Description
parselnt (s trin g N a m e ) Attempts to convert the String object that’s supplied as an
argument to an int type. If successful, it returns the int
value. If unsuccessful, it throws an exception.
toString (intN am e) Converts the int value that’s supplied as an argument to a
String object and returns that String object.

Two static methods of the Double class


Method Description
parseDouble (s trin g N a m e ) Attempts to convert the String object that’s supplied as an
argument to a double type. If successful, it returns the
double value. If unsuccessful, it throws an exception.
toString (doubleN am e) Converts the double value that’s supplied as an argument
to a String object and returns that String object.

How to create Integer and Double objects


Integer quantitylntegerObject = new Integer(quantity);
Double priceDoubleObject = new Double(price);

How to use static methods to convert primitive types to String objects


String counterString = Integer.toString(counter);
String priceString = Double.toString(price);

How to use static methods to convert String objects to primitive types


int quantity = Integer.parselnt(quantityString);
double price = Double.parseDouble(priceString);

Description
• The Integer and Double classes are known as wrapper classes since they can be
used to construct Integer and Double objects that contain (wrap around) int and
double values. This can be useful when you need to pass an int or double value to a
method that only accepts objects, not primitive data types.
• The Integer and Double classes also provide static methods that you can use for
converting values from these data types to strings and vice versa.
• If the parselnt and parseDouble methods can’t successfully parse the string, they
will cause an error to occur. In Java terminology, this is known as throwing an
exception. You’ll leam how to handle or catch exceptions in chapter 5.
• Every primitive type has a wrapper class that works like the Integer and Double
classes.

Figure 3-10 How to use the Integer and Double classes


100 Section 1 Essential Java skills

The formatted Invoice application


To illustrate some of the skills you’ve just learned, figure 3-11 shows the
console and code for an enhanced version of the Invoice application that was
presented in chapter 2. This time, the application does a few more calculations
and formats the results before displaying them. You can see the results for one
user entry in the console that’s in this figure.

The code for the application


The shaded code in this figure identifies the primary changes to the Invoice
application of the last chapter. First, two new values are calculated. Sales tax is
calculated by multiplying the total before tax by the SALES_TAX_PCT con­
stant that’s declared and initialized at the beginning of the main method. And
the invoice total is calculated by adding the sales tax to the total before tax.
Second, currency and percent objects are created by using the methods of
the NumberFormat class. Then, the format methods of these objects are used to
format the five values that have been calculated by this application. This shows
how one currency object can be used to format two or more values. The result of
each use of the format method is a string that is added to the message that
eventually gets displayed.
Although this application is now taking on a more professional look, you
should remember that it still has some shortcomings. First, it doesn’t handle the
exception that’s thrown if the user doesn’t enter a valid number at the console.
You’ll learn how to fix that problem in chapter 5. Second, because of the way
rounding works with the NumberFormat methods, the results may not always
come out the way you want them to. You’ll learn more about that next.
Chapter 3 How to work with data

The console for the formatted Invoice application


f- ------------- *
Enter subtotal: 150.50
Discount percent: 10%
Discount amount: $15.05
Total before tax: $135.45
Sales tax: $6.77
Invoice total: $142.22

Continue? (y/n):
V --------------------- A
The code for the formatted Invoice application
import java.util.Scanner;
import java.text.NumberFormat;

public class InvoiceApp {


public static void main(String[] args) {

final double S A L E S T A X P C T = .05;

Scanner sc = new Scanner(System.in);


String choice = "y";
while (choice.egualsIgnoreCase("y")) {
// get the input from the user
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();

// calculate the results


double discountPercent = 0.0;
if (subtotal >= 100)
discountPercent = .1;
else
discountPercent = 0.0;
double discountAmount = subtotal * discountPercent;
double totalBeforeTax = subtotal - discountAmount;
double salesTax = totalBeforeTax * S A L E S T A X P C T ;
double total = totalBeforeTax + salesTax;

// format and display the results


NumberFormat currency = NumberFormat.getCurrencylnstance();
NumberFormat percent = NumberFormat.getPercentlnstance();
String message =
"Discount percent: " + percent.format(discountPercent) + "\n"
+ "Discount amount: " + currency.format(discountAmount) + "\n"
+ "Total before tax: ■ + currency.format(totalBeforeTax) + "\n"
+ "Sales tax: " + currency.format(salesTax) + "\n"
+ "Invoice total: " + currency.format(total) + "\n";
System.out.println(message);

// see if the user wants to continue


System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.printlnO ;
}
}
}

Figure 3-11 The formatted Invoice application


102 Section 1 Essential Java skills

A bug in the arithmetic


The console at the top of figure 3-12 shows more output from the Invoice
application in figure 3-11. But wait! The results for a subtotal entry of 100.05
don’t add up. If the discount amount is $10.00, the total before tax should be
$90.05, but it’s $90.04. What’s going on?

How to debug the application


To analyze data problems like this, you can add debugging statements to a
program like the ones in figure 3-12. These statements display the unformatted
values of the result fields so you can see what they are before they’re formatted.
This is illustrated by the console at the bottom of this figure, which shows the
results for the same entries as the ones in the console at the top of this figure.
If you look at the unformatted results, you can easily see what’s going on.
Because of the way NumberFormat rounding works, the discount amount value
of 10.005 and the total before tax value of 90.045 aren’t rounded up. However,
the invoice total value of 94.54725 is rounded up. With this extra information,
you know that everything is working the way it’s supposed to, even though
you’re not displaying the results you want.
Although an error like this may be acceptable in some applications, it is
unacceptable in most business applications. And for those applications, you
need to provide solutions that deliver the results that you want. (Imagine getting
an invoice that didn’t add up!)
One solution is to write your own code that does the rounding so you don’t
need to use the NumberFormat class to do the rounding for you. As you go
through this book, you’ll learn how to use classes and methods that will help
you do that. However, that still doesn’t deal with the fact that some decimal
fractions can’t be accurately represented by floating-point numbers. To solve
that problem as well as other data problems, the best solution is to use the
BigDecimal class that you’ll learn about next.
Chapter 3 How to work with data 103

The console with an arithmetic bug


f- ------------- *
Enter subtotal: 100.05
Discount percent: 10%
Discount amount: $10.00
Total before tax: $90.04
Sales tax: $4.50
Invoice total: $94.55

Continue? (y/n):
V- ------------ J

Debugging statements that can be added to the code


String debugMessage = "\nUNFORMATTED RESULTS\n"
+ "Discount percent: " + discountPercent + "\n"
+ "Discount amount: " + discountAmount + "\n"
+ "Total before tax: " + totalBeforeTax + "\n"
+ "Sales tax: " + salesTax + "\n"
+ "Invoice total: " + total + "\n"
+ "\nFORMATTED RESULTS";
System.out.println(debugMessage);

The console with debugging information


y
Enter subtotal: 100.05

UNFORMATTED RESULTS
Discount percent: 0.1
Discount amount: 10.005
Total before tax: 90.045
Sales tax: 4.50225
Invoice total: 94.54725

FORMATTED RESULTS
Discount percent: 10%
Discount amount: $10.00
Total before tax: $90.04
Sales tax: $4.50
Invoice total: $94.55

Continue? (y/n):
1

Figure 3-12 How to debug the Invoice application


104 Section 1 Essential Java skills

How to use the BigDecimal class


The BigDecimal class is designed to solve two types of problems that are
associated with floating-point numbers. First, the BigDecimal class can be used
to exactly represent decimal numbers. Second, it can be used to work with
numbers that have more than 16 significant digits.

The constructors and methods


Figure 3-13 summarizes a few of the constructors that you can use with the
BigDecimal class. These constructors accept an int, double, long, or string
argument and create a BigDecimal object from it. Because floating-point
numbers are limited to 16 significant digits and because these numbers don’t
always represent decimal numbers exactly, it’s often best to create BigDecimal
objects from strings rather than doubles.
Once you create a BigDecimal object, you can use its methods to work with
the data. In this figure, for example, you can see some of the BigDecimal
methods that are most useful in business applications. Here, the add, subtract,
multiply, and divide methods let you perform those operations. The compareTo
method lets you compare the values in two BigDecimal objects. And the
toString method lets you convert the value of a BigDecimal object to a string.
This figure also includes the setScale method, which lets you set the number
of decimal places (scale) for the value in a BigDecimal object as well as the
rounding mode. For example, you can use the setScale method to return a
number that’s rounded to two decimal places like this:
salesTax = salesTax.setScale(2, RoundingMode.HALFUP);
In this example, RoundingMode.HALF_UP is a value in the RoundingMode
enumeration that’s summarized in this figure. The scale and rounding mode
arguments work the same for the divide method.
Enumerations are similar to classes, and you’ll leam more about them in
chapter 10. For now, you can code the rounding mode as HALF_UP because it
provides the type of rounding that is normal for business applications. However,
you need to import the RoundingMode enumeration at the start of the applica­
tion unless you want to qualify the rounding mode like this:
java.math.RoundingMode.HALF_UP
If you look at the API documentation for the BigDecimal class, you’ll see
that it provides several other methods that you may want to use. This class also
provides many other features that you may want to become more familiar with.
Chapter 3 How to work with data 105

The BigDecimal class


j ava.math.BigDecimal

Constructors of the BigDecimal class


Constructor Description
BigDecimal ( i n t ) Creates a new BigDecimal object with the specified int value.
BigDecimal (d o u b le ) Creates a new BigDecimal object with the specified double value.
BigDecimal(long) Creates a new BigDecimal object with the specified long value.
BigDecimal(String) Creates a new BigDecimal object with the specified String object.
Because of the limitations of floating-point numbers, it’s often
best to create BigDecimal objects from strings.

Methods of the BigDecimal class


Methods Description
a d d ( v a lu e ) Returns the value of this BigDecimal object after the specified
BigDecimal value has been added to it.
compareTo ( v a lu e ) Compares the value of the BigDecimal object with the value of
the specified BigDecimal object and returns -1 if less, 0 if equal,
and 1 if greater.
divide ( v a l u e , s c a le , Returns the value of this BigDecimal object divided by the
r o u n d in g - mode) value of the specified BigDecimal object, sets the specified
scale, and uses the specified rounding mode.
multiply ( v a lu e ) Returns the value of this BigDecimal object multiplied by the
specified BigDecimal value.
setScale ( s c a l e , Sets the scale and rounding mode for the BigDecimal object.
ro u n d in g -m o d e )
subtract ( v a lu e ) Returns the value of this BigDecimal object after the specified
BigDecimal value has been subtracted from it.
toString() Converts the BigDecimal value to a string.

The RoundingMode enumeration


j ava.math.RoundingMode

Two of the values in the RoundingMode enumeration


Values Description
HALFUP Round towards the “nearest neighbor” unless both neighbors
are equidistant, in which case round up.
HALFEVEN Round towards the “nearest neighbor” unless both neighbors
are equidistant, in which case round toward the even neighbor.

Description
• The BigDecimal class provides a way to perform accurate decimal calculations in
Java. It also provides a way to store numbers with more than 16 significant digits.

Figure 3-13 The constructors and methods for the BigDecimal class
106 Section 1 Essential Java skills

How to use BigDecimal arithm etic


Figure 3-14 shows how you can use BigDecimal arithmetic in the Invoice
application. To start, look at the console output when BigDecimal is used. As
you can see, this solves both the rounding problem and the floating-point
problem so it now works the way you want it to.
To use BigDecimal arithmetic in the Invoice application, you start by
coding an import statement that imports all of the classes and enumerations of
the java.math package. This includes both the BigDecimal class and the
RoundingMode enumeration. Then, you use the constructors and methods of the
BigDecimal class to create the BigDecimal objects, do the calculations, and
round the results when necessary.
In this figure, the code starts by constructing BigDecimal objects from the
subtotal and discountPercent variables, which are double types. To avoid
conversion problems, though, the toString method of the Double class is used to
convert the subtotal and discountPercent values to strings that are used in the
BigDecimal constructors.
Since the user may enter subtotal values that contain more than two decimal
places, the setScale method is used to round the subtotal entry after it has been
converted to a BigDecimal object. However, since the discountPercent variable
only contains two decimal places, it isn’t rounded. From this point on, all of the
numbers are stored as BigDecimal objects and all of the calculations are done
with BigDecimal methods.
In the statements that follow, only discount amount and sales tax need to be
rounded. That’s because they’re calculated using multiplication, which can
result in extra decimal places. In contrast, the other numbers (total before tax
and total) don’t need to be rounded because they’re calculated using subtraction
and addition. Once the calculations and rounding are done, you can safely use
the NumberFormat objects and methods to format the BigDecimal objects for
display.
When working with BigDecimal objects, you may sometimes need to create
one BigDecimal object from another BigDecimal object. However, you can’t
supply a BigDecimal object to the constructor of the BigDecimal class. Instead,
you need to call the toString method from the BigDecimal object to convert the
BigDecimal object to a String object. Then, you can pass that String object as
the argument of the constructor as illustrated by the last statement in this figure.
Is this a lot of work just to do simple business arithmetic? Relative to some
other languages, you would have to say that it is. In fact, it’s fair to say that this
is a weakness of Java. However, once you get the hang of working with the
BigDecimal class, you should be able to solve floating-point and rounding
problems with ease.
Chapter 3 How to work with data 107

The Invoice application output when BigDecimal arithmetic is used


------------- *
Enter subtotal: 100.05
Subtotal: $100.05
Discount percent: 10%
Discount amount: $10.01
Total before tax: $90.04
Sales tax: $4.50
Invoice total: $94.54

Continue? (y/n):
V --------------------- ό

The import statement that’s required for BigDecimal arithmetic


import java.math.*; // imports all classes and enumerations in java.math

The code for using BigDecimal arithmetic in the Invoice application


// convert subtotal and discount percent to BigDecimal
BigDecimal decimalSubtotal = new BigDecimal(Double.toString(subtotal));
decimalSubtotal = decimalSubtotal.setScale(2, RoundingMode.HALFUP);
BigDecimal decimalDiscountPercent =
new BigDecimal(Double.toString(discountPercent));

// calculate discount amount


BigDecimal discountAmount =
decimalSubtotal.multiply(decimalDiscountPercent);
discountAmount = discountAmount.setScale(2, RoundingMode.HALF_UP);

// calculate total before tax, sales tax, and total


BigDecimal totalBeforeTax = decimalSubtotal.subtract(discountAmount);
BigDecimal salesTaxPercent = new BigDecimal(SALESTAXPCT);
BigDecimal salesTax = salesTaxPercent.multiply(totalBeforeTax);
salesTax = salesTax.setScale(2, RoundingMode.HALFUP);
BigDecimal total = totalBeforeTax.add(salesTax);

How to create a BigDecimal object from another BigDecimal object


BigDecimal total2 = new BigDecimal(total.toString());

Description
• With this code, all of the result values are stored in BigDecimal objects, and all of
the results have two decimal places that have been rounded correctly when needed.
• Once the results have been calculated, you can use the NumberFormat methods to
format the values in the BigDecimal objects without any fear of rounding prob­
lems. However, the methods of the NumberFormat object limits the results to 16
significant digits.

Figure 3-14 How to use BigDecimal arithmetic


108 Section 1 Essential Java skills

Perspective
If this chapter has succeeded, you should now be able to work with
whatever primitive data types you need in your applications. You should be
able to use the NumberFormat, Math, Double, and Integer classes whenever
you need them. And you should be able to use the BigDecimal class to solve
the problems that are associated with floating-point numbers.

Summary
• Java provides eight primitive data types to store integer, floating-point, character,
and boolean values.
• Variables store data that changes as a program runs. Constants store data that
doesn’t change as a program runs. You use assignment statements to assign values
to variables.
• You can use arithmetic operators to form arithmetic expressions, and you can use
some assignment operators as a shorthand for some types of arithmetic expres­
sions.
• Java can implicitly cast a less precise data type to a more precise data type. Java
also lets you explicitly cast a more precise data type to a less precise data type.
• You can use the NumberFormat class to apply standard currency, percent, and
number formats to any of the primitive numeric types.
• You can use the static methods of the Math class to perform mathematical opera­
tions such as rounding numbers and calculating square roots.
• You can use the constructors of the Double and Integer wrapper classes to create
objects that wrap double and int values. You can also use the static methods of
these classes to convert strings to numbers and vice versa.
• You can use the constructors of the BigDecimal class to create objects that store
decimal values that aren’t limited to 16 significant digits. Then, you can use the
methods of these objects to do the calculations that your programs require.
Chapter 3 How to work with data 109

Exercise 3-1 Test the Invoice application


In this exercise, you’ll test the formatted Invoice application that’s presented in
figure 3-11.
1. Open the project named ch03_exl_InvoiceFormatted that’s in the ex_starts
directory. Then, review the code for this project.
2. Run the application and test it. As you test the application, enter the two
subtotal values that are shown in figures 3-11 and 3-12 to see how the
program works and to see what the problems are.
3. To better understand what is happening, add debugging statements like those
in figure 3-12 so the program displays two sets of data for each entry: first the
unformatted output, then the formatted output. When you add debugging
statements, you should try to do it in a way that makes them easy to remove
when you’re through debugging.
4. Test the application again with a range of entries so you clearly see what the
data problems are when you study the unformatted and formatted results.

Exercise 3-2 Modify the Test Score application


In this exercise, you’ll use some of the skills that you learned in this chapter to
modify the Test Score application.
1. Open the project named ch03_ex2_TestScore that’s in the ex_starts directory.
Then, review the code for this project and run it until you understand how it
works.
2. Use the += operator to increase the scoreCount and scoreTotal variables.
Then, test this to make sure that it works.
3. As the user enters test scores, use the methods of the Math class to keep track
of the minimum and maximum scores. When the user enters 999 to end the
program, display these scores at the end of the other output data. Now, test
these changes to make sure that they work. (This step can be challenging if
you’re new to programming, but you’ll leam a lot by doing it.)
4. Change the variable that you use to total the scores from a double to an int
data type. Then, use casting to cast the score count and score total to doubles
as you calculate the average score and save that average as a double. Now, test
that change.
5. Use the NumberFormat class to round the average score to one decimal place
before displaying it at the end of the program. Then, test this change. Note
that the rounding method that’s used doesn’t matter in a program like this.
110 Section 1 Essential Java skills

Exercise 3-3 Create a new application


In this exercise, you’ll develop an application that will give you a chance to use
the arithmetic skills you learned in this chapter. This application asks the user to
enter a file size in megabytes (MB) and a download speed in megabytes per
second. Then, it calculates how long it takes to download that file. The output
from this application should look something like this:
fc
Welcome to the Download Time Estimator

Enter file size (MB): 800


Enter download speed (MB/sec): 1

This download will take approximately 0 hours 13 minutes 20 seconds

Continue? (y/n); n_____________________________________________________

1. Start a new project named ch03_ex3_DownloadTime that contains a class


named DownloadTimeApp that has a main method.
2. Add the code that gets input from the user and displays output. To do that,
you can copy code from another similar application and modify it so it’s
appropriate for this application.
3. Add the code that calculates the hours, minutes, and seconds needed to
download the specified file size at the specified download speed. To do that,
start by calculating the download time in seconds and then rounding that
value to an integer. Then, divide the total seconds by the number of seconds in
an hour to get the number of hours, and divide the remaining seconds by the
number of seconds in a minute to get the number of minutes. Note that this
application only calculates an approximate value, so you don’t need to use
BigDecimal arithmetic.
4. Test the application to make sure it works correctly.

Exercise 3-4 Use BigDecimal arithmetic


This exercise has you modify the Test Score application so it uses BigDecimal
arithmetic.
1. Open the project named ch03_ex4_TestScore in the ex_starts directory.
2. Modify the code so it uses BigDecimal arithmetic to calculate the average test
score with the result rounded to one decimal place. Note that because the
scoreCount and scoreTotal variables are ints, you don’t need to create the
BigDecimal objects from strings.
3. Test this change with a range of values to make sure it works.
4
How to code
control statements
In chapter 2, you learned how to code simple if and while statements to control
the execution of your applications. Now, you’ll learn more about coding these
statements. You’ll learn how to code the other control statements that Java
offers. And you’ll learn how to code your own static methods, which will help
you divide your applications into manageable parts.

How to code Boolean expressions.....................................112


How to compare primitive data types............................................................112
How to compare strings................................................................................. 114
How to use the logical operators...................................................................116
How to code if/else and switch statements.......................118
How to code if/else statements................................................................... 118
How to code switch statements.................................................................. 120
An enhanced version of the Invoice application........................................... 124
How to code loops................................................................ 126
How to code while and do-while loops......................................................126
How to code for loops................................................................................ 128
The Future Value application......................................................................... 130
How to code nested loops.............................................................................. 132
How to code break and continue statements....................134
How to code break statements.................................................................... 134
How to code continue statements...............................................................136
How to code and call static methods.................................138
How to code static methods........................................................................... 138
How to call static methods............................................................................ 138
The Future Value application with a static method...................................... 140
Perspective............................................................................ 142
112 Section 1 Essential Java skills

How to code Boolean expressions


In chapter 2, you learned how to code the Boolean expressions that control
the operation of your control statements. These are expressions that evaluate to
either true or false. To start, this topic repeats some of the information that you
learned before, but in a larger context.

How to compare primitive data types


Figure 4-1 shows how to use the six relational operators to code a Boolean
expression that compares operands that are primitive data types. In a Boolean
expression, an operand can be a literal, a variable, an arithmetic expression, or a
keyword such as true or false.
The first three expressions in this figure use the equality operator (==) to
test if the two operands are equal. To use this operator, you must code two
equals signs instead of one. That’s because a single equals sign is used for
assignment statements. As a result, if you try to code a Boolean expression with
a single equals sign, your code won’t compile.
The next expression uses the inequality operator (!=) to test if a variable is
not equal to a numeric literal. The two expressions after that use the greater than
operator (>) to test if a variable is greater than a numeric literal and the less than
operator (<) to test if one variable is less than another. And the two expressions
after that use the greater than or equal operator (>=) and less than or equal
operator (<=) to compare operands.
The last two expressions in this figure illustrate that you don’t need the ==
or != operator when you use a boolean variable in an expression. That’s be­
cause, by definition, a boolean variable evaluates to a boolean value. As a result,
isValid == true
is the same as
isValid
and
!isValid
is the same as
isValid == false
Although the first and last expressions may be easier for a beginning program­
mer to understand, the second and third expressions are commonly used by
professional programmers.
When comparing numeric values, you usually compare values of the same
data type. However, if you compare different types of numeric values, Java will
automatically cast the less precise numeric type to the more precise type. For
example, if you compare an int type to a double type, the int type will be cast to
the double type before the comparison is made.
Chapter 4 How to code control statements 113

Relational operators
Operator Name Description
== Equality Returns a true value if both operands
are equal.
1= Inequality Returns a true value if the left and right
operands are not equal.
> Greater Than Returns a true value if the left operand
is greater than the right operand.
< Less Than Returns a true value if the left operand
is less than the right operand.
>= Greater Than Or Equal Returns a true value if the left operand
is greater than or equal to the right operand.
<= Less Than Or Equal Returns a true value if the left operand
is less than or equal to the right operand.

Examples of Boolean expressions


discountPercent == 2.3 // equal to a numeric literal
letter == 1y 1 // equal to a char literal
isValid == false // equal to the false value

subtotal != 0 // not equal to a numeric literal

years > 0 // greater than a numeric literal


i < months // less than a variable

subtotal >= 500 // greater than or equal to a numeric literal


quantity <= reorderPoint // less than or equal to a variable

isValid // isValid is equal to true


IisValid // isValid is equal to false

Description
• You can use the relational operators to create a Boolean expression that compares
two operands and returns a boolean value that is either true or false.
• If you compare two numeric operands that are not of the same type, Java will
convert the less precise operand to the type of the more precise operand before
doing the comparison.
• By definition, a boolean variable evaluates to a boolean value of true or false.

Figure 4-1 How to compare primitive data types


114 Section 1 Essential Java skills

How to compare strings


As you learned in chapter 2, a string is an object, not a primitive data type,
so you can’t use the relational operators to compare strings. Instead, you must
use the equals or equalsIgnoreCase method of the String class as shown by the
expressions at the start of figure 4-2.
Both of these methods require an argument that provides the String object
or literal that you want to compare with the current object. The difference
between the two is that the equals method is case-sensitive while the
equalsIgnoreCase method is not.
If you call the equals or equalsIgnoreCase method from a string that con­
tains a null, however, Java will throw an exception. To avoid that, you can use
the equality operator (==) or the inequality operator (!=) to check whether a
string contains a null before you use the equals or equalsIgnoreCase method.
This is illustrated by the last two expressions at the start of this figure.
The next block of code shows what happens when you test two strings for
equality with the == operator. Here, the code asks you to enter values for two
different strings. No matter what values you enter, though, the equals compari­
son that follows will be false. If, for example, you enter “abc” for both strings,
the equals test will be false.
That’s because all object variables are reference types, which means that
they don’t actually contain the data like primitive types do. Instead, reference
types refer to (or point to) the data, which is held in another area of internal
storage. For these types, the equality and inequality operators test to see
whether the variables refer to the same object. If they do, they’re considered
equal. But if they refer to two different objects, they’re considered unequal,
even if the objects contain the same values.
What happens if you issue this statement?
strlngl = string2;
The variable named string 1 now refers to the same data that string2 refers to. As
a result, the Boolean expression
strlngl == strlng2
will be true because both variables will refer to the same object.
This just makes the point that you shouldn’t use the equality and inequality
operators to test whether two strings have the same values because these opera­
tors don’t work that way. Since all objects are reference types, this holds true for
other types of objects too. As a result, you’ll learn other ways to test objects for
equality as you progress through this book.
Chapter 4 How to code control statements 115

Two methods of the String class


Method Description
equals(String) Compares the current String object with the
String object specified as the argument and returns
a true value if they are equal. This method makes
a case-sensitive comparison.
equalsIgnoreCase(String) Works like the equals method but is not case-sensitive.

Expressions that compare two string values


firstName.equals("Frank") // equal to a string literal
firstName.equalsIgnoreCase("Frank") // equal to a string literal
firstName.equals("") // equal to an empty string

IlastName.equals("Jones") // not equal to a string literal


!code.equalsIgnoreCase(productCode) // not equal to another string variable

firstName == null // equal to a null value


firstName 1= null // not equal to a null value

Code that tests whether two strings refer to the same object
Scanner sc = new Scanner(System.in);
System.out.print("Enter stringl: ");
String stringl = sc.nextO;
System.out.print("Enter string2: ") ;
String string2 = sc.nextO;

if (stringl == string2) // this will be false no matter what you enter


System.out.println("stringl = string2");
else
System.out.println("stringl not = string2");

Description
• To test two strings to see whether they contain the same string values, you must call
one of the methods of the String object.
• To test whether a string is null, you can use the equality operator (==) or the in­
equality operator (!=) with the null keyword.
• A string object is a reference type, not a primitive data type. That means that a string
variable doesn’t contain the data like a primitive type does. Instead, a string variable
refers to (or points to) the data, which is in another location of computer memory.
• If you use the equality or inequality operator to compare two string variables, Java
tests to see whether the two strings refer to the same String object. If they do, the
expression is true. If they don’t, it’s false.

Technical note
• Because Java stores string literals in pools to reduce duplication, the equality and
inequality tests for strings may not work as shown above when two String objects
are assigned the same literal value.

Figure 4-2 How to compare strings


116 Section 1 Essential Java skills

How to use the logical operators


Figure 4-3 shows how to use the logical operators to code a Boolean
expression that consists of two or more Boolean expressions. For example, the
first expression uses the && operator. As a result, it evaluates to true if both the
first expression and the second expression evaluate to true. Conversely, the
second expression uses the II operator. As a result, it evaluates to true if either
the first expression or the second expression evaluate to true.
When you use the && and II operators, the second expression is only
evaluated if necessary. Because of that, these operators are sometimes referred
to as the short-circuit operators. To illustrate, suppose the value of subtotal in
the first example is less than 250. Then, the first expression evaluates to false.
That means that the entire expression will return a false value. As a result, the
second expression is not evaluated. Since this is more efficient than always
evaluating both expressions, you’ll want to use these operators most of the time.
However, there may be times when you want to evaluate both expressions
regardless of the value that’s returned by the first expression. For example, there
may be times when the second expression performs an operation such as
incrementing a variable or calling a method. In that case, you can use the & and
I operators to make sure that the second expression is evaluated.
You can also use multiple logical operators in the same expression as
illustrated by the fifth example. Here, the && and II operators connect three
expressions. As a result, the entire expression is true if the first and second
expressions are true or the third expression is true.
When you code this type of expression, the expression is evaluated from left
to right based on this order of precedence: arithmetic operations first, followed
by relational operations, followed by logical operations. For logical operations,
And operations are performed before Or operations. If you need to change this
sequence or if there’s any doubt about the order of precedence, you can use
parentheses to clarify or control this evaluation sequence.
If necessary, you can use the ! operator to reverse the value of an expres­
sion. However, this can create code that’s difficult to read. As a result, you
should avoid using the ! operator whenever possible. For example, instead of
coding
!(subtotal < 100)
you can code
subtotal >= 100
Both expressions perform the same task, but the second expression is easier to
read.
Chapter 4 How to code control statements 117

Logical operators
Operator Name Description
&& And Returns a true value if both expressions are
true. This operator only evaluates the second
expression if necessary.
Or Returns a true value if either expression is
" true. This operator only evaluates the second
expression if necessary.
& And Returns a true value if both expressions are
true. This operator always evaluates both
expressions.
1 Or Returns a true value if either expression is
true. This operator always evaluates both
expressions.
1 Not Reverses the value of the expression.

Examples
subtotal >= 250 && subtotal < 500
timelnService < = 4 || timelnService >= 12

isValld == true & counter++ < years


isValld == true | counter++ < years

(subtotal >= 250 && subtotal < 500) || isValid == true

I(counter++ >= years)

Description
• You can use the logical operators to create a Boolean expression that combines two
or more Boolean expressions.
• Since the && and II operators only evaluate the second expression if necessary,
they’re sometimes referred to as short-circuit operators and are slightly more
efficient than the & and I operators.
• By default, Not operations are performed first, followed by And operations, and
then Or operations. These operations are performed after arithmetic operations and
relational operations.
• You can use parentheses to change the sequence in which the operations will be
performed or to clarify the sequence of operations.

Figure 4-3 How to use the logical operators


118 Section 1 Essential Java skills

How to code if/else


and switch statements
In chapter 2, you were introduced to the if/else statement, but this topic will
expand on that. This topic will also present the switch statement.

How to code if/else statements


Figure 4-4 reviews the use of the if/else statement (or just if statement). This
is Java’s implementation of the selection structure.
When an if statement is executed, Java begins by evaluating the Boolean
expression in the if clause. If it’s true, the statements within this clause are
executed and the rest of the if/else statement is skipped. If it’s false, Java
evaluates the first else if clause (if there is one). Then, if its Boolean expression
is true, the statements within this else if clause are executed, and the rest of the
if/else statement is skipped. Otherwise, Java evaluates the next else if clause.
This continues with any remaining else if clauses. Finally, if none of the
clauses contains a Boolean expression that evaluates to true, Java executes the
statements in the else clause (if there is one). If none of the Boolean expressions
are true and there is no else clause, Java doesn’t execute any statements.
Although the syntax indicates that the statements for an if, else if, or else
clause must be coded within braces, the braces are optional if the clause con­
tains a single statement. That’s the case in the first example in this figure. In
contrast, braces are required for the if and else if clauses in the second example.
Whenever you code a set of braces in Java, you are explicitly defining a
block of code that may contain one or more statements. Then, any variables that
are declared within those braces have block scope. In other words, they can’t be
accessed outside of that block. As a result, if you want to access a variable
outside of the block, you must declare it before the block. This is illustrated by
both the first and second examples.
When coding if statements, it’s a common practice to code one if statement
within another if statement. This is known as nesting if statements, and it’s
illustrated by the third example in this figure. When you nest if statements, it’s a
good practice to indent the nested statements and their clauses since this allows
the programmer to easily identify where each nested statement begins and ends.
In this figure, for example, Java only executes the nested statement if the
customer type is “R”. Otherwise, it executes the statements in the outer else
clause.
Another good coding practice is to code the conditions with a logical
structure and in a logical sequence. If necessary, you can also add comments to
your code so it’s easier to follow. As always, the easier your code is to read and
understand, the easier it is to test, debug, and maintain.
Chapter 4 How to code control statements 119

The syntax of the if/else statement


if (booleanExpression) {statements}
[else if (booleanExpression) {statements}] ...
[else {statements}]

Example 1: An if statement with else if and else clauses


double discountPercent = 0.0;
if (subtotal >= 100 && subtotal < 200)
discountPercent = .1;
else if (subtotal >= 200 && subtotal < 300)
discountPercent = .2;
else if (subtotal >= 300)
discountPercent = .3;
else
discountPercent = 0.05;

Example 2: An if statement that contains two blocks of code


double discountPercent = 0.0;
String shippingMethod =
if (eustomerType.equals ("R"))
{ // start block
discountPercent = .1;
shippingMethod = "UPS";
} // end block
else if (eustomerType.equals("C")
{ // start block
discountPercent = .2;
shippingMethod = "Bulk";
} // end block
else
shippingMethod = "USPS";

Example 3: Nested if statements


if (eus tomerType.equals("R "))
{
if (subtotal >= 100) // begin nested if
discountPercent = .2;
else
discountPercent =.1; // end nested if
}
else
discountPercent = .4;

Description
• If a clause in an if/else statement contains just one statement, you don’t have to
enclose the statement in braces. You can just end the clause with a semicolon.
However, this statement can’t declare a variable or it won’t compile.
• If a clause requires more than one statement, you must enclose the block of state­
ments in braces. Then, any variable that is declared within the block has block
scope so it can only be used within that block.

Figure 4-4 How to code if/else statements


120 Section 1 Essential Java skills

How to code switch statements


Figure 4-5 shows how to work with the switch statement. This is the Java
implementation of a control structure known as the case structure, which lets
you code different actions for different cases. The switch statement can some­
times be used in place of an if statement with else if clauses.
Prior to version 1.7 of Java, the switch statement could only be used with
expressions that evaluate to an integer. As a result, in early versions of Java, the
switch statement had limited use. However, with version 1.7 and later, the
switch statement can also be used with expressions that evaluate to a string.
To code a switch statement, you start by coding the switch keyword fol­
lowed by a switch expression that evaluates to one of the integer types or to a
string. After the switch expression, you can code one or more case labels that
represent the possible values of the switch expression. Then, when the switch
expression matches the value specified by the case label, the statements after the
label are executed.
You can code the case labels in any sequence, but you should be sure to
follow each label with a colon. Then, if the label contains one or more state­
ments, you can code a break statement after them to jump to the end of the
switch statement. Otherwise, the execution of the program falls through to the
next case label and executes the statements in that label. The default label is an
optional label that identifies the statements to execute if none of the case labels
are executed.
The first example shows how to code a switch statement that sets the
description for a product based on the value of an int variable named productlD.
Here, the first case label assigns a value of “Hammer” to the productDescription
variable if productlD is equal to 1. Then, the break statement exits the switch
statement. Similarly, the second case label sets the product description to “Box
of Nails” if productlD is equal to 2 and then exits the switch statement. If
productlD is equal to something other than 1 or 2, the default case label is
executed. Like the other two case labels, this one sets the value of the
productDescription variable and then exits the switch statement.
The second example works like the first example, but the switch statement
evaluates the value of a String variable named productCode. Here, the first case
label assigns a value of “Hammer” to the productDescription variable if
productCode is equal to “hmOl”. Since the switch statement is case-sensitive,
this case label is only executed if the productCode variable stores a string with
the exact same capitalization. For example, this case isn’t executed if
productCode is equal to “HM01”. Similarly, the second case label sets the
product description to “Box of Nails” if productCode is equal to “bn03”.
Chapter 4 How to code control statements

The syntax of the switch statement


switch (switchExpression)
{
case labell:
statements
break;
[case label2:
statements
break;] ...
[default:
statements
break;]
}

Example 1: A switch statement that uses an integer


switch (productID)
{
case 1:
productDescription = "Hammer";
break;
case 2:
productDescription = "Box of Nails";
break;
default:
productDescription = "Product not found";
break;
}

Example 2: A switch statement that uses a string


switch (productCode)
{
case "hmOl":
productDescription = "Hammer";
break;
case "bn03":
productDescription = "Box of Nails";
break;
default:
productDescription = "Product not found";
break;
}

Description
• Prior to version 1.7 of Java, the switch statement could only be used with an
expression that evaluated to one of these integer types: char, byte, short, or int.
• Starting with version 1.7 of Java, the switch statement can also be used with string
expressions. Then, the switch statement uses the equals method of the String object
to compare the strings. As a result, the strings in switch statements are case-
sensitive.
• The switch statement transfers control to the appropriate case label. If control isn’t
transferred to one of the case labels, the optional default label is executed.

Figure 4-5 How to code switch statements (part 1 of 2)


122 Section 1 Essential Java skills

The third example in figure 4-5 shows how to code a switch statement that
sets a day variable to “weekday” or “weekend” depending on the value of the
integer in the variable named dayOfWeek. Here, the case labels for 2, 3, 4, and
5 don’t contain any statements, so execution falls through to the case label for 6.
As a result, day is set to “weekday” for any of those values. Similarly, whenever
dayOfWeek equals 1 or 7, day is set to “weekend”.
Although a break statement is coded at the end of the last case label in this
example, you should know that it isn’t required. If you omit this break state­
ment, program execution automatically falls through to the statement that
follows the switch statement. However, it’s generally considered a good pro­
gramming practice to code a break statement at the end of the last case label.
That way, if you add a new case label after the last case label, your switch
statement still works correctly. Similarly, if you move the last case label so it
occurs earlier in the switch statement, it still works correctly.
When you code switch statements, you can nest one statement within
another. You can also nest if/else statements within switch statements and
switch statements within if/else statements. Here again, you should try to code
the statements with a logical structure that is relatively easy to understand. If
necessary, you can also add comments that clarify the logic of your code.
Chapter 4 How to code control statements 123

Example 3: A switch statement that falls through case labels


switch (dayOfWeek)
{
case 2:
case 3:
case 4:
case 5:
case 6:
day = "weekday";
break;
case 1:
case 7 :
day = "weekend";
break;
}

Description
• If a case label doesn’t contain a break statement, code execution will fall through to
the next label. Otherwise, the break statement ends the switch statement.
• The case labels can be coded in any sequence.

Figure 4-5 How to code switch statements (part 2 of 2)


124 Section 1 Essential Java skills

An enhanced version of the Invoice application


To give you a better idea of how if/else statements can be used, figure 4-6
presents another enhanced version of the Invoice application. This time, the
console prompts the user for two entries: customer type and subtotal.
In this application, if the user enters “R” or “C” for the customer type, the
discount percent changes depending on the value of the subtotal. If, for ex­
ample, the customer type is “R” and the subtotal is greater than or equal to 250,
the discount percent is .2. Or, if the customer type is “C” and the subtotal is less
than 250, the discount percent is .2.
Here, you can see that the conditions are coded in a logical order. For
instance, the expressions in the nested if statement for customer type “R” go
from a subtotal that’s less than 100, to a subtotal that’s greater than or equal to
100, to a subtotal that’s greater than or equal to 250. That covers all of the
possible subtotals from the smallest to the largest. Although you could code
these conditions in other sequences, this sequence makes it easy to tell that all
possibilities have been covered.
Chapter 4 How to code control statements 125

The console
(?- ----------- «
Enter customer type (r/c): r
Enter subtotal: 100
Discount percent: 10%
Discount amount: $10.00
Total: $90.00

Continue? (y/n):
V ------------------ à
The code
import java.text.NumberFormat;
import java.util.Scanner;

public class InvoiceApp


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";

while (Ichoice.equalsIgnoreCase("n"))
{
// get the input from the user
System.out.print("Enter customer type (r/c): ");
String customerType = sc.nextO;
System.out.print("Enter subtotal: ");
double subtotal = sc.nextDouble();

// get the discount percent


double discountPercent = 0.0;
if (customerType.equalsIgnoreCase("R"))
{
if (subtotal < 100)
discountPercent = 0;
else if (subtotal >= 100 && subtotal < 250)
discountPercent = .1;
else if (subtotal >= 250)
discountPercent = .2;
}
else if (customerType.equalsIgnoreCase("C"))
{
if (subtotal < 250)
discountPercent = .2;
else
discountPercent = .3;
}
else
discountPercent = .1;

// the code to calculate, format, and display results goes here

// the code to see if the user wants to continue goes here

Figure 4-6 The enhanced Invoice application


126 Section 1 Essential Java skills

How to code loops


In chapter 2, you learned how to code while statements and while loops.
Now, you’ll review the coding for those loops and leam how to code two other
Java statements that implement the iteration structure.

How to code while and do-while loops


Figure 4-7 shows how to use the while statement to code a while loop. Then,
it shows how to code a do-while loop. The difference between these types of
loops is that the Boolean expression is evaluated at the beginning of a while
loop and at the end of a do-while loop. As a result, the statements in a while
loop are executed zero or more times while the statements in a do-while loop
are always executed at least once.
When coding while and do-while loops, it’s common to use a counter
variable to execute the statements in the loop a certain number of times. The
first loop in this figure, for example, uses an int counter variable named i that’s
initialized to 1. Then, the last statement in the loop increments the counter
variable with each iteration of the loop. As a result, the first statement in this
loop will be executed as long as the counter variable is less than or equal to 36.
As I’ve mentioned earlier, it is a common coding practice to name counter
variables with single letters like i, j, and k.
Most of the time, you can use either of these two types of loops to accom­
plish the same task. For instance, the first example in this figure uses a while
loop to calculate the future value of a series of monthly payments at a specified
interest rate, and the second example uses a do-while loop to perform the same
calculation.
When you code loops, it’s important to remember that the code within a
loop has block scope. As a result, any variables that are declared within the loop
can’t be used outside of the loop. That’s why the variables that are needed
outside of the loops in this figure have been declared outside of the loop. That
way, you can use these variables after the loop has finished executing.
It’s also important to avoid infinite loops. If, for example, you forget to code
a statement that increments the counter variable, the loop will never end. Then,
in NetBeans, you can stop the loop by clicking on the Stop button that’s dis­
played in the Output window.
Chapter 4 How to code control statements 127

The syntax of the while loop


while (booleanExpression)
{
statements
}
A while loop that calculates a future value
int i = 1;
int months = 36;
while (i <= months)
{
futureValue = (futureValue + monthlyPayment) *
(1 + monthlylnterestRate);
i++;
}

The syntax of the do-while loop


do
{
statements
}
while (booleanExpression);

A do-while loop that calculates a future value


int i = 1;
int months = 36;
do
{
futureValue = (futureValue + monthlyPayment) *
(1 + monthlylnterestRate) ;
i++;
}
while (i <= months);

Description
• In a while loop, the condition is tested before the loop is executed. In a do-while
loop, the condition is tested after the loop is executed.
• A while or do-while loop executes the block of statements within the loop as long
as its Boolean expression is true.
• If a loop requires more than one statement, you must enclose the statements in
braces. This identifies the block of statements that are executed by the loop, and
any variables or constants that are declared in that block have block scope.
• If a loop requires just one statement, you don’t have to enclose the statement in
braces. However, that statement can’t declare a variable or it won’t compile.
• If the condition at the start of a while statement or at the end of a do-while state­
ment never becomes false, the statement never ends. Then, the program goes into
an infinite loop. In NetBeans, you can cancel an infinite loop by clicking on the
Stop button in the Output window.

Figure 4-7 How to code while and do-while loops


128 Section 1 Essential Java skills

How to code for loops


Figure 4-8 shows how to use the for statement to code for loops. This type
of loop is useful when you need to increment or decrement a counter that
determines how many times the loop is going to be executed.
To code a for loop, you start by coding the for keyword followed by three
expressions enclosed in parentheses and separated by semicolons. The first
expression is an initialization expression that gives the starting value for the
counter variable. This expression can also declare the counter variable, if
necessary. The second expression is a Boolean expression that determines when
the loop will end. And the third expression is an increment expression that
determines how the counter is incremented or decremented each time the loop is
executed.
The first example in this figure shows how to use these expressions. First,
the initialization expression declares the counter variable that’s used to deter­
mine the number of loops and assigns an initial value to it. In this example, the
counter variable is an int type named i, and it’s initialized to 0. Next, a Boolean
expression specifies that the loop will be repeated as long as the counter is less
than 5. Then, the increment expression increments the counter by 1 at the end of
each repetition of the loop.
Since the two loops in this example store the counter variable followed by a
space in a string, this code stores the numbers 0 to 4 in a string variable like
this:
0 12 3 4
Notice that you can code this loop using a single statement or a block of state­
ments. If you use more than one statement, though, you must enclose those
statements in braces.
The second example calculates the sum of 8, 6,4, and 2. Here, the sum
variable is declared before the loop so it will be available outside of the loop.
Within the parentheses of the for loop, the initialization expression initializes
the counter variable to 8, the Boolean expression indicates that the loop will end
when the counter variable is no longer greater than zero, and the increment
expression uses an assignment operator to subtract 2 from the counter variable
with each repetition of the loop. Within the loop, the value of the counter
variable is added to the value that’s already stored in the sum variable. As a
result, the final value for the sum variable is 20.
The third example shows how to code a loop that calculates the future value
for a series of monthly payments. Here, the loop executes one time for each
month. If you compare this example with the examples in the previous figure,
you can see how a for loop improves upon a while or do-while loop when a
counter variable is required.
Chapter 4 How to code control statements 129

The syntax of the for loop


for (initializationExpression; booleanExpression; incrementExpression)
{
statements
}

Example 1: A for loop that stores the numbers 0 through 4 in a string


With a single statement
String numbers = "";
for (int i = 0; i < 5; i++)
numbers += i + " ";

With a block of statements


String numbers = "";
for (int i = 0; i < 5; i++)
{
numbers += i;
numbers += " ";
}

Example 2: A for loop that adds the numbers 8,6,4, and 2


int sum = 0 ;
for (int j = 8; j > 0; j -= 2)
{
sum += j;
}

Example 3: A for loop that calculates a future value


for (int i = 1; i <= months; i++)
{
futureValue = (futureValue + monthlyPayment) *
(1 + monthlylnterestRate) ;
}

Description
• A for loop is useful when you need to increment or decrement a counter that
determines how many times the loop is executed.
• Within the parentheses of a for loop, you code an initialization expression that
gives the starting value for the counter, a Boolean expression that determines when
the loop ends, and an increment expression that increments or decrements the
counter.
• The loop ends when the Boolean expression is false.
• If necessary, you can declare the counter variable before the for loop. Then, this
variable will be in scope after the loop finishes executing.

Figure 4-8 How to code for loops


130 Section 1 Essential Java skills

The Future Value application


Now that you’ve learned the statements for coding loops, figure 4-9 presents
an application that uses a for loop within a while loop. As the console for this
application shows, the user starts by entering the values for the monthly pay­
ment that will be made, the yearly interest rate, and the number of years the
payment will be made. Then, for each group of entries, the application calcu­
lates and displays the future value.
If you look at the code for this application, you can see that it uses a while
loop to determine when the program will end. Within this loop, the program
first gets the three entries from the user. Next, it converts these entries to the
same time unit, which is months. To do that, the number of years is multiplied
by 12, and the yearly interest rate is divided by 12. Besides that, the yearly
interest rate is divided by 100 so it will work correctly in the future value
calculation.
Once those variables are prepared, the program enters a for loop that
calculates the future value. When the loop finishes, the program displays the
result and asks whether the user wants to continue.
Because this application doesn’t validate the user’s entries, it will crash if
the user enters invalid data. But you’ll leam how to fix that in the next chapter.
Otherwise, this application works the way you would want it to. In this case,
rounding isn’t an issue because the result is rounded just one time after the
future value loop has finished.
Because it can be hard to tell whether an application with a loop is produc­
ing the right results, it often makes sense to add debugging statements within
the loop while you’re testing it. For instance, you could add this statement to the
Future Value application as the last statement in the loop:
System.out.println("Debug: " + i + " " + futureValue);
Then, one line will be displayed on the console each time through the loop so
you can check to make sure that the calculations for the first few months are
accurate. You will also be able to tell at a glance whether the loop was executed
the right number of times.
Chapter 4 How to code control statements

The console
f- ------
Enter monthly investment: 100
Enter yearly interest rate: 3
Enter number of years: 3
Future value: $3,771.46

Continue? (y/n): y
W- ---------- λ
The code
import java.util.Scanner;
import java.text.NumberFormat;

public class FutureValueApp


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
while (! choice.equalsIgnoreCase("n"))
{
// get the input from the user
System.out.print("Enter monthly investment: ");
double monthlylnvestment = sc.nextDouble();
System.out.print("Enter yearly interest rate: ");
double interestRate = sc.nextDouble();
System.out.print("Enter number of years: ");
int years = sc.nextlnt();

// convert yearly to monthly values and initialize future value


double monthlylnterestRate = interestRate/12/100;
int months = years * 12 ;
double futureValue = 0.0;

// use a for loop to calculate the future value


for (int i = 1; i <= months; i++)
{
futureValue =
(futureValue + monthlylnvestment) *
(1 + monthlylnterestRate);
}
// format and display the result
NumberFormat currency = NumberFormat.getCurrencylnstance();
System, out. println ("Future value: 11
+ currency.format(futureValue));
System.out.printlnO ;

// see if the user wants to continue


System.out.print("Continue? (y/n): ");
choice = sc.nextO;
System.out.printlnO ;
}
}
}

Figure 4-9 The Future Value application


132 Section 1 Essential Java skills

How to code nested loops


Like if and switch statements, you can also nest loops. In the last figure, for
example, you saw a for loop that calculates a future value nested within a while
loop that determines when the program ends. Now, figure 4-10 shows how to
nest a for loop within another for loop. Notice that as with all nested statements,
the nested for loops are indented to clearly show how they’re related.
The example in this figure shows how to use three levels of nested for loops
to display a table of future value calculations. Here, the amount of the monthly
investment is set to $100, the interest rate varies from 5.0% to 6.5%, and the
number of years varies from 2 years to 4 years. Before the nested for loops are
executed, another for loop adds the headings to the string that will hold the
table.
The outermost for loop iterates through the years (4, 3, and 2), adding one
row for each year to the table string. To do that, the code within this loop starts
by adding the year to the string that will hold the data for the row. Then, the
next for loop iterates through the four interest rates (5%, 5.5%, 6%, and 6.5%).
The code within this loop uses the innermost for loop to calculate the future
value for each interest rate. Then, the result of each calculation is appended to
the row string. When this loop is finished, the outermost loop appends the row
string to the table string and clears the row string so it can be used again in the
next iteration of the loop. After all three loops are finished, the println method
prints the table string to the console.
As you review this code, you might notice that spaces are used to align the
data in the columns. Although it would be possible to use tab characters to align
the columns, that doesn’t always work the way you want. To explicitly control
alignment, then, you should use spaces.
Chapter 4 How to code control statements 133

The console
/h- ------ Λ
Monthly Payment: 100.0

5.0% 5.5% 6.0% 6.5%


4 $5,323.58 $5,379.83 $5,436.83 $5,494.59
3 $3,891.48 $3,922.23 $3,953.28 $3,984.64
2 $2,529.09 $2,542.46 $2,555.91 $2,569.45
V- ---------- 1

Nested loops that print a table of future values


// get the currency and percent formatters
NumberFormat currency = NumberFormat.getCurrencylnstance();
NumberFormat percent = NumberFormat.getPercentlnstance() ;
percent.setMinimumFractionDlgits(1);

// set the monthly payment to 100 and display it to the user


double monthlyPayment = 100.0;
System.out.println("Monthly Payment: " + monthlyPayment);
System.out.println() ;

// declare a variable to store the table


String table = " ";

// fill the first row of the table


for (double rate = 5.0; rate < 7.0; rate += .5)
{
table += percent.format(rate/100) + ■
}
table += "\n";

// loop through each row


for (int years = 4 ; years > 1; years--)
{
// append the years variable to the start of the row
String row = years + " ";
// loop through each column
for (double rate = 5.0; rate < 7.0; rate += .5)
{
// calculate the future value for each rate
int months = years * 12;
double monthlylnterestRate = rate/12/100;
double futureValue = 0.0;
for (int i = 1; i <= months; i++)
{
futureValue =
(futureValue + monthlyPayment) *
(1 + monthlylnterestRate) ;
}
// add the calculation to the row
row += currency.format(futureValue) + " ";
}
table += row + '\nn;
row = "" ;
}
System.out.println(table) ;

Figure 4-10 How to code nested loops


134 Section 1 Essential Java skills

How to code break


and continue statements
When you code loops, you usually want them to run to completion. Occa­
sionally, though, an application may require that you jump out of a loop. To do
that, you can use the break or continue statement.

How to code break statements


Figure 4-11 shows how to use the break statement and the labeled break
statement to exit loops. If you need to exit the current loop, you can code a
break statement. If you need to exit another loop in a set of nested loops, you
can use the labeled break statement.
The first example shows how you can use the break statement to exit from
an inner loop. Here, a while loop that generates random numbers is nested
within a for loop. Notice that the Boolean expression for the while loop has
been set to true. Because of that, this loop would execute indefinitely without a
statement that explicitly jumps out of the loop. In this case, a break statement is
used to exit from the loop when the random number that’s generated is greater
than 7. Then, control is returned to the for loop, which is executed until its
Boolean expression is satisfied.
The second example shows how you can use the labeled break statement to
exit an outer loop from an inner loop. To use a labeled break statement, you
code a label for the loop that you want to exit. Then, to break out of the outer
loop, you just type the break statement followed by the name of the label. This
will transfer control to the statement that follows the outer loop.
Chapter 4 How to code control statements 135

The syntax of the break statement


break;

Example 1: A break statement that exits the inner loop


for (int i = 1; i < 4; i++)
{
System.out.println("Outer " + i);
while (true)
{
int number = (int) (Math.random() * 10);
System.out.println(" Inner " + number);
if (number > 7)
break;

}
}
The syntax of the labeled break statement
break labelName;

The structure of the labeled break statement


labelName:
loop declaration
{
statements
another loop declaration
{
statements
if (conditionalExpression)
{
statements
break labelName;
}
}
}
Example 2: A labeled break statement that exits the outer loop
outerLoop:
for (int i = 1; i < 4; i++)
{
System.out.println("Outer " + i);
while (true)
{
int number = (int) (Math.random() * 10);
System.out.printIn(" Inner " + number);
if (number > 7)
break outerLoop;-------
}
} «---------------------------------------------
Description
• To jump to the end of the current loop, you can use the break statement.
• To jump to the end of an outer loop from an inner loop, you can label the outer loop
and use the labeled break statement. To code a label, type the name of the label and
a colon before a loop.
Figure 4-11 How to code break statements
136 Section 1 Essential Java skills

How to code continue statements


Figure 4-12 shows how to use the continue statement and the labeled
continue statement. These statements work similarly to the break statements, but
they jump to the beginning of a loop instead of the end of a loop. Like the break
statements, you can use the unlabeled version of the statement to work with the
current loop, and you can use the labeled version of the statement to work with
nested loops.
The first example uses a for loop to generate 9 random numbers ranging in
value from 0 to 10. Then, if the random number is less than or equal to 7, the
continue statement jumps to the beginning of the loop. As a result, the println
method that comes after the continue statement is only executed if the random
number is greater than 7.
The second example uses nested for loops to print the prime numbers that
are less than 20. In case you’re not familiar with prime numbers, a prime
number is an integer greater than 1 that can only be divided by 1 and itself. For
example, 7 is a prime number because it can only be divided by 1 and 7. In
contrast, 9 is not a prime number because it can be divided by 3 in addition to 1
and 9.
To identify the prime numbers, the outer loop in this example iterates
through the numbers 2 through 19. Then, the inner loop iterates through the
numbers 2 to the counter in the outer loop minus 1. In other words, it looks for a
number other than 1 and the counter itself that will divide the number. To do
that, the modulus operator is used to get the remainder of the counter from the
outer loop divided by the counter from the inner loop. If the remainder equals 0,
it indicates that the number can be divided by another number and is therefore
not a prime number. In that case, the continue statement causes control of the
program to jump to the top of the outer loop, and the outer loop continues with
the next number. If the remainder doesn’t equal 0 at any point in the inner loop,
though, it indicates that the number is a prime number. Then, the last statement
in the outer loop prints the number to the console.
Chapter 4 How to code control statements 137

The syntax of the continue statement


continue;

Example 1: A continue statement that jumps to the beginning of a loop


for (int j = 1; j < 10; j++)
{
int number = (int) (Math.random() * 10);
System.out.println(number);
if (number <= 7)
continue;
System.out.println("This number is greater than 7");
}
The syntax of the labeled continue statement
continue labelName;

The structure of the labeled continue statement


labelName:
loop declaration
{
statements
another loop declaration
{
statements
if (conditionalExpression)
{
statements
continue labelName;
}
}
}
Example 2: A labeled continue statement that jumps to the beginning
of the outer loop
outerLoop: 4 -----------------------------
for (int i = 2; i < 20; i++)
{
for (int j = 2; j < i-1; j++)
{
int remainder = i % j;
if (remainder == 0)
continue outerLoop;----------
}
System.out.println(i);
}
Description
• To skip the rest of the statements in the current loop and jump to the top of the
current loop, you can use the continue statement.
• To skip the rest of the statements in the current loop and jump to the top of a
labeled loop, you can add a label to the loop and use the labeled continue state­
ment.
• To code a label, type the name of the label and a colon before a loop.

Figure 4-12 How to code continue statements


138 Section 1 Essential Java skills

How to code and call static methods


So far, you’ve learned how to code applications that consist of a single
method, the static main method that’s executed automatically when you run a
class. Now, you’ll leam how to code and call other static methods. That’s one
way to divide the code for an application into manageable parts.

How to code static methods


Figure 4-13 shows how to code a static method. To start, you code an access
modifier that indicates whether the method can be called from other classes
(public) or just the class that it’s coded in (private). Next, you code the static
keyword to identify the method as a static method.
After the static keyword, you code a return type that identifies the type of
data that the method will return. That return type can be either a primitive data
type or a class like the String class. If the method doesn’t return any data, you
code the void keyword.
After the return type, you code a method name that indicates what the
method does. A common coding convention is to use camel notation and to start
each method name with a verb followed by a noun or by an adjective and a
noun, as in calculateFutureValue.
After the method name, you code a set of parentheses. Within the parenthe­
ses, you declare the parameters that are required by the method. If a method
doesn’t require any parameters, you can code an empty set of parentheses as
shown by the first example. And if a method requires more than one parameter,
you separate them with commas as shown by the second example. Later on,
when you call the method, you pass values to these parameters.
At this point, you code a set of braces that contains the statements that the
method will execute. If the method is going to return a value, these statements
must include a return statement that identifies the variable or object to be
returned. This is illustrated by the calculateFutureValue method in this figure.
When you code the method name and parameter list of a method, you form
the signature of the method. As you might expect, each method must have a
unique signature. However, you can code two or more methods with the same
name but with different parameters. This is known as overloading a method, and
you’ll leam more about that in chapter 7.

How to call static methods


Figure 4-13 also shows how to call a public or private static method that’s
coded within the same class. This is just like calling a static method from a Java
class, but you don’t need to code the class name. Then, if the method requires
arguments, you code the arguments within parentheses, separating each argu­
ment with a comma. Otherwise, you code an empty set of parentheses.
Notice that if you pass arguments, those arguments must be in the same
order as the parameters in the method. The arguments and parameters must also
Chapter 4 How to code control statements 139

The basic syntax for coding a static method


public Iprivate static returnType methodName([parameterList])
{
statements
}
A static method with no parameters and no return type
private static void printWelcomeMessage()
{
System.out.println("Hello New User");
}
A static method with three parameters that returns a double value
public static double calculateFutureValue(double monthlylnvestment,
double monthlylnterestRate, int months)
{
double futureValue = 0.0;
for (int i = 1; i <= months; i++)
{
futureValue = (futureValue + monthlylnvestment)
* (1 + monthlylnterestRate) ;
}
return futureValue;
}

The syntax for calling a static method that’s in the same class
methodName([argumentList] )

A call statement with no arguments


printWelcomeMessage();

A call statement that passes three arguments


double futureValue = calculateFutureValue(investment, rate, months);

Description
• To allow other classes to access a method, use the public access modifier. To
prevent other classes from accessing a method, use the private modifier.
• To code a method that returns data, code a return type in the method declaration
and code a return statement in the body of the method. The return statement ends
the execution of the method and returns the specified value to the calling method.
• Within the parentheses of a method, you can code an optional parameter list that
contains one or more parameters that consist of a data type and name. These are
the values that must be passed to the method when it is called.
• The name of a method along with its parameter list form the signature of the
method, which must be unique.
• When you call a method, the arguments in the argument list must be in the same
order as the parameters in the parameter list defined by the method, and they must
have compatible data types. However, the names of the arguments and the param­
eters don’t need to be the same.

Figure 4-13 How to code and call static methods


140 Section 1 Essential Java skills

have compatible data types. That means that an argument and parameter must
have the same data type, or the parameter must have a more precise data type
than the argument so the argument can be implicitly cast to that type. To refresh
your memory on implicit casting, you can refer back to figure 3-7 in chapter 3.
In practice, the terms parameter and argument are often used interchange­
ably. In this book, however, we’ll use the term parameter to refer to the vari­
ables of a method declaration, and we’ll use the term argument to refer to the
variables that are passed to a method.

The Future Value application with a static method


To illustrate the use of static methods, figure 4-14 presents another version
of the Future Value application. This time, the application uses a static method
to calculate the future value. This method requires three arguments, and it
includes the for loop that processes those arguments. When the loop finishes, the
return statement returns the future value to the main method.
To use the static method, the main method prepares the three arguments so
they’re all in month units. Then, it calls the static method and passes the three
arguments to it. This simplifies the main method and illustrates how static
methods can be used to divide a program into manageable components.
In this case, the statement that calls the method passes arguments that have
the same variable names as the parameters of the method. Although this isn’t
necessary, it makes the code easier to follow. What is necessary, though, is that
the arguments be passed in the same sequence as the parameters and have
compatible data types.
In the next chapter, you’ll see other ways that static methods can be used.
Then, in chapter 7, you’ll see how static methods can be coded with the public
keyword so they can be accessed by other classes. For now, though, you can
code all of your static methods with the private access modifier.
Chapter 4 How to code control statements

The code
import java.util.Scanner;
import java.text.NumberFormat;

public class FutureValueApp


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice = "y";
while (! choice.equalsIgnoreCase("n"))
{
// get the input from the user
System.out.print("Enter monthly investment: ");
double monthlylnvestment = sc.nextDouble();
System.out.print("Enter yearly interest rate: ");
double interestRate = sc.nextDouble();
System.out.print("Enter number of years: ");
int years = sc.nextlnt();

// convert yearly values to monthly values


double monthlylnterestRate = interestRate/12/100;
int months = years * 12 ;

// call the future value method


double futureValue = calculateFutureValue(
monthlylnvestment, monthlylnterestRate, months);

// format and display the result


NumberFormat currency = NumberFormat.getCurrencylnstance();
System.out.println("Future value: "
+ currency.format(futureValue));
System.out.printlnO ;

// see if the user wants to continue


System.out.print("Continue? (y/n): ");
choice = sc.nextO;
System.out.printlnO ;
}
}
// a static method that requires three arguments and returns a double
private static double calculateFutureValue(double monthlylnvestment,
double monthlylnterestRate, int months)
{
double futureValue = 0.0;
for (int i = 1; i <= months; i++)
{
futureValue =
(futureValue + monthlylnvestment) *
(1 + monthlylnterestRate);
}
return futureValue;
}

Figure 4-14 The Future Value application with a static method


142 Section 1 Essential Java skills

Perspective
If this chapter has succeeded, you should now be able to use if, switch,
while, do-while, and for statements. These are the Java statements that imple­
ment the selection, case, and iteration structures, and they provide the logic of
an application. You should also be able to code and call your own static
methods, which will help you divide your programs into manageable parts.

Summary
• You can use the relational operators to create Boolean expressions that compare
primitive data types and return true or false values, and you can use the logical
operators to connect two or more Boolean expressions.
• To determine whether two strings are equal, you can call the equals and
equalsIgnoreCase methods from a String object.
• You can use if/else statements and switch statements to control the logic of an
application, and you can nest these statements whenever necessary.
• You can use while, do-while, and for loops to repeatedly execute one or more
statements until a Boolean expression evaluates to false, and you can nest these
statements whenever necessary.
• You can use break statements to jump to the end of the current loop or a labeled
loop, and you can use continue statements to jump to the start of the current loop
or a labeled loop.
• To code a static method, you code an access modifier, the static keyword, its return
type, its name, and a parameter list. Then, to return a value, you code a return
statement within the method.
• To call a static method that’s in the same class as the main method, you code the
method name followed by an argument list.
Chapter 4 How to code control statements 143

Exercise 4-1 Test the Future Value application


In this exercise, you’ll test the Future Value application that’s presented in
figure 4-9 in this chapter.
1. Open the project named ch04_exl_FutureValue that’s stored in the ex_starts
directory. Then, test it with valid data to see how it works.
2. To make sure that the results are correct, add a debugging statement within
the for loop that calculates the future value. This statement should display the
month and future value each time through the loop. Then, test the program
with simple entries like 100 for monthly investment, 12 for yearly interest
(because that’s 1 percent each month), and 1 for year. When the debugging
data is displayed, check the results manually to make sure they’re correct.

Exercise 4-2 Enhance the Invoice application


In this exercise, you’ll modify the nested if/else statements that are used to
determine the discount percent for the Invoice application in figure 4-6. Then,
you’ll code and call a static method that determines the discount percent.

Open the application and change the if/else statement


1. Open the project named ch04_ex2_Invoice that’s stored in the ex_starts
directory. Then, run the application to see how it works.
2. Change the if/else statement so customers of type “R” with a subtotal that is
greater than or equal to $250 but less than $500 get a 25% discount and those
with a subtotal of $500 or more get a 30% discount. Next, change the if/else
statement so customers of type “C” always get a 20% discount. Then, test the
application to make sure this works.
3. Add another customer type to the if/else statement so customers of type “T”
get a 40% discount for subtotals of less than $500, and a 50% discount for
subtotals of $500 or more. Then, test the application.
4. Check your code to make sure that no discount is provided for a customer
type code that isn’t “R”, “C”, or “T”. Then, fix this if necessary.
Code and call a static method that determines the discount percent
5. Code a static method named getDiscountPercent that has two parameters:
customer type and subtotal. To do that efficiently, you can move the
appropriate code from the main method of the application into the static
method and make the required modifications.
6. Add code that calls the static method from the body of the application. Then,
test to make sure that it works.
144 Section 1 Essential Java skills

Exercise 4-3 Enhance the Test Score application


In this exercise, you’ll enhance the Test Score application so it uses a while or a do-
while loop plus a for loop. After the enhancements, the console for a user’s session
should look something like this:
/r— --------- Λ
Enter the number of test scores to be entered: 5

Enter score 1: 75
Enter score 2 : 80
Enter score 3 : 75
Enter score 4 : 880
Invalid entry. not counted
Enter score 4 : 80
Enter score 5: 95

Score count : 5
Score total: 405
Average score: 81
Minimum score: 75
Maximum score: 95

Enter more test scores? (y/n): y

Enter the number of test scores to be entered: 3

Enter score 1: 85
Enter score 2 : 95
Enter score 3 : 100

Score count : 3
Score total: 280
Average score: 93.3
Minimum score: 85
Maximum score: 100

Enter more test scores? (y/n):


V— --------- J)

1. Open the project named ch04_ex3_TestScore that’s stored in the ex_starts


directory. Then, run the application to see how it works.
2. Change the while statement to a do-while statement, and test this change. Does
this work any better than the while loop?
3. Enhance the program so it uses a while or do-while loop that lets the user enter
more than one set of test scores. When you do that, be sure to move the
declarations for the variables inside the loop so these variables are initialized each
time through the loop. Test the application to make sure it works.
4. Add code at the beginning of the while or do-while loop that asks the user how
many test scores are going to be entered. Then, use this number in a for loop to get
that many test score entries from the user. When the for loop ends, the program
should display the summary data for the test scores. Test these enhancements.
5. If you didn’t already do it, make sure that the code in the for loop doesn’t count an
invalid entry. In that case, an error message should be displayed and the counter
should be decremented by one. Now, test to make sure this works.
5
How to validate input data
In the last three chapters, you learned how to code applications that get input
from a user and perform calculations based on that input. However, if the user
enters data that the application can’t handle, an exception will occur and the
application will crash.
Now, you’ll learn how to validate the input data before processing it so
problems like that won’t occur. But first, you’ll leam the basic skills for
handling exceptions caused by invalid data. These are essential skills when
you’re developing professional applications.

How to handle exceptions.................................................. 146


How exceptions w ork....................................................................................146
How to catch exceptions................................................................................148
The Future Value application with exception handling................................150
How to validate data............................................................ 152
How to prevent exceptions from being thrown............................................. 152
How to validate a single entry...................................................................... 154
How to use generic methods to validate an entry.........................................156
The FutureValue application with data validation........... 158
The console.................................................................................................... 158
The code........................................................................................................ 160
Perspective........................................................................... 164
146 Section 1 Essential Java skills

How to handle exceptions


To prevent your applications from crashing, you can write code that handles
exceptions when they occur. This is known as exception handling, and it plays an
important role in most applications.

How exceptions work


When an application can’t perform an operation, Java throws an exception. An
exception is an object that’s created from one of the classes in the Exception
hierarchy such as the ones shown in figure 5-1. Exception objects represent errors
that have occurred, and they contain information about those errors. One of the
most common causes of exceptions is invalid input data.
The Exception class that’s at the top of the exception hierarchy defines the
most general type of exception. The RuntimeException class is a subclass of the
Exception class that defines a more specific type of exception. Similarly, the
NoSuchElementException and IllegalArgumentException classes are subclasses
of the RuntimeException class that define even more specific types of exceptions.
Since the RuntimeException class represents exceptions that occur at runtime,
none of the exceptions shown in this figure are checked by the compiler. In
chapter 14, you’ll learn about another type of exception that is checked by the
compiler.
A well-coded application will catch any exceptions that are thrown and
handle them. Exception handling can be as simple as notifying users that they
must enter valid data. Or, for more serious exceptions, it may involve notifying
users that the application is being shut down, saving as much data as possible,
cleaning up resources, and exiting the application as smoothly as possible.
When you’re testing an application, it’s common to encounter exceptions that
haven’t been handled. For a console application, this will typically cause informa­
tion about the exception to be displayed at the console. This information usually
includes the name of the exception class, a brief message that describes the cause
of the exception, and a stack trace. In this figure, for example, you can see the
information that’s displayed when the user enters an invalid double value for the
Invoice application.
As you can see in this example, a stack trace is a list of the methods that were
called before the exception occurred. These methods are listed in the reverse order
from the order in which they were called. Each method includes a line number,
which can help you find the statement that caused the exception in your source
code. The stack trace in this figure, for example, indicates that line 20 of the main
method of the InvoiceApp class threw an exception when it called the nextDouble
method of the Scanner class.
One common situation where you’ll need to handle exceptions is when you
convert string data to numeric data. If, for example, the nextlnt or nextDouble
method of the Scanner class can’t convert the data the user enters to the correct
data type, an InputMismatchException is thrown. Similarly, a
NumberFormatException is thrown when a value of one data type can’t be
Chapter 5 How to validate input data 147

Some of the classes in the Exception hierarchy


Exception
RuntimeException
NoSuchElementException
InputMismatchException
IllegalArgumentException
NumberFormatException
ArithmeticException
NullPointerException

The console after an InputMismatchException has been thrown


^ Enter subtotal: $100 N
Exception in thread "main" java.uti1.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at j ava.util.Scanner.nextDouble(Scanner.java:2456)
at InvoiceApp.m a i n (InvoiceApp.java:2 0)
v Λ
Four methods that might throw an exception
Class Method Throws
Scanner nextlnt () InputMi smatchExcept ion
Scanner nextDouble () InputMi smatchExcept ion
Integer parselnt(String) NumberFormatException
Double parseDouble(String) NumberFormatException

Description
• An exception is an object that contains information about an error that has oc­
curred. When an error occurs in a method, the method throws an exception.
• If an exception is thrown when you’re testing a console application, some informa­
tion about the exception, including its name and stack trace, is displayed at the
console.
• A stack trace is a list of the methods that were called before the exception oc­
curred. The list appears in reverse order, from the last method called to the first
method called.
• All exceptions are subclasses of the Exception class. The Exception class repre­
sents the most general type of exception. Each successive layer of subclasses
represents more specific exceptions.
• The class for an exception is usually stored in the same package as the class whose
methods throw that type of exception. For instance, the InputMismatchException
class is stored in the java.util package along with the Scanner class.

Figure 5-1 How exceptions work


148 Section 1 Essential Java skills

converted to another data type. This exception can be thrown by the parseDouble
method of the Double class or the parselnt method of the Integer class.
The class for an exception is usually stored in the same package as the class
that has the methods that throw that type of exception. For instance, the
InputMismatchException is thrown by the Scanner class, so the class for this
exception is stored in the java.util package along with the Scanner class. As a
result, if your application is going to use this exception object, it should import
java.util.InputMismatchException or all of the classes in the java.util package.

How to catch exceptions


To catch and handle exceptions, you use the try statement shown in figure
5-2. First, you code a try clause that contains a block of one or more statements
that may cause an exception. Then, you code a catch clause immediately after
the try clause. This clause contains the block of statements that will be executed
if an exception is thrown by a statement in the try block. Since this block
contains the code that handles the exception, it is known as an exception handler.
The example in this figure shows how you might use a try statement in the
Invoice application. Here, the nextDouble method of the Scanner class is coded
within a try clause, and a catch clause is coded for the InputMismatchException.
Then, if the user enters a non-numeric value for the subtotal, the nextDouble
method will throw an InputMismatchException and the code in the catch block
will be executed. To catch that exception, though, the application must either
import the class for that exception, or it must qualify the name of the class with
the name of the package that contains it.
In this case, the catch block starts by calling the next method of the Scanner
object to discard the incorrectly entered value. That way, the scanner won’t try to
retrieve this value the next time the nextDouble method is called. This is neces­
sary because the nextDouble method isn’t completed if an exception occurs.
After this value is discarded, the second statement displays an error message.
And finally, the continue statement jumps to the beginning of the loop, which
causes the application to prompt the user to enter another subtotal. Of course,
this assumes that the try/catch statement is coded within a while loop like the
one shown in the next figure.
The catch block in this example will only be executed if the
InputMismatchException is thrown. Since this exception is the only exception
that’s likely to be thrown in the try block, this is the clearest way to catch this
exception. If you wanted the catch clause to catch other exceptions as well,
however, you could name an exception higher up in the Exception hierarchy. For
example, if you wanted to catch any runtime exception, you could code this
catch clause:
catch (RuntlmeException e)
And if you wanted to catch any exception, you could code this catch clause:
catch (Exception e)
You’ll leam more about how this works in chapter 14.
Chapter 5 How to validate input data 149

The syntax for the try statement


try { statements }
catch (ExceptionClass exceptionName) { statements }

Two ways to import the InputMismatchException class


import.java.util.InputMismatchException;
import.java.util.*;

A try statement that catches an InputMismatchException


double subtotal = 0.0;
try
{
System.out.print("Enter subtotal: ■) ;
subtotal = sc.nextDouble();
}
catch (InputMismatchException e)
{
sc.next(); // discard the incorrectly entered double
System.out.println("Error! Invalid number. Try again.\n");
continue; // jump to the top of the loop
}

Console output
Enter subtotal: $100
Error! Invalid number. Try again.

Enter subtotal:

Description
• In a try statement (or try/catch statement), you code any statements that may throw
an exception in a try block. Then, you can code a catch block that will handle any
exceptions that may occur in the try block.
• When an exception occurs, any remaining statements in the try block are skipped
and the statements in the catch block are executed.
• Any variables or objects that are used in both the try and catch blocks must be
declared before the try and catch blocks so both the try and catch blocks can access
them.
• If you use a catch block to catch a specific type of exception, you should also
import the package that contains that exception class.

Figure 5-2 How to catch exceptions


150 Section 1 Essential Java skills

The Future Value application


with exception handling
Figure 5-3 presents an improved version of the Future Value application that
was presented in the last chapter. This version uses a try statement that’s coded
within the while loop to catch any exceptions that might be thrown when data is
retrieved from the user.
To start, this application begins with an import statement that imports all of
the classes in the java.util package. This includes the Scanner class and the
InputMismatchException class. As a result, this application can use a Scanner
object to get user input from the console, and it can catch the
InputMismatchException object that may be thrown by the methods of the
Scanner class.
To catch exceptions, all of the statements that get numeric input are coded
within a try block. Then, if the user enters data with an invalid numeric format,
the three statements in the catch block will be executed. The first statement uses
the next method to discard the invalid entry. Then, the second statement displays
a message that indicates that the entry is not a valid number. And finally, the
continue statement causes execution to continue at the top of the while loop.
That way, the user is prompted repeatedly until valid data is entered for all three
values.
Although this technique works, it has two shortcomings. First, the user must
start entering values from the beginning each time an exception is thrown even
if some of the values were valid. Second, the application displays a generic
error message that isn’t as descriptive or helpful as it could be. Later in this
chapter, you’ll learn how to fix both of these shortcomings.
Chapter 5 How to validate input data

The code for the FutureValue application with exception handling


import java.util.*;
Import java.text.NumberFormat;

public class FutureValueExceptionApp


{
public static void main(String[] args)
{
System.out.println("Welcome to the Future Value Calculator\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
double monthlylnvestment = 0.0;
double interestRate = 0.0;
int years = 0 ;
try
{
System.out.print("Enter monthly investment: ");
monthlylnvestment = sc.nextDouble();
System.out.print("Enter yearly interest rate: ");
interestRate = sc.nextDouble();
System.out.print("Enter number of years: ");
years = sc.nextlnt();
}
catch (InputMismatchException e)
{
sc.nextO; // discard the invalid number
System.out.println("ErrorI Invalid number. Try again.\n");
continue; // jump to the top of the loop
}
double monthlylnterestRate = interestRate/12/100;
int months = years * 12 ;
double futureValue = calculateFutureValue(
monthlylnvestment, monthlylnterestRate, months);

NumberFormat currency = NumberFormat.getCurrencylnstance();


System.out.println("Future value: "
+ currency.format(futureValue) + "\n");
System.out.print("Continue? (y/n): ");
choice = sc.nextO;
System.out.println();
}
}
private static double calculateFutureValue(double monthlylnvestment,
double monthlylnterestRate, int months)
{
double futureValue = 0 ;
for (int i = 1; i <= months; i++)
futureValue = (futureValue + monthlylnvestment) *
(1 + monthlylnterestRate);
return futureValue;
}
}

Figure 5-3 The Future Value application with exception handling


152 Section 1 Essential Java skills

How to validate data


Although you can use the try statement to catch and handle an exception
caused by invalid data, it’s usually best to prevent exceptions from being thrown
whenever that’s possible. To do that, you can use a technique called data
validation. Then, when an entry is invalid, the application displays an error
message and gives the user another chance to enter valid data. This is repeated
until all the entries are valid.

How to prevent exceptions from being thrown


Figure 5-4 presents four methods of the Scanner class that you can use to
prevent exceptions from being thrown. For instance, the first example in this
figure illustrates how you can use the hasNextDouble method to check if the
user has entered a string that can be converted to a double type. To do that, the
hasNextDouble method is coded as the condition on an if statement. If this
condition is true, the nextDouble method is called to retrieve the value.
If the condition on the if statement isn’t true, it means that the user entered
an invalid double value. In that case, the nextLine method is used to discard the
entire line that the user entered. Then, an error message is displayed and the
continue statement jumps to the beginning of the loop. This assumes, of course,
that the if statement is coded within a loop like the while loop shown in figure
5-3.
When writing code like this, you might think that you could use the next
method to discard the string that the user enters. However, if the user enters two
or more strings, the next method will only discard the first string. Then, when
the continue statement jumps to the top of the loop, if the next string can be
converted to a double, the nextDouble method will read that string without
prompting the user for a new value. Since that’s not what you want, you’ll
typically use the nextLine method instead of the next method to discard all the
remaining values.
In the last chapter, you learned that if you call the equals or
equalsIgnoreCase method from a string that contains a null, Java will throw an
exception. Specifically, Java will throw a NullPointerException. To prevent this
exception from being thrown, you can use code like that shown in the second
example. To start, this code checks the value of a variable named customerType.
If it isn’t null, the code that follows calls the equals method. If it is null, no
processing is performed. Later in this book, you’ll see why this type of code is
often necessary.
Since code that checks user input without using exception handling runs
faster than code that uses exception handling, you should avoid using exception
handling to check user input whenever possible. In general, it’s considered a
good practice to use exception handling only when the situation is truly excep­
tional. For example, it’s not exceptional that a user would accidentally enter a
non-numeric value for a subtotal. As a result, you should use the methods of the
Scanner class to prevent these types of exceptions whenever possible.
Chapter 5 How to validate input data 153

Methods of the Scanner class you can use to validate data


Method Description
hasNext() Returns true if the scanner contains another token.
hasNextlnt() Returns true if the scanner contains another token that
can be converted to an int value.
hasNextDouble() Returns true if the scanner contains another token that
can be converted to a double value.
nextLine() Returns any remaining input on the current line as a
String object and advances the scanner to the next line.

Example 1: Code that prevents an InputMismatchException


double subtotal = 0.0;
System.out.print("Enter subtotal: ") ;
if (sc.hasNextDouble())
{
subtotal = sc.nextDouble();
}
else
{
sc.nextLine(); // discard the entire line
System.out.println("Error! Invalid number. Try again.\n");
continue; // jump to the top of the loop
}
Console output
j Enter subtotal: $100 |
Error! Invalid number. Try again.

Enter subtotal:
v J

Example 2: Code that prevents a NullPointerException


if (customerType != null)
{
if (eustomerType.equals("R") )
discountPercent = .4;
}

Description
• The hasXxx methods of the Scanner class let you check whether additional data is
available at the console and whether that data can be converted to a specific data
type. You can use these methods to prevent an exception from being thrown when
one of the next methods is called.
• You can use the nextLine method to retrieve and discard any additional data that
the user enters on a line that isn’t required by the application.
• When your code prevents an exception from being thrown, it runs faster than code
that catches and then handles the exception.

Figure 5-4 How to prevent exceptions from being thrown


154 Section 1 Essential Java skills

How to validate a single entry


When a user enters data in a console application, you may want to perform
several types of data validation. In particular, it’s common to perform the two
types of data validation for numeric entries that are illustrated in figure 5-5.
First, if the application requires that the user enter a number at the prompt,
you can use one of the has methods of the Scanner class to check that the string
value the user entered can be converted to the appropriate numeric data type.
Second, if the application requires that the user enter a number within a speci­
fied range, you can use if/else statements to check that the number falls within
that range. This is known as range checking.
To repeat this checking until all the entries on the form are valid, you can
use a while loop like the one shown in this figure. This loop is executed repeat­
edly as long as the value of a boolean variable named isValid is false. Then,
within the while loop, the first if/else statement checks whether the user entered
a double value. If so, the nextDouble method is used to retrieve that value, and
the isValid variable is set to true. If not, an error message is displayed.
If the value the user entered is valid, the second ilMse statement checks the
value to see if it is greater than 0 and less than 10000. If so, the data is valid and
the while loop ends. Otherwise, an appropriate error message is displayed, and
the isValid variable is set to false so the while loop will repeat.
In this code, the nextLine method is called after the first if/else statement to
discard any unnecessary or invalid entries. For example, if the user enters
100 dollars
the nextDouble method converts 100 to a double value, and the nextLine
method reads past the “dollars” string. Then, because the String object that’s
returned by the nextLine method isn’t assigned to a variable, it’s discarded.
Similarly, if the user enters an invalid double value, it’s discarded by the
nextLine method.
Since all characters in a string are valid, you don’t need to check string
variables for that type of validity. In some cases, though, you need to check
whether the characters that a string contains are acceptable to the application. If,
for example, the user is asked to enter a one-character code that should only be
R, C, or T, the application should check to make sure the user has entered one of
those characters. That’s easily done with an if statement.
Although this figure only shows how to check data that the user has entered
at a command prompt, the same principles apply to other types of applications.
In section 4, for example, you’ll see how these principles can be used to validate
entries for an application that uses a graphical user interface.
Chapter 5 How to validate input data 155

Code that gets a valid double value within a specified range


Scanner sc = new Scanner(System.in);
double subtotal = 0.0;
boolean isValid = false;
while (isValid == false)
{
// get a valid double value
System.out.print("Enter subtotal: ■) ;
if (sc.hasNextDouble() )
{
subtotal = sc.nextDouble();
isValid = true;
}
else
{
System.out.println("Error! Invalid number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line

// check the range of the double value


if (isValid == true && subtotal <= 0)
{
System.out.println("Error! Number must be greater than 0.");
isValid = false;
}
else if (isValid == true && subtotal >= 10000)
{
System.out.println("Error! Number must be less than 10000.");
isValid = false;
}
}

Description
• When a user enters data, that data usually needs to be checked to make sure that it
is valid. This is known as data validation.
• When an entry is invalid, the program needs to display an error message and give
the user another chance to enter valid data. This needs to be repeated until the entry
is valid. One way to code this type of validation routine is to use a while loop.
• Two common types of validity checking for a numeric entry are (1) to make sure
that the entry has a valid numeric format, and (2) to make sure that the entry is
within a valid range (known as range checking).

Figure 5-5 How to validate an entry


156 Section 1 Essential Java skills

How to use generic methods to validate an entry


Almost all professional applications need to validate two or more entries.
Instead of writing code that validates a specific entry then, it often makes sense
to create generic methods like the ones shown in figure 5-6. These methods
perform the same types of validation shown in the previous figure, but they
work for any double entry instead of for a specific entry.
In this figure, the getDouble method checks to be sure that the user enters a
double value. This method accepts two parameters: a Scanner object and a
String object that contains the text for the prompt. Then, this method displays
the prompt to the user and, if the user enters a valid double value, it uses the
scanner to read that value. Finally, the return statement returns the value to the
calling method.
The getDoubleWithinRange method accepts four parameters. The first two
parameters are the same as those used by the getDouble method. The second
two parameters contain doubles that identify the range of values that are ac­
cepted by the application. Within the while loop for this method, the first
statement passes the Scanner object and the prompt string to the getDouble
method to get a double value from the user. Then, the if/else statement that
follows checks if the double value returned by the getDouble method falls
within the specified range. If so, the while loop ends and the double value is
returned to the calling method. Otherwise, the getDouble method is called again
until the user enters a value within the valid range.
Note that the public keyword is used as the access modifier for both of these
methods. That way, the methods can be accessed and used by other classes.
You’ll learn more about that in chapter 7. If you’re only going to use the meth­
ods within one class, though, the access modifier can be coded as private.
Once you understand how the getDouble and getDoubleWithinRange
methods work, you can code methods for other numeric types. For example,
you can code a getlnt method that uses the hasNextlnt method to be sure that
the user enters a valid int value at the prompt. Similarly, you can code a
getlntWithinRange method to check that an int value is within a specified range.
The code at the bottom of this figure shows how to call these methods to
make sure a valid double value has been entered at the Subtotal prompt. The
first statement creates the Scanner object that’s needed by the getDouble
method. Then, the second statement calls the getDouble method to get a valid
double value for the subtotal. The third statement uses the
getDoubleWithinRange method to get a valid double value for a subtotal that is
greater than 0 and less than 10000. This shows that you can call the getDouble
method directly if you don’t need to check the range. If you need to check the
range, however, you can call the getDoubleWithinRange method, which calls
the getDouble method for you.
Chapter 5 How to validate input data 157

A method that gets a valid numeric format


public static double getDouble(Scanner sc. String prompt)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextDouble())
{
d = sc.nextDouble();
isValid = true;
}
else
{
System.out.println("Error! Invalid number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
A method that checks for a valid numeric range
public static double getDoubleWithinRange(Scanner sc. String prompt,
double min, double max)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
d = getDouble(sc, prompt); // call the getDouble method
if (d <= min)
{
System.out.println(
"ErrorI Number must be greater than " + min +
}
else if (d >= max)
{
System.out.println(
"ErrorI Number must be less than " + max + ".");
}
else
isValid = true;
}
return d;
}
Code that uses these methods to return two valid double values
Scanner sc = new Scanner(System.in);
double subtotall = getDouble(sc, "Enter subtotal: ");
double subtotal2 = getDoubleWithinRange(sc, "Enter subtotal: ", 0, 10000);

Description
• Because most applications need to check more than one type of entry for validity, it
often makes sense to create and use generic methods for data validation.

Figure 5-6 How to use generic methods to validate an entry


158 Section 1 Essential Java skills

The Future Value application


with data validation
Figure 5-3 presented a version of the Future Value application that used a
try statement to catch the most common exceptions that might be thrown. Now,
you’ll see an improved version of this application that uses generic methods to
validate the user entries. This code prevents the most common exceptions from
being thrown, and it provides more descriptive messages to the user.

The console
Figure 5-7 shows the console display when the user enters invalid data for
the improved version of the Future Value application. Here, the error messages
have been highlighted so you can see them more easily. For example, the first
error message is displayed if the user doesn’t enter a valid double value for the
monthly investment. The second error message is displayed if the user enters a
value that’s out of range for the interest rate. And the third error message is
displayed if the user doesn’t enter a valid integer value for the years.
The Data Entry section in this figure uses descriptive error messages to
identify the problems to the user, and it doesn’t require that the user re-enter
values that have already been successfully entered. In addition, it only uses the
first value the user enters on a line, which is usually what you want. All other
values are discarded.
After the user completes the Data Entry section, the Future Value applica­
tion calculates the future value and displays it along with the user’s entries in
the Formatted Results section. This makes it easy to see what valid values the
user entered, which is useful if the user has entered one or more invalid entries
in the Data Entry section.
Chapter 5 How to validate input data 159

The console for the Future Value application


Welcome to the Future Value Calculator Λ

DATA ENTRY
Enter monthly Investment: $100
Error! Invalid decimal value. Try again.
Enter monthly Investment: 100 dollars
Enter yearly Interest rate: 120
Error! Number must be less than 30.0.
Enter yearly Interest rate: 12.0
Enter number of years: one
Error! Invalid Integer value. Try again.
Enter number of years: 1

FORMATTED RESULTS
Monthly investment: $100.00
Yearly interest rate: 12.0%
Number of years : 1
Future value: $1,280.93

Continue? (y/n):

Description
• The Data Entry section gets input from the user and displays an appropriate error
message if the user enters an invalid numeric format or a number that’s outside the
valid range.
• The Formatted Results section displays the data that was entered by the user along
with the future value in a format that’s easy to read.

Figure 5-7 The console for the Future Value application with data validation
160 Section 1 Essential Java skills

The code
Figure 5-8 shows the code for this version of the Future Value application.
On page 1, you can see the code for the main method. Because this code is
similar to code you’ve already seen, you shouldn’t have any trouble understand­
ing how it works. The biggest difference is that it uses methods named
getDoubleWithinRange and getlntWithinRange to validate the data entered by
the user. In this case, the monthly investment must be a double that’s greater
than 0 and less than 1000, the yearly interest rate must be a double that’s greater
than 0 and less than 30, and the number of years must be an int that’s greater
than 0 and less than 100. Then, the application will be able to calculate the
future value for any values within these ranges.
The getDouble and getDoubleWithinRange methods shown on page 2 of
this listing are the ones presented in figure 5-6. As a result, if you have any
trouble understanding how these methods work, you may want to review that
figure. The getlnt and getlntWithinRange methods on page 3 work like the
getDouble and getDoubleWithinRange methods except that they validate an int
value instead of a double value. Note that all four of these methods, as well as
the calculateFutureValue method, are coded with the public access modifier so
they can be accessed from other classes.
As you review this code, notice how each method performs a specific task.
For example, the getDouble and getlnt methods prompt the user for an entry,
validate the entry, and return the valid entry. Similarly, the calculateFutureValue
method performs a calculation and returns the result. This is a good design
because it leads to code that’s reusable and easy to maintain. For example, you
can use the getDouble and getlnt methods with any console application that gets
double or int values from the user. Although you can copy these methods from
one application to another, you can also store them in classes that you can
access from any application. You’ll learn how to do that in chapter 7.
Chapter 5 How to validate input data

The code for the Future Value application with data validation Page 1
import java.util.*;
import j ava.text.* ;

public class FutureValueApp


{
public static void main(String[] args)
{
System.out.println("Welcome to the Future Value Calculator\n");

Scanner sc = new Scanner(System.in);


String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double monthlylnvestment = getDoubleWithinRange(sc,
"Enter monthly investment: ", 0, 1000);
double interestRate = getDoubleWithinRange(sc,
"Enter yearly interest rate: ", 0, 30);
int years = getlntWithinRange(sc,
"Enter number of years: ", 0, 100);

double monthlylnterestRate = interestRate/12/100;


int months = years * 12;
double futureValue = calculateFutureValue(
monthlylnvestment, monthlylnterestRate, months);

NumberFormat currency = NumberFormat.getCurrencylnstance();


NumberFormat percent = NumberFormat.getPercentlnstance();
percent.setMinimumFractionDigits(1);

String results =
"Monthly investment :\t"
+ currency.format(monthlylnvestment) + "\n"
+ "Yearly interest rate:\t"
+ percent.format(interestRate/100) + "\n"
+ "Number of years:\t"
+ years + 11\n"
+ "Future value:\t\t"
+ currency.format(futureValue) + "\n";

System.out.printlnO ;
System.out.println("FORMATTED RESULTS");
System.out.println(results);

System.out.print("Continue? (y/n): ");


choice = sc.next();
sc.nextLineO; // discard any other data entered on the line
System.out.printlnO ;
}
}

Figure 5-8 The code for the Future Value application with data validation (part 1 of 3)
162 Section 1 Essential Java skills

The code for the Future Value application with data validation Page 2
public static double getDoubleWithinRange(Scanner sc. String prompt,
double min, double max)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
d = getDouble(sc, prompt);
if (d <= min)
System.out.println(
"Error! Number must be greater than " + min +
else if (d >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return d;
}
public static double getDouble(Scanner sc. String prompt)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextDouble())
{
d = sc.nextDouble();
isValid = true;
}
else
{
System.out.println(
"Error! Invalid decimal value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}

Figure 5-8 The code for the Future Value application with data validation (part 2 of 3)
Chapter 5 How to validate input data 163

The code for the Future Value application with data validation Page 3
public static int getlntWithinRange(Scanner sc. String prompt,
int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getlnt(sc, prompt);
if (i <= min)
System.out.println(
"Error! Number must be greater than " + min + ".");
else if (i >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return i ;
}
public static int getlnt(Scanner sc. String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextlnt())
{
i = sc.nextlnt();
isValid = true;
}
else
{
System.out.println(
"Error! Invalid integer value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i ;
}
public static double calculateFutureValue(double monthlylnvestment,
double monthlylnterestRate, int months)
{
double futureValue = 0;
for (int i = 1; i <= months; i++)
{
futureValue =
(futureValue + monthlylnvestment) *
(1 + monthlylnterestRate);
}
return futureValue;
}
}

Figure 5-8 The code for the Future Value application with data validation (part 3 of 3)
164 Section 1 Essential Java skills

Perspective
Now that you’ve completed this chapter, you should be able to write
console applications that validate the input data that’s entered by the users and
catch any exceptions that occur. As a result, the applications should never
crash. That, of course, is the way professional applications should work.
At this point, you’ve learned a complete subset of Java, and you know how
to use some of the methods in a few of the classes in the Java API. But there’s
a lot more to Java programming than that. In particular, you need to leam how
to create your own classes that have their own methods. That’s the essence of
object-oriented programming, and that’s what you’ll leam in the next section
of this book. But first, you’ll leam how to test and debug an application.

Summary
• An exception is an object that’s created from the Exception class or one of its
subclasses. This object contains information about an error that has occurred.
• The stack trace is a list of methods that were called before an exception occurred.
• You can code a try statement to create an exception handler that will catch and
handle any exceptions that are thrown. This is known as exception handling.
• Data validation refers to the process of checking input data to make sure that it’s
valid.
• Range checking refers to the process of checking an entry to make sure that it falls
within a certain range of values.

Exercise 5-1 Add validation to the Invoice


application

In this exercise, you’ll add code to the Invoice application that validates the data
the user enters. That includes exception handling code as well as specific data
validation methods.
1. Open the project named ch05_exl_Invoice in the ex_starts directory. Then,
test the application to see how it works.
2. As you test the application, enter an invalid customer type code to see what
happens. Then, enter an invalid subtotal entry like $1000 to see what happens
when the application crashes.
Validate the customer type code
3. Modify the application so it will only accept customer type codes r and c. It
should also discard any extra entries on the customer type line. If the user
enters an invalid code, the application should display an error message and
Chapter 5 How to validate input data 165

ask the user to enter a valid code. This should be done before the user enters a
subtotal. Then, test this enhancement.
4. Code a static method named getYalidCustomerType that does the validation
of step 3. This method should include one parameter that receives a Scanner
object, and it should return a valid customer type code. The method should
get an entry from the user, check it for validity, display an error message if it’s
invalid, and discard any other user entries whether or not the entry is valid.
This method should continue getting user entries until one is valid. The
easiest way to add the code for this method is to copy the code you wrote in
step 3.
5. Modify the application so it uses this method. Then, test this enhancement.
Validate the subtotal
6. Add a try statement that catches any InputMismatchException that the
nextDouble method of the Scanner class might throw. The catch block should
display an error message and issue a continue statement to jump to the
beginning of the while loop. It should also discard the invalid entry and any
other entries on the line. For this to work, you’ll need to import the
InputMismatchException class, and you’ll need to declare the subtotal
variable before the try statement so it can be used outside that statement. Test
this enhancement.
7. Code a static method named getValidSubtotal that uses the hasDouble method
of the Scanner class to validate the subtotal entry so the
InputMismatchException won’t occur. This method should require one
parameter that receives a Scanner object, and it should return a valid subtotal.
This method should get an entry from the user, check that it’s a valid double
value, check that it’s greater than zero and less than 10000, display
appropriate error messages if it isn’t valid, and discard any other user entries
whether or not the entry is valid. This should continue until the method gets a
valid subtotal entry.
8. Modify the code within the try statement so it uses this method. Then, test this
enhancement so you can see that an InputMismatchException is no longer
caught by the catch block.
Discard any extra entries for the Continue prompt
9. Run the application again. When the Continue prompt is displayed, enter two
or more values to see what happens.
10. Modify the code so the application works right even if the user enters two or
more values when asked if he wants to continue. To do that, you need to
discard any extra entries. Then, test this enhancement.
At this point, the application should be bulletproof. It should only accept valid
entries for customer type and subtotal, and it should work even if the user
makes two or more entries for a single prompt.
166 Section 1 Essential Java skills

Exercise 5-2 Add validation to the Test Score


application

In this exercise, you’ll add data validation to a variation of the Test Score
application that you worked on in previous chapters. To do that, you’ll use
generic methods that you can copy from the Future Value application. This will
show you that generic validation methods can be used in a wide range of
applications.
1. Open the project named ch05_ex2_TestScore in the ex_starts directory. Then,
run the application to see how it works. Note that it crashes if you enter an
invalid integer for a score or if you enter “y” followed by another value at the
prompt that asks if you want to enter another score. Note also that it allows
invalid scores such as 150.
2. Open the ch05_FutureValueValidation project in the book_apps directory.
Then, copy the generic getlnt and getlntWithinRange methods from that
application and paste them into the TestScoreApp class.
3. Use the getlnt and getlntWithinRange methods to validate that each score
ranges from 1 through 100. Then, test this enhancement.
4. Add code that discards any extra entries at the prompt that asks if you want to
enter another score. Then, test the application to make sure that it is
bulletproof.
6
How to test and debug
an application
As you develop a Java application, you need to test it to make sure that it
performs as expected. Then, if you encounter any problems, you need to debug
the application to locate the cause of the problems. This chapter shows how to
do both.

Basic skills for testing and debugging............................ 168


Typical test phases........................................................................................ 168
The three types of errors............................................................................... 168
Common Java errors..................................................................................... 170
A simple way to trace code execution..........................................................172
How to use NetBeans to debug anapplication................174
How to set and remove breakpoints..............................................................174
How to step through code............................................................................. 176
How to inspect variables............................................................................... 176
How to inspect the stack trace...................................................................... 178
Perspective..........................................................................180
168 Section 1 Essential Java skills

Basic skills for testing and debugging


When you test an application, you run it to make sure that it works cor­
rectly. As you test the application, you try every possible combination of input
data and user actions to be certain that the application works in every case. In
other words, the goal of testing is to make an application fail.
When you debug an application, you fix the errors (bugs) that you discover
during testing. Each time you fix a bug, you test again to make sure that the
change that you made didn’t affect any other aspect of the application.

typical test phases


When you test an application, you typically do so in phases. Figure 6-1 lists
three common test phases.
In the first phase, you test the user interface. For a console application, that
means you should make sure that the console displays the correct text and
prompts the user for the correct data. For an application with a graphical user
interface, that means you should visually check the controls to make sure
they’re displayed properly with the correct text. Then, you should make sure
that all the keys and controls work correctly. For instance, you should test the
Tab and Enter keys as well as the operation of check boxes and drop-down lists.
In the second phase, you test the application with valid data. To start, you
can enter data that you would expect a user to enter. Then, you should enter
valid data that tests all of the limits of the application.
In the third phase, you try to make the application fail by testing every
combination of invalid data and user action that you can think of. That should
include random actions like pressing the Enter key or clicking the mouse at the
wrong time.

The three types of errors


Three types of errors can occur as you test an application. These errors are
described in figure 6-1.
Syntax errors, also called compile-time errors, prevent your application
from compiling and running. This type of error is the easiest to find and fix. If
you use an IDE like NetBeans, it automatically detects syntax errors as you type
and gives you suggestions for how to fix them.
Unfortunately, some errors can’t be detected until you run an application.
These errors are known as runtime errors, and they throw exceptions that stop
the execution of an application.
Even if an application runs without throwing exceptions, it may contain
logic errors that prevent the application from working correctly. This type of
error is often the most difficult to find and correct. For example, the Future
Value application in this figure has a logic error. Can you tell what it is?
Chapter 6 How to test and debug an application 169

The Future Value application with a logic error


f- ------------- Λ
Welcome to the Future Value Calculator

DATA ENTRY
Enter monthly Investment: 100
Enter yearly interest rate: 3
Enter number of years : 3

FORMATTED RESULTS
Monthly investment: $100.00
Yearly interest rate: 3.0%
Number of years: 3
Future value: $6,517.42

Continue? (y/n):
V ---------------------

The goal of testing


• To find all errors before the application is put into production.

The goal of debugging


• To fix all errors before the application is put into production.

Three test phases


• Check the user interface to make sure that it works correctly.
• Test the application with valid input data to make sure the results are correct.
• Test the application with invalid data or unexpected user actions. Try everything
you can think of to make the application fail.

The three types of errors that can occur


• Syntax errors violate the rules for how Java statements must be written. These
errors, also called compile-time errors, are caught by the NetBeans IDE or the Java
compiler before you run the application.
• Runtime errors don’t violate the syntax rules, but they throw exceptions that stop
the execution of the application.
• Logic errors are statements that don’t cause syntax or runtime errors, but produce
the wrong results. In the Future Value application shown above, the future value
isn’t correct, which is a logic error.

Description
• To test a Java application, you run it to make sure that it works properly no matter
what combinations of valid or invalid data you enter.
• When you debug an application, you find and fix all of the errors (bugs) that you
find when you test the application.

Figure 6-1 An introduction to testing and debugging


170 Section 1 Essential Java skills

Common Java errors


Figure 6-2 presents some of the coding errors that are commonly made as
you write a Java application. If you study this figure, you’ll have a better idea of
what to watch out for. And if you did the exercises for the first five chapters,
you’ve probably experienced some of these errors already.
The code at the top of this figure is the start of the code for the static
getDouble method of the Future Value application, but with four errors intro­
duced. The first error is that a data type has not been declared for the variable
named d. Unlike some other languages, Java requires that you declare the data
type for all variables.
The second error is a missing semicolon at the end of the statement that
declares the variable named isValid. As you know, Java requires a semicolon at
the end of every statement unless the statement contains a block of code that’s
enclosed in braces.
The third error is a missing closing parenthesis at the end of the condition
for the if statement. Remember that every opening parenthesis, brace, or quota­
tion mark must have a closing parenthesis, brace, or quotation mark.
The fourth error is that the statement that calls the nextDouble method from
the Scanner object named sc uses improper capitalization. For this statement,
“NextDouble” should be “nextDouble” since Java is case-sensitive.
This figure also describes the problem that Java has with floating-point
arithmetic. As you can see in the example near the bottom of this figure,
floating-point arithmetic can produce strange results even with simple
calculations. This is the same problem that was described at the end of chapter
3, so you should already be aware of it and know how to use the BigDecimal
class to fix it.
Chapter 6 How to test and debug an application

Code that contains errors


sc. String prompt)

d = 0.0; // no data type declared


boolean isValid = false // missing semicolon at end of statement
while (isValid == false)
{
System.out.print(prompt)
if (sc.hasNextDouble() // missing closing parenthesis
{
d = sc.NextDouble() ; // improper capitalization
isValid = true;
}
else
{
System.out.println("Error! Invalid decimal value. Try again.");
}
sc.nextLine() ;
}
return d
}
Common syntax errors
• Misspelling keywords.
• Forgetting to declare a data type for a variable.
• Forgetting an opening or closing parenthesis, bracket, brace, or comment character.
• Forgetting to code a semicolon at the end of a statement.
• Forgetting an opening or closing quotation mark.

Problems with identifiers


• Misspelling or incorrectly capitalizing an identifier.
• Using a reserved word, global property, or global method as an identifier.

Problems with values


• Not checking that a value is the right data type before processing it. For example,
you expect the user to enter a number, but he or she enters a non-numeric value
instead.
• Using one equals sign instead of two when testing numeric and Boolean values for
equality.
• Using two equals signs instead of the equals or equalsIgnoreCase method to test
two strings for equality.

A problem with floating-point arithmetic


• The double data type uses floating-point numbers that can lead to arithmetic errors.
For example, 0.2 + 0.7 is 0.8999999999999999.
• One way around this is to use the BigDecimal class as described at the end of
chapter 3.

Figure 6-2 Common Java errors


172 Section 1 Essential Java skills

A simple way to trace code execution


When you trace the execution of an application, you add statements to your
code that display messages or variable values at key points in the code. You
typically do this to help find the cause of a logic error.
If, for example, you can’t figure out why the future value that’s calculated
by the Future Value application is incorrect, you can insert println statements
into the code for the application as shown in figure 6-3. Here, the first println
statement prints a message that indicates that the calculateFutureValue method
is starting. Then, the next three println statements print the values of
monthlylnvestment, monthlylnterestRate, and months variables. Finally, the last
println statement prints the value of the counter variable and the futureValue
variable each time through the for loop. That should help you determine where
the calculation is going wrong. Then, when you find and fix the problem, you
can remove the println statements.
When you use this technique, you usually start by adding just a few println
statements to the code. Then, if that doesn’t help you solve the problem, you
can add more. This works well for simple applications, but it creates extra work
for you because you have to add statements to your code and remove them later.
In the next few figures, you’ll leam how to use NetBeans to debug an
application without having to add or remove statements. Since this is usually
easier than adding and removing statements, you’ll rarely need to use the
technique shown in this figure. However, it can be useful in some cases.
Chapter 6 How to test and debug an application 173

Code that uses println statements to trace execution


public static double calculateFutureValue(double monthlylnvestment,
double monthlylnterestRate, int months)
{
System.out.println("starting calculateFutureValue method...");
double futureValue = 0;
System.out.println("monthlylnvestment: " + monthlylnvestment);
System.out.println("monthlylnterestRate: " + monthlylnterestRate);
System.out.println("months: " + months);
for (int i = 1; i <= months; i++)
{
futureValue =
(futureValue + monthlylnvestment) *
(1 + monthlylnterestRate) ;
System.out.println("month " + i + " futureValue: " + futureValue);
}
return futureValue;
}

The data that’s printed to the console


starting calculateFutureValue method...
monthlylnvestment: 100.0
monthlylnterestRate: 0.03
months: 36
month 1 futureValue: 103.0
month 2 futureValue: 209.09
month 3 futureValue: 318.3627
month 4 futureValue: 430.913581
month 5 futureValue: 546.84098843

Description
• A simple way to trace the execution of an application is to insert println statements
at key points in the code that print messages to the console.
• The messages that are printed to the console can indicate what code is being
executed, or they can display the values of variables.
• When you see an incorrect value displayed, there is a good chance that the
application contains a logic error between the current println statement and the
previous one.

Figure 6-3 A simple way to trace code execution


174 Section 1 Essential Java skills

How to use HetBeans


to debug an application
As you test applications, you will encounter errors that are commonly
referred to as bugs. When that happens, you must find and fix those errors using
a process known as debugging. Fortunately, NetBeans includes a powerful tool
called a debugger that can help you find and fix these errors.

How to set and remove breakpoints


The first step in debugging an application is to figure out what is causing
the bug. To do that, it’s often helpful to view the values of the variables at
different points in the application’s execution. This will help you determine the
cause of the bug, which is critical to debugging the application.
The easiest way to view the variable values as an application is executing is
to set a breakpoint as shown in figure 6-4. To do that, you click on the line
number to the left of the line of code. Then, the breakpoint is marked by a red
square. Later, when you run the application with the debugger, execution will
stop just prior to the statement at the breakpoint. Then, you will be able to view
the variables that are in scope at that point in the application. You’ll leam more
about that in the next figure.
When debugging, it’s important to set the breakpoint before the line in the
application that’s causing the bug. Often, you can figure out where to set a
breakpoint by reading the runtime exception that’s displayed when your applica­
tion crashes. Sometimes, though, you will have to experiment before finding a
good location to set a breakpoint.
After you set the breakpoint, you need to run the application with the
debugger. To do that, you can use the Debug Project/Debug Main Project button
that’s available from the toolbar (just to the right of the Run Project/Run Main
Project button). If you encounter any problems, try right-clicking on the .java
file that contains the main method and selecting the Debug File command to run
the application with the debugger.
Note that once you set a breakpoint, it remains set until you remove it.
That’s true even if you close the project and exit from NetBeans. To remove a
breakpoint, you can click on its icon.
Chapter 6 How to test and debug an application 175

A code editor window with a breakpoint


Q ch06_FutureValue - NetBeans ÎDE 7.0 1 \m & m \

File Edit View Navigate Source Refactor Run Debug P rofile Team Tools W ind ow Help Q ·· Search (Ctrl+I)

Ö ÎL J [ fib ί {P ; [<defaultconfig> ' î Ta d i l · ® *


P ro jects FutureValueApp.java ss] GUUS!“
IQ
φ · 3 5 di04_Invoice
φ- ch05_FutureValueValidabon
& a s ilο e 'iid
140
É -g P ch Q6_Fu tu reV alu e
141 public static double calculaCaFutureValue (double montΏ 1yInve3trtent,
0 - (3 Source Packages 142 d o u b l e m o n t h l y l n t e r e s t R a t e , i n t m o n th s )
É - Éid ^default package > 143 0 {
jdÿ^utureValueApp.java 144 d o u b le f u tu r e V a lu e = 0;
Θ Libraries 145 f o r ( i n t i = 1 ; i <= m onths,* i+ + )
146 {
□ f u tu re V a lu e =
14S (f u tu r e V a lu e + m o n th ly ln v e s tm e n t)
149 (1 + KtonthlylnterestRace) ;
150
151 r e t u r n f u tu re V a lu e ;
152
153

; O utput

147 1 1 INS

Description
• A breakpoint causes program execution to stop before the line that contains the
breakpoint is executed.
• To set a breakpoint for a line, open the code editor for the class and click on the
line number. The breakpoint is identified by a small red square that’s placed to the
left of the line of code.
• To remove a breakpoint, click on the breakpoint icon.
• You can set and remove breakpoints either before you start debugging or while
you’re debugging. In most cases, you’ll set at least one breakpoint before you start
debugging.
• To start debugging for the main project, click the Debug Main Project button on the
toolbar. If a single project is open and it’s not set as the main project, the name of
this button is Debug Project.
• You can also start debugging by right-clicking on a project and selecting the Debug
command or by right-clicking on the file that contains the main method you want to
run and selecting the Debug File command.

Figure 6-4 How to set and remove breakpoints


176 Section 1 Essential Java skills

How to step through code


When you run an application with the debugger and it encounters a
breakpoint, execution stops just prior to the statement at the breakpoint. Once
execution stops, a green arrow marks the next statement to be executed. In
addition, NetBeans opens the Variables window shown in figure 6-5. This
window shows the values of the variables that are in scope at the current point
of execution.
NetBeans also displays the Debug toolbar while you’re debugging. You can
click the Step Into button on this toolbar repeatedly to step through an applica­
tion one statement at a time. Then, you can use the Variables window to observe
exactly how and when the variable values change as the application executes.
That can help you determine the cause of a bug.
As you step through an application, you can click the Step Over button if
you want to execute a method without stepping into it. Or, you can use the Step
Out button to step out of any method that you don’t want to step through. When
you want to continue normal execution, you can click the Continue button.
Then, the application will run until the next breakpoint is reached. Or, you can
use the Finish Debugger Session button to end the application’s execution.
These are powerful debugging features that can help you find the cause of
serious programming problems. Stepping through an application is also a good
way to understand how the code in an existing application works. If, for ex­
ample, you step through the loop in the calculateFutureValue method, you’ll get
a better idea of how that loop works.

How to inspect variables


When you set breakpoints and step through code, the Variables window
automatically displays the values of the variables that are in scope. In figure 6-5,
the execution point is in the calculateFutureValue method of the
FutureValueApp class. Here, the Variables window shows the values of the three
parameters that are passed to the method (monthlylnvestment,
monthlylnterestRate, and months) and two local variables that are declared
within the method (futureValue and i).
For numeric variables and strings, the value of the variable is shown in the
Variables window. However, when an object such as one that’s created from the
Scanner class is displayed in the Variables window, it doesn’t display the values
of its variables automatically. Instead, it displays a plus sign to the left of the
object name. Then, you can view the values for the object by clicking on that
plus sign to expand it.
In the next chapter, you’ll learn how to create objects from classes that you
define. Then, if the code within one of these objects is executing, you’ll see a
variable named this in the Variables window. This is a keyword that’s used to
refer to the current object, and you can expand it to view the values of the
variables that are defined by the object. That will make more sense when you
start to learn about object-oriented programming in the next chapter.
Chapter 6 How to test and debug an application 177

A debugging session
Q NetBeans IDE 7,0 |siks«|
F ile E d it V ie w N a v ig a te S o u rc e R e fa c to r Run D ebug P r o f ile T eam Took W in d o w H e lp j Q ," Search (Ctrl+!)

Ï J Q Is! % i *0 C1 ; l<defeultconflg> -I T ^ D' LU Ö ill


P ro je c ts I D e b u g g in g : FutureValueApp ja va ss 111 ΙΓ*ΙΓ°1
j 'main1suspended a t 'FutureValu l>
IQ □ FutureValueApp.calcula 140
□ FutureValueApp.main:27 141 p u b l i c s t a t i c d o u b le c a lc u la te F u tm r e V a lu e ( d o u b l e m o n th ly lm s
142 d o u b le m o n t h l y l n t e r e s t R a t e , I n t m o n th s)
143 P i
144 d o a b le f u tu r e V a l u e =■ 0;
Φ f o r ( i n t i = 1 ; i <= m o n th s ; i + + )
146 {
P f u tu r e V a l u e =
143 ( f u tu r e V a l u e + m o n th ly ln v e s tm e n t)
149 (1 + m o n t h l y l n t e r e s t R a t e ) ;
150 >
151 return futureValue;

Name Type

<Enter new watch> □


® Ç 1Static

<Q> monthlylnvestment do ub le P ιο ο ·°
V > monthlylnterestRate double Q0-0025
φ months

<QrfutureValue y 503.7625234609472
Q
% G 1D Ü b Ü td ❖i
O B re ak p oin ts

chQ6_FutureValue (debug) | 14 5 I 1 IN S

Some of the buttons on the Debug toolbar


Button Keyboard shortcut Description
Step Over F7 Steps through the code one statement at a
time, skipping over called methods.
Step Into F8 Steps through the code one statement at a
time, including statements in called methods.
Step Out Ctrl+F7 Finishes executing the code in the current
method and returns to the calling method.
Continue F5 Continues execution until the next breakpoint.
Finish Debugger Session Shift+F5 Ends the application’s execution.

Description
• When a breakpoint is reached, program execution is stopped before the line is executed.
• The arrow in the bar at the left side of the code editor window shows the line that will
be executed next.
• The Variables window shows the values of the variables that are in scope for the current
method. This window is displayed by default when you start a debugging session. If
you close it, you can open it again using the Wmdow->Debugging->Variables
command.
• If a variable in the Variables window refers to an object, you can view the values for
that object by clicking the plus sign to the left of the object name to expand it.
• You can use the buttons on the Debug toolbar to control the execution of an application.

Figure 6-5 How to step through code and inspect variables


178 Section 1 Essential Java skills

How to inspect the stack trace


When you’re debugging, it’s sometimes helpful to view the stack trace,
which is a list of methods in the reverse order in which they were called. By
default, NetBeans displays a stack trace in the Debugging window that’s dis­
played in the group of windows to the left of the code editor. In addition, you
can display a stack trace in the Call Stack window as shown in figure 6-6.
In the Call Stack window in this figure, you can see that code execution is
on line 147 of the calculateFutureValue method of the FutureValueApp class.
You can also see that this method was called by line 27 of the main method of
the FutureValueApp class. At this point, you may want to display line 27 of the
main method to view the code that called the calculateFutureValue method. To
do that, you can double-click on the main method in the stack trace.
In this figure, both methods are stored in the same class. However, as you’ll
learn in the next few chapters, it’s common for a method in one class to call a
method in another class. In that case, double-clicking on a method in the stack
trace displays the source code for the other class in the code editor. If you
experiment with is, you’ll find that it can help you locate the origin of a bug.
Chapter 6 How to test and debug an application 179

A debugging session with the Call Stack window displayed


Q ch06_FutureValue - NetBeans IDE 7.0 ΙΒΗγ ξ ι γ ' χ" !
File Edit View Navigate Source Refactor Run Debug P rofile Team Tools W ind ow Help IQ ^- Search {C bl+I)

; I <default config > » p> j f j ^ , «■


O Q ij : g g , i, ■·:
! P ro jects : D ebugging Q T D E E Jd
3 'main' a t line breakpoint Future») I £ 1 SB I G B I m j
IQ __ I F u tu re V a lu e A p p .ca ku la TÏÔT
I__ I FutureValueApp.main;27 141 p u b l i c s t a t i c d o u b l e c a lc u la f c e J T u tm r e V a lu e ( d o u b le m o n t h l y I n v e s t m e n t ,
142 d o u b l e m o n t h l y l n t e r e s t R a t e , i n t m o n th s )
143 <
144 d o u b le f u tu r e V a l u e = 0;
145 f o r ( i n t i = 1 ; i <= m o n t h s ; i+ + )
146 {
fu tu re V a lu e =
14S (f u tu r e V a lu e + r a o n th ly ln v e s tra e n t) *
© 149 (1 + m o n t h l y l n t e r e s t R a t e ) ;
150 }
151 return futureValue;

I I Fu tu reVa lu eA p p.ca le ula te Fu tu reV alu e:147

I I FutureValueApp .main : 27

* III

lb m ti
□ Breakpoints

ch06_FutureValue (debug) n;.· 11 147 i 1 I IMS

Description
• A stack trace is a list of the methods that have been called in the reverse order in
which they were called.
• By default, NetBeans displays a stack trace in the Debugging window that’s
included in the group of windows at the left side of the IDE.
• You can also display a stack trace in the Call Stack window, which appears in the
group of windows below the code editor. You can display this window by selecting
the Window->Debugging-> Call Stack command.
• To jump to a line of code in the code editor that’s displayed in the stack trace,
double-click on that line in the stack trace.

Figure 6-6 How to inspect the stack trace


180 Section 1 Essential Java skills

Perspective
Before you put an application into production, you should test and debug it
thoroughly. That way, no unexpected errors will occur as the application is
being used. Now that you’ve completed this chapter, you should have the skills
you need to test an application to identify any bugs it may contain. Then, you
should be able to use the NetBeans debugger to locate the cause of those bugs.
The skills presented in this chapter should give you a solid foundation for
testing and debugging any application that you develop. However, you should
know that NetBeans provides some additional features that you can use to test
and debug your applications. For example, you can use the Watches window to
list the values of variables and expressions you specify, and you can use the
Breakpoints window to manage the breakpoints in an application. After
reading this chapter, you shouldn’t have any trouble learning how to use these
windows as well as other NetBeans features on your own.
As you begin to develop more complex applications, you may also want to
leam about unit testing. Unit testing is a way of creating tests for individual
units of source code such as methods to make sure that they work correctly.
As you test an application, you may also run into memory or performance-
related problems. To help identify the source of these problems, you can use
the NetBeans Profiler. This tool lets you monitor the performance of an
application. Then, you can use the data it provides to locate code in your
application that can be optimized so the application will run more efficiently.

Summary
• To test an application, you run it to make sure that it works properly no matter
what combinations of valid or invalid data you enter.
• When you debug an application, you find and fix all of the errors (bugs) that you
find when you test the application.
• Syntax errors violate the rules for how Java statements must be written. These
errors are detected by the NetBeans IDE or the Java compiler before you can run
the application.
• Runtime errors occur after you run an application. These types of errors throw
exceptions that stop the execution of the application.
• Logic errors don’t cause the application to crash, but they prevent it from working
correctly.
• A simple way to trace the execution of an application is to insert println statements
at key points in the code.
• NetBeans includes a powerful tool known as a debugger that can help you find and
fix these errors.
Chapter 6 How to test and debug an application

You can set a breakpoint on a line of code to stop code execution just before that
line of code. Then, you can step through the code and view the values of the vari­
ables as the code executes.
A stack trace is a list of methods in the reverse order in which they were called.

Exercise 6-1 Test and debug the Invoice


application

This exercise guides you through the process of using NetBeans to test and debug
an application.

Test the Invoice application with invalid data


1. Open the ch06_exl_Invoice project, and test the Invoice application with an
invalid subtotal like $1000 (enter the dollar sign too). This should cause the
application to crash with a runtime error and to display an error message in the
Output window.
2. Study the error message, and note the line number of the statement in the
InvoiceApp class that caused the crash. Then, click on the link to that line of
code. This should open the InvoiceApp.java file in the code editor and highlight
the line of code that caused the crash. Based on this information, you should be
able to figure out that the application crashed because $1000 isn’t a valid
double value. By now, you should know how to fix this type of problem.
Set a breakpoint and step through the application
3. Set a breakpoint on this line of code:
double discountPercent = 0.0;
4. Make sure that the ch06_exl_InvoiceApp project is set as the main project.
Then, click on the Debug Main Project button in the toolbar. This runs the
project with the debugger on.
5. Click the Output tab to display the Output window and enter a value of 100 for
the subtotal when prompted by the application. When you do, the application
runs to the breakpoint and stops.
6. Click the Variables tab to display the Variables window and note that the choice
and subtotal variables have been assigned values.
7. Click the Step Into button in the toolbar repeatedly to step through the
application one statement at a time. After each step, review the values in the
Variables window to see how they have changed. Note how the application
steps through the if/else statement based on the subtotal value.
8. Click the Continue button in the toolbar to continue the execution of the
application.
9. Display the Output window again. Then, enter “y” to continue and enter a
value of 50 for the subtotal.
182 Section 1 Essential Java skills

10. Display the Variables window again and inspect the values of the variables.
11. Click the Step Over button in the toolbar repeatedly to step through the
application one statement at a time. After each step, review the values in the
Variables window to see how they have changed.
12. When you’re done inspecting the variables, click the Finish Debugger Session
button to end the application. This should give you some idea of how useful
the NetBeans debugging tools can be.

Exercise 6-2 Test and debug the Future Value


application

In this exercise, you’ll use NetBeans to find and fix syntax errors and a logic
error in the Future Value application.

Use NetBeans to correct the syntax errors


1. Open the ch06_ex2_FutureValue project, and then display the
FutureValueApp.j ava file. Note that the getDouble method in this file
contains syntax errors.
2. Use NetBeans to find and fix the errors.
Use println statements to trace code execution
3. Scroll down to the calculateFutureValue method, and add a println statement
within the loop that prints the value of the month and the future value each
time the loop is executed.
4. Run the application to see how the println statement works.
Review the values that are displayed in the Output window, and
notice that that the future value increases by too much each month.
5. Comment out the println statement so it no longer prints messages
to the Output window.
Step through the application
6. In the calculateFutureValue method, set a breakpoint on the statement that
calculates the future value.
7. Run the application and enter values when prompted. The
application should stop at the breakpoint.
8. Experiment with the Step Into, Step Over, and Step Out buttons as
you step through the code of the application. At each step, notice
the values that are displayed in the Variables window and use
them to find the logic error.
9. When you’re done experimenting, click on the Finish Debugger
Session button and remove the breakpoint.
10. Fix the logic error and then run the application again to be sure it
produces correct results.
Section 2

Object-oriented programming
with Java
In the first section of this book, you learned how to use classes that are
provided as part of the Java API. For instance, you learned how to use the
Math class to perform common arithmetic operations, and you learned
how to use the NumberFormat class to format numeric values. That’s one
part of object-oriented programming.
Besides the classes provided by the API, though, you can create your
own classes. That’s the other part of object-oriented programming, and
that’s what the four chapters in this section teach you to do. Specifically,
chapter 7 shows you how to create your own classes. Chapter 8 shows you
how to use inheritance, one of the most important features of object-
oriented programming. Chapter 9 shows you how to use interfaces. And
chapter 10 presents other object-oriented skills.
Because each of the chapters in this section builds on the previous
chapters, you should read these chapters in sequence. In addition, you
should read all of the chapters in this section before going on to sections 3,
4, or 5. That’s because many of the chapters in these sections rely on your
knowledge of inheritance and interfaces.
7
How to define
and use classes
This chapter shows you how to create and use your own classes in Java
applications. Here, you’ll learn how to create classes that include regular fields
and methods as well as classes that contain static fields and methods. In
addition, you’ll see two complete applications that use several user-defined
classes.
When you complete this chapter, you’ll start to see how creating your
own classes can help simplify the development of an application. As a bonus,
you’ll have a better understanding of how the Java API works.

An introduction to classes................................................. 186


How classes can be used to structure an application.................................... 186
How encapsulation works..............................................................................188
The relationship between a class and its objects.......................................... 190
How to code a class that defines an object...................... 192
How to use NetBeans to create a new class.................................................. 192
The code for the Product class..................................................................... 194
How to code instance variables.....................................................................196
How to code constructors..............................................................................198
How to code methods................................................................................... 200
How to overload methods............................................................................. 202
How to use the this keyword........................................................................ 204
How to use NetBeans to work with classes..................................................206
How to create and use an object....................................... 208
How to create an object................................................................................ 208
How to call the methods of an object........................................................... 210
How primitive types and reference types are passed to a method............... 212
A ProductDB class that creates a Product object.........................................214
A ProductApp class that uses a Product object............................................216
How to code and use static fields and methods..............218
How to code static fields and methods.........................................................218
How to call static fields and methods........................................................... 220
How to code a static initialization block......................................................222
When to use static fields and methods.........................................................222
The Line Item application................................................... 224
The console....................................................................................................224
The class diagrams....................................................................................... 224
The code for the classes................................................................................ 226
Perspective........................................................................... 232
186 Section 2 Object-oriented programming with Java

An introduction to classes
The topics that follow introduce you to the concepts that you need to know
before you create your own classes. That includes how you’ll use classes in a
typical business application, how the fields and methods of a class can be
encapsulated within the class, and how a class relates to its objects.

How classes can be used


to structure an application
Figure 7-1 shows how you can use classes to simplify the design of a busi­
ness application using a multi-layered architecture, also called a multi-tiered
architecture. In a multi-layered application, the classes that perform different
functions of the application are separated into two or more layers, or tiers.
A three-tiered application architecture like the one shown in this figure
consists of a presentation layer, a middle layer, and a database layer. In practice,
the middle layer is sometimes eliminated and its functions split between the
database and presentation layers. On the other hand, the design of some applica­
tions further develops the middle layer into additional layers.
The classes in the presentation layer handle the details of the application’s
user interface. So far, all of the applications you’ve seen have been console
applications. In these applications, most of the presentation layer is handled by
the main method, which may call methods of other classes. In section 4, though,
you’ll leam how to write Java applications that display a graphical user interface
(GUI) that consists of multiple windows called frames. In these applications, a
separate class is usually created for each frame displayed by the application.
The classes of the database layer are responsible for all of the database
access that’s required by the application. These classes typically include meth­
ods that connect to the database and retrieve, add, update, and delete informa­
tion from the database. Then, the other layers can call these methods to access
the database. Although we refer to this layer as the database layer, it can also
contain classes that work with data that’s stored in files.
The middle layer provides an interface between the database layer and the
presentation layer. This layer often includes classes that correspond to business
entities (for example, products and customers). It may also include classes that
implement business rules, such as discount or credit policies. The classes in this
tier are often referred to as business classes, and the objects that are created
from these classes are often called business objects.
One advantage of developing applications with a tiered architecture is that it
allows the work to be spread among members of a development team. For
example, one group of developers might work on the database layer, another
group on the middle layer, and still another group on the presentation layer.
Another advantage is that it allows classes to be shared among applications.
In particular, the classes that make up the database and middle layers can be
stored in packages that can be used by more than one project. You’ll leam how
to work with packages in chapter 10.
Chapter 7 How to define and use classes 187

The architecture of a three-tiered application

Presentation Presentation
layer classes

Middle Business
layer classes

Database
layer Database

Description
• To simplify development and maintenance, many applications use a three-tiered
architecture to separate the application’s user interface, business rules, and data­
base processing. Classes are used to implement the functions performed at each
layer of the architecture.
• The classes in the presentation layer control the application’s user interface. For a
console application, the presentation layer typically consists of a class with a main
method and any other classes related to console input and output. For a GUI
application, the user interface typically consists of one class for each window
(called a frame in Java) that makes up the GUI.
• The classes in the database layer handle all of the application’s data processing.
• The classes in the middle layer, which is sometimes called the business rules layer,
act as an interface between the classes in the presentation and database layers.
Sometimes, these classes correspond to business entities, such as customers or
products, and sometimes these classes implement business rules, such as discount
or credit policies. Often, the classes in this layer are referred to as business classes,
and the objects created from them are called business objects.
• The classes that make up each layer are often stored in packages that can be shared
among applications. For more information, see chapter 10.

Figure 7-1 How classes can be used to structure an application


188 Section 2 Object-oriented programming with Java

How encapsulation works


Figure 7-2 shows a class diagram for a class named Product. This diagram
uses Unified Modeling Language (JJML), a modeling language that has become
the industry standard for working with all object-oriented programming lan­
guages including Java.
In this class diagram, the class contains three fields and seven methods.
Here, the minus sign (-) identifies fields and methods that are available only
within the current class, while the plus sign (+) identifies fields and methods
that are available to other classes.
In this case, all of the methods are available to other classes, but none of the
fields are. However, the methods make the data stored by the fields available to
other classes. For instance, the getCode method returns the value stored in the
code field, and the setCode method assigns a new value to the code field.
This illustrates the concept of encapsulation, which is a fundamental
concept of object-oriented programming. This means that the programmer can
hide, or encapsulate, some fields and methods of a class, while exposing others.
Since the fields (or data) of a class are typically encapsulated within a class,
encapsulation is sometimes referred to as data hiding.
When you use a class, encapsulation lets you think of it as a black box that
provides useful fields and methods. When you use the parselnt method of the
Integer class, for example, you don’t know how the method converts a string to
an integer, and you don’t need to know. Similarly, if you use the getPrice
method of the Product class in this figure, you don’t know how the method
works, and you don’t need to know.
This also means that you can change the code for a method within a class
without affecting the classes that use the method. For instance, you can change
the code for the getPrice method without changing the classes that use that
method. This makes it easier to upgrade or enhance an application because you
only need to change the classes that need upgrading.
Chapter 7 How to define and use classes 189

A class diagram for the Product class


Product
-code: String
-description: String
-price: double

+setCode(String)
+getCode(): String
+setDescription(String)
+getDescription(): String > Methods
+setPrice(double)
+getPrice(): double
+getFormattedPrice(): String

Description
• The fields of a class store the data of a class.
• The methods of a class define the tasks that a class can perform. Often, these
methods provide a way to work with the fields of a class.
• Encapsulation is one of the fundamental concepts of object-oriented programming.
This means that the class controls which of its fields and methods can be accessed
by other classes. As a result, the fields in the class can be hidden from other classes,
and the methods in a class can be modified or improved without changing the way
that other classes use them.

UML diagramming notes


• UML ( Unified Modeling Language) is the industry standard used to describe the
classes and objects of an object-oriented application.
• The minus sign (-) in a UML class diagram marks the fields and methods that can’t
be accessed by other classes, while the plus sign (+) marks the fields and methods
that can be accessed by other classes.
• For each field, the name is given, followed by a colon, followed by the data type.
• For each method, the name is given, followed by a set of parentheses. If a method
requires parameters, the data type of each parameter is listed in the parentheses.
Otherwise, the parentheses are left empty, and the data type of the value that’s
going to be returned is given after the colon.

Figure 7-2 How encapsulation works


190 Section 2 Object-oriented programming with Java

The relationship between a class and its objects


Figure 7-3 uses UML diagrams to show the relationship between a class and
its objects. In this figure, one class diagram and two object diagrams show how
objects are created from a class. Here, the diagrams show only the fields, not the
methods, of the class and its objects. In this case, two objects named productl
and product2 are created from the Product class.
Although an object diagram is similar to a class diagram, there are two
differences. First, the name of the object diagram is underlined. Second, each
field in an object diagram contains a value.
Once an instance of a class is created, it has an identity and a state. An
object’s identity is its address in internal memory, which is always unique. An
object’s state refers to the values that are stored by the object. For example, the
states of the two Product objects in this figure are determined by the three
values that they hold. As a program executes, the state of an object may change,
but the identity of the object won’t.
Chapter 7 How to define and use classes

The relationship between a class and its objects


Product
-code: String
-description: String
-price: double

i V
Droductl
-code = "java"
-description = "Murach1s Beginning Java"
-price = 49.50 1f
prod uct2
-code = "mcb2n
-description = "Murach1s Mainframe COBOL"
-price = 59.50

Description
• A class can be thought of as a template from which objects are made.
• An object diagram provides the name of the object and the values of the fields.
• Once an instance of a class is created, it has an identity (a unique address) and a
state (the values that it holds). Although an object’s state may change throughout a
program, its identity never does.

Figure 7-3 The relationship between a class and its objects


192 Section 2 Object-oriented programming with Java

How to code a class


that defines an object
Now that you’ve learned some of the basic concepts for using classes,
you’re ready to leam the basic skills for creating your own classes. In the topics
that follow, you’ll leam how to create a business class named Product that you
can use to work with products.

How to use NetBeans to create a new class


When you develop object-oriented applications, you’ll frequently need to
add new classes to your projects. To do that with NetBeans, you can use the
New Java Class dialog box shown in figure 7-4. In this figure, for example, this
dialog box is being used to create a class named Product.
Notice here that a package isn’t specified for the class. Because of that, the
class will be stored in the default package. Although it’s typically a good idea to
use packages to organize the classes in an application, this chapter and the next
two chapters will focus on creating and using classes. Then, in chapter 10,
you’ll leam how to create and use packages.
When you complete the New Java Class dialog box, NetBeans creates a file
that will store the Java code for the class. For the Product class in this figure,
that file will be named Product.java. NetBeans also generates the starting code
for the class as shown in this figure. Note that the name of the class matches the
name of the file, which is required. In addition, the public access modifier is
used so the class can be accessed from other classes.
By default, NetBeans places the opening brace for a class it creates on the
same line as the class declaration. However, if you prefer to have the opening
brace on its own line, you should know that you can change how this code is
generated. To do that, you can use the Tools->Option command as described in
this figure.
Chapter 7 How to define and use classes 193

The dialog box for creating a new Java class


Q New Java Class

Steps Ha me and Location

1, Choose File Type Class Name: Product]


2. Name and Location

Project: ;ch07_Product

Location: Source Packages

Package:

Created File: C:V™jrach\javaVietbeans^)ook_appsVh07_ProdLict\srcV5roduct.java

! . Warning: I t is highly recommended that you do NOT place Java dasses in the default package.

I < Back - I Finish | | Cancel | Help

The code that’s generated for the Product class


public class Product {

Description
• To create a new class, right-click on the package where you want to add the class,
select the New->Java Class command, and respond to the resulting dialog box. At
the least, you should enter a name for the class in the Class Name text box.
• Although this dialog box encourages you to select a package for the class, this isn’t
required. If you don’t select a package for the class, NetBeans will store the class in
the default package. To leam how to create and use packages, see chapter 10.
• You can change a NetBeans option so the opening brace for a class is on its own
line rather than on the same line as the class declaration. To do that, use the
Tools-^Options command, click the Editor button at the top of the Options dialog
box that’s displayed, display the Formatting tab, select Java from the Language
drop-down list, and select Braces from the Category drop-down list. Then, select
New Line from the Class Declaration drop-down list.

Figure 7-4 How to use NetBeans to create a new class


194 Section 2 Object-oriented programming with Java

The code for the Product class


Figure 7-5 presents the code for the Product class. This code implements the
fields and methods of the class diagram in figure 7-2. In the next six pages, you’ll
learn the details of writing code like the code shown here. For now, I’ll just present
a preview of this code so you have a general idea of how it works.
The first three statements in this class are declarations for the fields of the class.
The, fields are the variables or constants that are available to the class and its ob­
jects. In this example, all three fields define instance variables, which store the data
for the code, description, and price variables that apply to each Product object.
After the field declarations, this class declares the constructor of the Product
class. This constructor creates an instance of the Product class and initializes its
instance variables to their default values. As you’ll see later in this chapter, you
can also code constructors that accept parameters. Then, the constructor can use
the parameter values to initialize the instance variables.
Next are the declarations for the methods of the Product class. In this class, the
methods provide access to the values stored in the three fields. For each field, a get
method returns the value stored in the field, while a set method assigns a new
value to the field. Of these methods, the getFormattedPrice method is the only
method that does any work beyond getting or setting the value provided by the
instance variable. This method applies the standard currency format to the price
variable and returns the resulting string.
Although the Product class includes both a get and a set method for each field,
you don’t always have to code both of these methods for a field. In particular, it’s
common to code just a get method for a field so that its value can be retrieved but
not changed. This can be referred to as a read-only field. Although you can also
code just a set method for a field, that’s uncommon.
The private and public keywords determine which members of a class are
available to other classes. Since all of the instance variables of the Product class
use the private keyword, they are only available within that class. The constructor
and the methods, however, use the public keyword. As a result, they are available
to all classes. Keep in mind, though, that you can include both public and private
instance variables and methods in any class.
By the way, this class follows the three coding rules that are required for a
JavaBean. First, it includes a constructor that requires no arguments. Second, all
of the instance variables are private. Third, it includes get and set methods for all
instance variables that you want to be able to access. As you progress with Java,
you’ll find many advantages to creating classes that are also JavaBeans. For
example, if you develop JavaServer Pages (JSPs) for a web application, you can
use special JSP tags to create a JavaBean and to access its get and set methods.
Now that you’ve seen the code for the Product class, you might want to
consider how it uses encapsulation. First, the three fields are hidden from other
classes because they’re declared with the private keyword. In addition, all of the
code contained within the constructor and methods is hidden. Because of that, you
can change any of this code without having to change the other classes that use
this class.
Chapter 7 How to define and use classes 195

The Product class


import java.text.NumberFormat;

public class Product


{
// the instance variables
private String code;
private String description;
private double price;

// the constructor
public Product()
{
code = 1111;
description = "";
price = 0 ;
}
// the set and get methods for the code variable
public void setCode(String code)
{
this.code = code;
}
public String getCodeO
{
return code;
}
// the set and get methods for the description variable
public void setDescription(String description)
{
this.description = description;
}
public String getDescription()
{
return description;
}
// the set and get methods for the price variable
public void setPrice(double price)
{
this.price = price;
}
public double getPriceO
{
return price;
}
// a custom get method for the price variable
public String getFormattedPrice()
{
NumberFormat currency = NumberFormat.getCurrencylnstance();
return currency.format(price);
}

Figure 7-5 The code for the Product class


196 Section 2 Object-oriented programming with Java

How to code instance variables


Figure 7-6 shows how to code the instance variables that define the types of
data that are used by the objects that are created from a class. When you declare
an instance variable, you should use an access modifier to control its accessibil­
ity. If you use the private keyword, the instance variable can be used only within
the class that defines it. In contrast, if you use the public keyword, the instance
variable can be accessed by other classes. You can also use other access modifi­
ers that give you finer control over the accessibility of your instance variables.
You’ll learn about those modifiers in the chapters that follow.
This figure shows four examples of declaring an instance variable. The first
example declares a variable of the double type. The second one declares a
variable of the int type. The third one declares a variable that’s an object of the
String class. And the last one declares an object from the Product class.. .the
class that you’re learning how to code right now.
Although instance variables work like regular variables, they must be
declared within the class body, but not inside methods or constructors. That
way, they’ll be available throughout the entire class. In this book, all of the
instance variables for a class are declared at the beginning of the class. How­
ever, when you read through code from other sources, you may find that the
instance variables are declared at the end of the class or at other locations within
the class.
Chapter 7 How to define and use classes 197

The syntax for declaring instance variables


public Iprivate primitiveType|ClassName variableName;

Examples
private double price;
private int quantity;
private String code;
private Product product;

Where you can declare instance variables


public class Product
{
//common to code instance variables here
private String code;
private String description;
private double price;

//the constructors and methods of the class


public Product(){}
public void setCode(String code){}
public String getCode(){ return code; }
public void setDescription(String description)!}
public String getDescription(){ return description; }
public void setPrice(double price){}
public double getPrice(){ return price; }
public String getFormattedPrice(){ return formattedPrice; }

//also possible to code instance variables here


private int test;
}

Description
• An instance variable may be a primitive data type, an object created from a Java
class such as the String class, or an object created from a user-defined class such as
the Product class.
• To prevent other classes from accessing instance variables, use the private keyword
to declare them as private.
• You can declare the instance variables for a class anywhere outside the constructors
and methods of the class.

Figure 7-6 How to code instance variables


198 Section 2 Object-oriented programming with Java

How to code constructors


Figure 7-7 shows how to code a constructor for a class. When you code one,
it’s a good coding practice to assign a value to all of the instance variables of the
class as shown in the four examples. You can also include any additional
statements that you want to execute within the constructor. For instance, the
fourth example ends by calling two different get methods from the current class.
When you code a constructor, you must use the public access modifier and
the same name, including capitalization, as the class name. Then, if you don’t
want to accept arguments, you must code an empty set of parentheses as shown
in the first example. On the other hand, if you want to accept arguments, you
code the parameters for the constructor as shown in the next three examples.
When you code the parameters for a constructor, you must code a data type and
a name for each parameter. For the data type, you can code a primitive data type
or the class name for any class that defines an object.
The second example shows a constructor with three parameters. Here, the
first parameter is a String object named code; the second parameter is a String
object named description; and the third parameter is a double type named price.
Then, the three statements within the constructor use these parameters to
initialize the three instance variables of the class.
In this example, the names of the parameters are the same as the names of
the instance variables. As a result, the constructor must distinguish between the
two. To do that, it uses the this keyword to refer to the instance variables of the
current object. You’ll learn about other ways you can use this keyword later in
this chapter.
The third example works the same as the second example, but it doesn’t
need to use the this keyword because the parameter names aren’t the same as
the names of the instance variables. In this case, though, the parameter names
aren’t very descriptive. As a result, the code in the second example is easier for
other programmers to read than the code in the third example.
The fourth example shows a constructor with one parameter. Here, the first
statement assigns the first parameter to the first instance variable of the class.
Then, the second statement calls a method of a class named ProductDB to get a
Product object for the specified code. Finally, the last two statements call
methods of the Product object, and the values returned by these methods are
assigned to the second and third instance variables.
When you code a constructor, the class name plus the number of parameters
and the data type for each parameter form the signature of the constructor. You
can code more than one constructor per class as long as each constructor has a
unique signature. For example, the first two constructors shown in this figure
have different signatures so they could both be coded within the Product class.
This is known as overloading a constructor.
If you don’t code a constructor, Java will create a default constructor that
doesn’t accept any parameters and initializes all instance variables to null, zero,
or false. If you code a constructor that accepts parameters, though, Java won’t
create this default constructor. So if you need a constructor like that, you’ll need
to code it explicitly. To avoid this confusion, it’s a good practice to code all of
Chapter 7 How to define and use classes 199

The syntax for coding constructors


public ClassName([parameterList] )
{
// the statements of the constructor
}
Example 1: A constructor that assigns default values
public Product()
{
code = 1111;
description = "" ;
price = 0.0;
}
Example 2: A custom constructor with three parameters
public Product(String code. String description, double price)
{
this.code = code;
this.description = description;
this.price = price;
}
Example 3: Another way to code the constructor shown above
public Product(String c. String d, double p)
{
code = c;
description = d;
price = p ;
}
Example 4: A constructor with one parameter
public Product(String code)
{
this.code = code;
Product p = ProductDB.getProduct(code);
description = p.getDescription();
price = p.getPrice();
}

Description
• The constructor must use the same name and capitalization as the name of the class.
• If you don’t code a constructor, Java will create a default constructor that initializes
all numeric types to zero, all boolean types to false, and all objects to null.
• To code a constructor that has parameters, code a data type and name for each
parameter within the parentheses that follow the class name.
• The name of the class combined with the parameter list forms the signature of the
constructor. Although you can code more than one constructor per class, each
constructor must have a unique signature.
• In the second and fourth examples above, the this keyword is used to refer to an
instance variable of the current object.

Figure 7-7 How to code constructors


200 Section 2 Object-oriented programming with Java

your own constructors. That way, it’s easy to see which constructors are avail­
able to a class, and it’s easy to check the values that each constructor uses to
initialize the instance variables.

How to code methods


Figure 7-8 shows how to code the methods of a class. To start, you code an
access modifier. Most of the time, you can use the public keyword to declare the
method so it can be used by other classes. However, you can also use the private
keyword to hide the method from other classes.
After the access modifier, you code the return type for the method, which
refers to the data type that the method returns. After the return type, you code
the name of the method followed by a set of parentheses. Within the parenthe­
ses, you code the parameter list for the method. Last, you code the opening and
closing braces that contain the statements of the method.
Since a method name should describe the action that the method performs,
it’s a common coding practice to start each method name with a verb. For
example, methods that set the value of an instance variable usually begin with
set. Conversely, methods that return the value of an instance variable usually
begin with get. These types of methods are typically referred to as accessors
because they let you access the values of the instance variables. Methods that
perform other types of tasks also begin with verbs such as print, save, read, and
write.
The first example shows how to code a method that doesn’t accept any
parameters or return any values. To do that, it uses the void keyword for the
return type and it ends with a set of empty parentheses. When this method is
called, it prints the instance variables of the Product object to the console,
separating each instance variable with a pipe character (I).
The next three examples show how to code methods that return data. To do
that, these methods specify a return type, and they include a return statement to
return the appropriate variable. When coding a method like this, you must make
sure that the return type that you specify matches the data type of the variable
that you return. Otherwise, your code won’t compile.
In the fourth example, the getFormattedPrice method uses a NumberFormat
object to apply standard currency formatting to the double variable named price.
This also converts the double variable to a String object. Then, the return
statement returns the String object to the calling method.
The fifth and sixth examples show two possible ways to code a set method.
In the fifth example, the method accepts a parameter that has the same name as
the instance variable. As a result, the assignment statement within this method
uses the this keyword to identify the instance variable. In the sixth example, the
parameter has a different name than the instance variable. As a result, the
assignment statement doesn’t need to use the this keyword. Since the parameter
name for both examples are descriptive, both of these examples work equally
well.
Chapter 7 How to define and use classes 201

The syntax for coding a method


public Iprivate returnType methodName([parameterList])
{
// the statements of the method
}
Example 1: A method that doesn’t accept parameters or return data
public void printToConsole()
{
System.out.println(code + "I" + description + " |" + price);
}
Example 2: A get method that returns a string
public String getCodeO
{
return code;
}
Example 3: A get method that returns a double value
public double getPrice()
{
return price;
}
Example 4: A custom get method
public String getFormattedPrice()
{
NumberFormat currency = NumberFormat.getCurrencylnstanceO;
return currency.format(price);
}
Example 5: A set method
public void setCode(String code)
{
this.code = code;
}
Example 6: Another way to code a set method
public void setCode(String productCode)
{
code = productCode;
}
Description
• To allow other classes to access a method, use the public keyword. To prevent other
classes from accessing a method, use the private keyword.
• To code a method that doesn’t return data, use the void keyword for the return type.
To code a method that returns data, code a return type in the method declaration
and code a return statement in the body of the method.
• When you name a method, you should start each name with a verb. It’s a common
coding practice to use the verb set for methods that set the values of instance
variables and to use the verb get for methods that return the values of instance
variables. These methods are typically referred to as set and get accessors.
Figure 7-8 How to code methods
202 Section 2 Object-oriented programming with Java

How to overload methods


Figure 7-9 shows how to overload a method, which is similar to overloading
a constructor. When you overload a method, you code two or more methods
with the same name, but with unique combinations of parameters. In other
words, you code methods with unique signatures.
For a method signature to be unique, the method must have a different
number of parameters than the other methods with the same name, or at least
one of the parameters must have a different data type. Note that the names of
the parameters aren’t part of the signature. So using different parameter names
isn’t enough to make the signatures unique. Also, the return type isn’t part of the
signature. As a result, you can’t create two methods with the same name and
parameters but different return types.
The purpose of overloading is to provide more than one way to invoke a
given method. For example, this figure shows three versions of the
printToConsole method. The first one accepts a String parameter named sep
that’s used to separate the code, price, and description of a Product object. Then,
it prints the resulting string to the console.
The second method doesn’t accept a parameter that specifies the separator
string. Instead, it separates the code, price, and description with the pipe charac­
ter. To do that, it calls the first printToConsole method and passes the pipe
character to it. Although I could have just called the println method to print the
line, calling an overloaded method can often prevent code duplication.
The third method accepts a String parameter for the separator along with a
boolean parameter that indicates whether to print a blank line after printing the
data to the console. This method begins by passing the sep parameter to the first
printToConsole method. Then, it uses an if statement to determine whether to
print a blank line.
When you refer to an overloaded method, the number of arguments you
specify and their types determine which version of the method is executed. The
three statements in this figure that call the printToConsole method illustrate how
this works. Because the first statement doesn’t specify an argument, it causes
the second version of the printToConsole method to be executed. In contrast, the
second statement specifies a String argument of four blank spaces and a boolean
argument of true. As a result, it will cause the third version of the
printToConsole method to be executed. Finally, the third statement specifies a
single String argument, which causes the first version of the printToConsole
method to be executed.
Chapter 7 How to define and use classes 203

Example 1: A method that accepts one argument


public void prlntToConsole(String sep)
{
System.out.println(code + sep + description + sep + price);
}

Example 2: An overloaded method that provides a default value


public void printToConsole()
{
prlntToConsole("I"); // this calls the method In the first example
}

Example 3: An overloaded method with two arguments


public void printToConsole(String sep, boolean printLineAfter)
{
printToConsole(sep); // this calls the method in the first example
if (printLineAfter)
System.out.println();
}

Code that calls these methods


Product p = ProductDB.getProduct("java");

p.printToConsole() ;
p .printToConsole(" ", true);
p.printToConsole(" 11) ;

The console
f/-- ;--- ;------------- ;-- .---------- :------------- ------ Λ
j ava jMurach1s Beginning Java 2 |4 9.5
java Murach's Beginning Java 49.5

java Murach's Beginning Java 49.5


V ---------- ------ J

Description
• When you create two or more methods with the same name but with different
parameter lists, the methods are overloaded. It’s common to use overloaded meth­
ods to provide two or more versions of a method that work with different data types
or that supply default values for omitted parameters.

Figure 7-9 How to overload methods


204 Section 2 Object-oriented programming with Java

How to use the this keyword


In figures 7-7 and 7-8, you saw how to use the this keyword to refer to an
instance variable from a constructor or method. You can also use this keyword
to call methods of the current object, to pass the current object to another
method, and to call another constructor of the current class from the current
constructor. Figure 7-10 shows you how to use this keyword.
The first line of the syntax summary shows how to refer to an instance
variable of the current object. The second and third lines show how to call a
constructor or method of the same class. And the fourth and fifth lines show
how to pass the current object to a method of the object and to a static method
of a class.
Since Java implicitly supplies the this keyword for all instance variables and
methods, you don’t usually need to code this keyword when referring to in­
stance variables or methods. However, the first example is an exception to this
rule. Here, the code, description, and price parameters in the constructor have
the same names as the code, description, and price instance variables. As a
result, you need to use the this keyword to explicitly identify the instance
variables. Of course, another approach would be to change the parameter names
so they aren’t the same as the instance variable names.
The second example shows how to call the getPrice method of the current
object. In this case, the this keyword isn’t necessary because it would be added
implicitly. However, it does make it clear that the getPrice method is a method
of the current object.
The third example shows how to call another constructor in the same class.
Specifically, this constructor uses the this keyword to call the constructor in the
first example, and it passes three default values to it. This is an easy way to
overload a constructor so it provides default values for missing parameters.
The fourth example shows how to use the this keyword to pass the current
object to a method. In this example, a method named print sends the current
object to the println method of the System.out object. As a result, the println
method will print a representation of the current object to the console.
The fifth example works like the fourth example, but it shows that you can
use the this keyword to pass the current object to a static method. In this case, a
method named save saves the current object by calling the static saveProduct
method of the ProductDB class.
Chapter 7 How to define and use classes 205

The syntax for using the this keyword


this.variableName // refers to an instance variable of the current object
this(argumentList); // calls another constructor of the same class
this.methodName(argumentList) // calls a method of the current object
objectName.methodName(this) // passes the current object to a method
ClassName.methodName(this) // passes the current object to a static method

Example 1: How to refer to instance variables


public Product(String code. String description, double price)
{
this.code = code;
this.description = description;
this.price = price;
}

Example 2: How to refer to methods


public String getFormattedPrice()
{
NumberFormat currency = NumberFormat.getCurrencylnstanceO;
return currency.format(this.getPrice) ;
}

Example 3: How to call a constructor


public Product()
{
this("", 0.0);
}

Example 4: How to send the current object to a method


public void print()
{
System.out.println(this);
}

Example 5: How to send the current object to a static method


public void save()
{
ProductDB.saveProduct(this) ;
}

Description
• Since Java implicitly uses the this keyword for instance variables and methods, you
don’t need to explicitly code it unless a parameter has the same name as an instance
variable.
• If you use the this keyword to call another constructor, the statement must be the
first statement in the constructor.

Figure 7-10 How to use the this keyword


206 Section 2 Object-oriented programming with Java

How to use NetBeans to work with classes


Figure 7-11 shows how NetBeans can make it easier to work with classes.
To start, after you enter the private fields for a class, you can use NetBeans to
generate the get and set methods for those fields. To do that, you use the Encap­
sulate Fields dialog box shown in this figure. As you can see, this dialog box
lists all the private fields and lets you select what methods you want to generate
for each field. It also lets you set several options that control how the methods
are generated.
When you use the Encapsulate Fields dialog box, the get and set methods
for a field are formatted like this by default:
public String getCodeO {
return code;
}
public void setCode(String code) {
this.code = code;
}
Just as you can when you create a class, though, you can change the code that’s
generated for a method so the opening brace is on its own line. To do that, you
select the New Line option from the Method Declaration drop-down list in the
Options dialog box. For more information about displaying this option, see
figure 7-4.
Once you’ve created a class, you can use the Navigator window shown in
this figure to jump to any member of the class. To do that, just double-click on
the member name. Although the usefulness of this feature isn’t obvious for a
simple class like the Product class, it can be helpful for classes with more
members.
Chapter 7 How to define and use classes 207

The NetBeans window for the Product application


Q chO/.Product - NetBeans IDE 7.0

F ile E d it V ie w N a v ig a te S o u rc e R e fa c to r Run D ebug P r o f ile T eam T o o ls . W in d o w H e lp j Search (C1rl+I)

0 '
: P ro je c ts 1Product.java 28 ’ ProductApp.java ; Pr&ductOB.java S8
g f di07_Product
IQ φ jg Source Packages
El iit.p o r t j a v a . t e x t , Huir.be rF o rit,a t;
h ä ! 2 1 1 và

ά - β - Ι <default package>
fa^frroduct.java P*obl±c c l a s s P r o d u c t
.java {
p r iv a te S tr in g code;
•to Libraries p r iv a te S tr in g d e s c r ip tio n ;
p r i v a t e d o u b le p r i c e ;
5
J public P r o d u c t (J
: Product.java - Navigator 10Π
co d e = ;
£ Product d e s c r i p t i o n = ,,r';
f O ProductO
p r i c e = 0;
Î
O getCodeO : String
■■■ Q getDescription{) : String
p u b l i c v o id s e tC o d e ( S tr in g ' c c d e f

;·-··
Q getformattedPriceO : String
Q getPriceO : double
{
t h i s . co d e = c o d e ;
Q setCode{String code)
>■·· ( j setDescripSon(5tring description)
}
f-· Q setPricefdciuble price)
Output
-t^j] code : String
-% ] desCTlption : String
-% ] price : double

& QXIGEDGSDQIJ «
111 INS

The dialog box for generating get and set methods

Description
• To generate g e t an d se t m ethods fo r one o r m ore field , select th e
R efactor-> E ncapsulate F ield s com m and an d resp o n d to th e resu ltin g dialo g box.
• T he N avigator w indow lists a ll th e m em bers o f th e cu rren tly selected class. To
d isp lay th is w indow , c lic k on its tab a t th e le ft sid e o f th e ID E , o r u se th e
W indow -^N avigating -^N avigator com m and. To ju m p to a m em ber, d o uble-click
on it in th e N avigator w indow .

Figure 7-11 How to use NetBeans to work with classes


208 Section 2 Object-oriented programming with Java

How to create and use an object


In earlier chapters, you learned how to create an object from a Java class
and call the methods of that object. Now that you know how a class works, you
should have a much better idea of what’s happening when you do that. So in the
next three topics, you’ll review the skills for creating objects and using meth­
ods. Then, you’ll see a class that creates a Product object, and you’ll see a class
that uses that object.

How to create an object


Figure 7-12 shows how to create an object with one and with two state­
ments. Most of the time, you’ll use one statement to create an object. However,
as you’ll see later in this book, certain types of coding situations require you to
create an object with two statements.
When you use two statements to create an object, the first statement de­
clares the class and the name of the variable that the object will be assigned to.
However, an instance of the object isn’t actually created until the second state­
ment is executed. This statement uses the new keyword to call the constructor
for the object, which initializes the instance variables. Then, a reference to this
object is assigned to the variable. At this point, you can use the variable to refer
to the object.
When you send arguments to the constructor of a class, you must make sure
that the constructor will be able to accept the arguments. To do that, you must
send the right number of arguments, in the right sequence, and with data types
that are compatible with the data types specified in the parameter list of the
constructor. When a class contains more than one constructor, the constructor
that matches the arguments that are sent is the constructor that will be executed.
The two-statement example in this figure creates a new Product object
without passing any arguments to the constructor of the Product class. The same
task is accomplished by the first one-statement example. Then, the second and
third examples show how to send a single argument to the constructor of the
Product class. Both of these statements send a String object, but the second
example sends a literal while the third example sends a variable that refers to a
String object. The fourth example sends three arguments to the constructor.
Chapter 7 How to define and use classes 209

How to create an object in two statements


Syntax
ClassName variableName;
variableName = new ClassName(argumentList);

Example with no arguments


Product product;
product = new Product();

How to create an object in one statement


Syntax
ClassName variableName = new ClassName(argumentList);

Example 1: No arguments
Product product = new Product();

Example 2: One literal argument


Product product = new Product("java");

Example 3: One variable argument


Product product = new Product(productCode);

Example 4: Three arguments


Product product = new Product(code, description, price);

Description
• To create an object, you use the new keyword to create a new instance of a class.
Each time the new keyword creates an object, Java calls the constructor for the
object, which initializes the instance variables for the object.
• After you create an object, you assign it to a variable. When you do, a reference to
the object is stored in the variable. Then, you can use the variable to refer to the
object.
• To send arguments to the constructor, code the arguments between the parentheses
that follow the class name. To send more than one argument, separate the argu­
ments with commas.
• When you send arguments to the constructor, the arguments must be in the se­
quence called for by the constructor and they must have data types that are compat­
ible with the data types of the parameters for the constructor.

Figure 7-12 How to create an object


210 Section 2 Object-oriented programming with Java

How to call the methods of an object


Figure 7-13 shows how to call the methods of an object. By now, you
should be familiar with the basic syntax for calling a method, so this figure
should just be review. To start, you type the object name followed by the dot
operator and the method name. Then, if the method requires arguments, you
code the argument list between the parentheses, separating multiple arguments
with commas. Otherwise, you code an empty set of parentheses.
The first two examples show two ways to call methods that don’t return any
data. The first example doesn’t send an argument, while the second example
sends an argument named productCode. In this case, the argument is a variable
that represents a String object, but the argument could also be a literal value
such as “java”. Either way, you need to send the right number of arguments, and
the data types of those arguments must be compatible with the data types
specified in the parameter list of the method.
The third and fourth examples show how to call a method that returns a
value and assigns that value to a variable. In the third example, the getPrice
method doesn’t have any arguments, but it does return a value. Then, that value
is assigned to a double variable named price. In the fourth example, the
getFormattedPrice method sends a boolean variable as an argument that indi­
cates whether a dollar sign should be included in the formatted value. This is a
variation of the getFormattedPrice method you saw back in figure 7-5. Like that
method, this method returns a string that is then stored in a string variable.
The fifth example shows how to call a method within an expression. Here,
the expression includes a call to the getCode method, which returns a String
object. Then, that String object is joined with three string literals, and the result
is assigned to another String object.
Chapter 7 How to define and use classes 211

How to call a method


Syntax
objectName.methodName(argumentList)

Example 1: Sends and returns no arguments


product.printToConsole();

Example 2: Sends one argument and returns no arguments


product.setCode(productCode);

Example 3: Sends no arguments and returns a double value


double price = product.getPrice();

Example 4: Sends an argument and returns a String object


String formattedPrice = product.getFormattedPrice(includeDollarSign);

Example 5: A method call within an expression


String message = "Code: " + product.getCode() + "\n\n"
+ "Press Enter to continue or enter 'x' to exit:";

Description
• To call a method that doesn’t accept arguments, type an empty set of parentheses
after the method name.
• To call a method that accepts arguments, enter the arguments between the parenthe­
ses that follow the method name. Here, the data type of each argument must be
compatible with the data type that’s specified by the method’s parameters.
• To code more than one argument, separate the arguments with commas.
• If a method returns a value, you can code an assignment statement to assign the
return value to a variable. Here, the data type of the variable must be compatible
with the data type of the return value.

Figure 7-13 How to call the methods of an object


212 Section 2 Object-oriented programming with Java

How primitive types and reference types


are passed to a method
Figure 7-14 shows the difference between passing primitive types to a
method and passing reference types (objects) to a method. In both cases, the
value of the variable is passed to the method rather than the variable itself. Since
a primitive type variable stores the actual value of the variable, though, that
means that the method can’t change the value of the variable directly. In con­
trast, a reference type variable stores a reference to the object. Because of that,
the method has access to the object and can change the values of its variables.
The first example shows how this works when a primitive data type is
passed to a method that increases the value of the variable by 10%. In this case,
the increasePrice method uses a return statement to return the increased value.
Then, the code that calls this method reassigns the return value to the original
variable. In other words, the method works with the value of the variable, but it
can’t modify the value in the variable itself.
The second example shows how this works when a reference type is passed
to a method. Here, the increasePrice method accepts a Product object. Notice
that the return type for this method is void, so no value is returned by the
method. Instead, the getPrice and setPrice methods of the Product class are used
to get and set the quantity variable. In other words, the method refers to the
object and its data so that data is actually changed by the method.
In practice, you usually don’t need to know how values are passed to
methods. Most of the time, you won’t need to modify a value that’s stored in a
parameter. Occasionally, though, you do need to be aware of the differences in
how you work with primitive types and object types. When you do, you can
refer back to this figure to refresh your memory.
Chapter 7 How to define and use classes 213

Example 1: A primitive type that’s passed to a method


A method that changes the value of a double type
static double increasePrice(double price) // returns a double
{
return price *= 1.1;
}
Code that calls the method
double price = 49.5;
price = increasePrice(price); // reassignment statement
System.out.println("price: " + price);

Result
price: 54.45

Example 2: An object type that’s passed to a method


A method that changes a value stored in a Product object
static void increasePrice(Product product) // no return value
{
double price = product.getPrice();
product.setPrice(price *= 1.1);
}
Code that calls the method
Product product = ProductDB.getProductC'java");
System.out.println("product.getPrice(): " + product.getPrice());
increasePrice(product); // no reassignment necessary
System.out.println("product.getPriceO: " + product.getPrice());

Result
product.getPrice(): 49.5
product.getPrice(): 54.45

Description
• When a primitive type is passed to a method, the method receives the value of the
variable. That means the method can’t change the value of the variable directly.
Instead, the method must return a new value that gets stored in the variable.
• When a reference type (an object) is passed to a method, the method also receives
the value of the variable. Because an object variable contains a pointer to the
object, though, the method can change the data in the object. That means that a new
value doesn’t need to be returned by the method.

Figure 7-14 How primitive types and reference types are passed to a method
214 Section 2 Object-oriented programming with Java

A ProductDB class that creates a Product object


Figure 7-15 presents a database class named ProductDB that provides the
data processing required by an application that displays the data for a product.
This class consists of a single static method named getProduct that returns a
Product object based on the product code that’s passed to it.
The code within the getProduct method starts by creating a Product object.
If you look back to figure 7-5, you’ll see that this causes the code and descrip­
tion fields to be set to empty strings and the price to be set to zero.
After the Product object is created, its setCode method is called to assign
the product code that was passed to the getProduct method to the code field of
this object. Next, the getProduct method uses an if/else statement to determine
what values are assigned to the description and price fields of the Product object
depending on the value of the product code. Notice that the setDescription and
setPrice methods of the Product object are used to set these values. Also notice
that if the product code doesn’t match any of the specified products, this method
sets the description to “Unknown” and it leaves the price at its default value of
zero. Finally, this method returns the Product object.
Because this class doesn’t retrieve the data for a product from a file or
database, it isn’t realistic. However, it does simulate the processing that would
be done by a class like this. In fact, you could use code like this to test the basic
functions of an application before you add the code that works with a file or
database. In section 5 of this book, you’ll learn how to implement a class like
this so it gets the required data from a file or a database.
Chapter 7 How to define and use classes 215

The ProductDB class


public class ProductDB
{
public static Product getProduct(String productCode)
{
// create the Product object
Product p = new Product();

// fill the Product object with data


p .setCode(productCode);
if (productCode.equalsIgnoreCase("java"))
{
p.setDescription("Murach1s Beginning Java");
p.setPrice(49.50);
}
else if (productCode.equalsIgnoreCase("jsps"))
{
p.setDescription("Murach1s Java Servlets and JSP");
p.setPrice(49.50);
}
else if (productCode.equalsIgnoreCase("mcb2"))
{
p.setDescription("Murach1s Mainframe COBOL");
p.setPrice(59.50);
}
else
{
p.setDescription("Unknown");
}
return p;
}
}
Notes
• The ProductDB class provides the database layer that creates a Product object and
gets the data for it from a file or database. In this case, though, the ProductDB class
just simulates the processing that would be done by a database class.
• In a more realistic application, the database class would use the product code to
retrieve the data for a product from a file or database and then fill the Product
object with that data. It would also include methods for adding new products and
for modifying and deleting existing products. You’ll learn how to code classes like
this in section 5.

Figure 7-15 A ProductDB class that returns a Product object


216 Section 2 Object-oriented programming with Java

A ProductApp class that uses a Product object


Figure 7-16 presents a ProductApp class that uses the ProductDB class and
the Product object it creates. As you can tell from the console at the top of this
figure, this application prompts the user for a product code. Then, it retrieves
and displays the description and price of that product.
The ProductApp class shown here contains the main method for the applica­
tion, which means that this method is executed when the application starts. To
make it easy to tell which class of an application contains the main method, it’s
common to add a suffix to the class name. In this book, we use “App” as the
suffix as you’ve seen in all the applications we’ve presented to this point.
The main method in this class is similar to the other ones that you’ve seen.
It uses a loop to retrieve and display the product data for each product code the
user enters. The code that uses the Product class in this loop is highlighted. The
first statement calls the getProduct method of the ProductDB class to create a
Product object named product. Notice here that except for the capitalization, the
object and class have the same name. That’s possible because Java is a case-
sensitive language.
Once the Product object is created and initialized, this program displays the
product’s description and price. To get that information, it calls the
getDescription and getFormattedPrice methods of the Product object.
Chapter 7 How to define and use classes 217

The console
f- ------- *
Welcome to the Product Selector

Enter product code: java

SELECTED PRODUCT
Description: Murach·s Beginning Java
Price: $49.50

Continue? (y/n):
V -------

The ProductApp class


import java.util.Scanner;

public class ProductApp


{
public static void main(String a r g s [])
{
// display a welcome message
System.out.println("Welcome to the Product Selector");
System.out.printlnO ;

// display 1 or more products


Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.print("Enter product code: ");
String productCode = sc.nextO; // read the product code
s c . n e x t L i n e O ; // discard any other data entered on the line

// get the Product object


Product product = ProductDB.getProduct(productCode);

// display the output


System.out.printlnO ;
System.out.println("SELECTED PRODUCT");
System.out.println("Description: " + product.getDescription());
System.out.println("Price: " + product.getFormattedPrice());
System.out.printlnO ;

// see if the user wants to continue


System.out.print("Continue? (y/n): ");
choice = sc.nextLineO;
System.out.printlnO ;
}
}
}

Note
• This class contains the main method that provides the entry point for the Product
application. In this book, we’ve used the suffix “App” to identify this type of class.

Figure 7-16 A ProductApp class that uses a Product object


218 Section 2 Object-oriented programming with Java

How to code and use static fields


and methods
In chapters 2 and 3, you learned how to call static methods from some of
the classes in the Java API. In chapter 4, you learned how to code static methods
in the same class as the main method. Now, you’ll leam how to code static
fields and methods in a separate class and how to call them from other classes.

How to code static fields and methods


Figure 7-17 shows how to code static fields and static methods. While
instance variables and regular methods belong to an object that’s created from a
class, static fields and static methods belong to the class itself. As a result,
they’re sometimes called class fields and class methods.
The top of this figure shows how to code static fields. In short, you use a
syntax that’s similar to the syntax for a regular variable or constant. However,
you use the static keyword so the variable or constant belongs to the class, not
the object. Then, you supply an initial value for the variable or constant. Typi­
cally, the static variables of a class are declared with private access, but the
static constants of a class are declared with public access. That way, other
classes can access and use these constants.
The first example shows how to code a class that contains one static field
and a static method. The static field is a constant that stores the number of
months per year. The static method is similar to the calculateFutureValue
method that you learned how to code in chapter 4. However, this method uses
the static field named MONTHS_IN_YEAR, and it is coded in a separate class
named FinancialCalculations. Note that since this class doesn’t contain any non­
static fields or methods, you don’t need to code a constructor for this class.
The second example shows how you can add a static variable and a static
method to the Product class. In this example, a static variable named
objectCount counts the number of Product objects that are created from the
Product class. This variable is declared as private so no other class can access it
directly. Then, the constructor increments the static variable each time a new
object is created from this class. Finally, the static getObjectCount method
returns the static objectCount variable.
When you code a class that mixes regular fields and methods with static
fields and methods, it’s a good practice to keep your fields and methods orga­
nized. To do that, you can group your fields and methods by type (instance or
static; variable or constant) and by access modifier (private or public). To
illustrate, the second example lists all instance variables in a group, followed by
the single static variable. For small classes, grouping fields and methods like
this isn’t critical. However, as your classes get longer, grouping can make your
code easier to read and maintain.
Chapter 7 How to define and use classes 219

How to declare static fields


private static int numberOfObjects = 0;
private static double majorityPercent = .51;
public static final int D A Y S I N J A N U A R Y = 31;
public static final float E A R T H M A S S I N K G = 5.972e24F;

Example 1: A class that contains a static constant and a static method


public class FinancialCalculations
{
public static final int M O N T H S I N Y E A R = 12;

public static double calculateFutureValue(double monthlyPayment,


double yearlylnterestRate, int years)
{
int months = years * M O N T H S I N Y E A R ;
double monthlylnterestRate = yearlyInterestRate/MONTHS_IN_YEAR/100;
double futureValue = 0;
for (int i = 1; i <= months; i++)
futureValue = (futureValue + monthlyPayment) *
(1 + monthlylnterestRate) ;
return futureValue;
}
}
Example 2: The Product class with a static variable and a static method
public class Product
{
private String code;
private String description;
private double price;

private static int objectCount = 0 ; // declare a static variable

public Product()
{
code = "";
description = "" ;
price = 0;
objectCount++; // update the static variable
}
public static int getObjectCount() // get the static variable
{
return objectCount;
}

Description
• You can use the static keyword to code static fields and static methods. Since static
fields and static methods belong to the class, not to an object created from the class,
they are sometimes called class fields and class methods.
• When you code a static method, you can only use static fields and fields that are
defined in the method. You can’t use instance variables in a static method because
they belong to an instance of the class, not to the class as a whole.

Figure 7-17 How to code static fields and methods


220 Section 2 Object-oriented programming with Java

How to call static fields and methods


Figure 7-18 shows how to call static fields and methods. As you would
expect, you use the same syntax for calling static fields and methods from your
own classes as you would for calling static fields and methods from the Java
API.
To call a static field, you just code the class name, followed by the dot
operator, followed by the field name. To illustrate, the first statement calls the PI
field from the Math class. This field returns a double value for pi, which is the
ratio of the circumference of a circle to its diameter. Then, the second statement
calls the MONTHS_IN_YEAR field from the FinancialCalculations class in the
previous figure.
The third statement shows how to call an objectCount field from the Prod­
uct class. If you declare this static field as public in the Product class, you can
use code like this to directly get or set this int value, which represents the
number of objects that have been created from the Product class. However, if
you declare this static field as private as shown in the previous figure, you can
only use static methods to get or set its value. And if you only declare a get
method, the field is a read-only field.
To call a static method, you code the class name, followed by the dot
operator, followed by the name of the static method and a pair of parentheses.
Within the parentheses, you code the arguments required by the method (if any).
To illustrate, the first statement in the static method examples calls the static
getCurrencylnstance method of the NumberFormat class. This method doesn’t
take any arguments, and it returns a NumberFormat object. The second state­
ment calls the static parselnt method of the Integer class. This method takes a
string argument, converts it to an int value, and returns that value. And the third
statement uses the static pow method of the Math class to return the squared
value of a variable named r.
The fourth statement calls the static calculateFutureValue method from the
FinancialCalculations class described in the previous figure. This method
accepts three arguments and returns the future value that’s calculated based on
the three arguments. Then, the eighth statement calls the static getObjectCount
method of the Product class. This method returns the value stored in the static
objectCount field.
The last statement in this figure shows how you can use both a static field
and a static method in an expression. Here, the value that’s returned by the static
pow method of the Math class is multiplied by the static PI field of the Math
class. Then, the result is assigned to a double variable named area.
Although the examples in this figure call static fields and methods from the
classes that contain them, you can also call a static field or method from an
object created from the class that contains it. For example, you can call the
getObjectCount method from a Product object named product like this:
int productCount = product.getObjectCount();
To make it clear that a field or method is static, however, we recommend that
you always call it from the class.
Chapter 7 How to define and use classes 221

The syntax for calling a static field or method


ClassName.FINAL_FIELD_NAME
ClassName.fieldName
ClassName.methodName(argumentList)

How to call static fields


From the Java API
Math.FI

From a user-defined class


FinancialCalculations.MONTHSINYEAR
Product.objectCount // if objectCount is declared as public

How to call static methods


From the Java API
NumberFormat currency = NumberFormat.getCurrencylnstance();
int quantity = Integer.parselnt(inputQuantity);
double rSquared = Math.pow(r, 2);

From user-defined classes


double futureValue = FinancialCalculations.calculateFutureValue(
monthlyPayment, yearlylnterestRate, years);
int productCount = Product.getObjectCount();

A statement that calls a static field and a static method


double area = Math.PI * Math.pow(r, 2); // pi times r squared

Description
• To call a static field, type the name of the class, followed by the dot operator,
followed by the name of the static field.
• To call a static method, type the name of the class, followed by the dot operator,
followed by the name of the static method, followed by a set of parentheses. If the
method requires arguments, code the arguments within the parentheses, separating
multiple arguments with commas.

Figure 7-18 How to call static fields and methods


222 Section 2 Object-oriented programming with Java

How to code a static initialization block


When it takes more than one statement to initialize a static field, you can
use a static initialization block to initialize the field as shown in figure 7-19. To
start, you just code the static keyword followed by braces. Then, you code the
statements of the block within the braces. The statements in this block are
executed when the class is loaded, which happens when you call one of the
class constructors or static methods.
In the example in this figure, the ProductDB class contains a static initial­
ization block that executes several statements that initialize the static Connec­
tion object. This object is used by some of the static methods in the class to
connect to a database. Since a static initialization block runs as soon as any
method of the class is called, this makes the Connection object available to the
rest of the methods in the class.
For now, don’t worry if you don’t understand the code in the static block.
The point is that it takes several statements to initialize the static Connection
object. You’ll learn more about these statements and how to connect to a data­
base in chapter 21.

When to use static fields and methods


Now that you know how to code static fields and methods, you may wonder
when to use them and when to use regular fields and methods. In general, when