0 ratings0% found this document useful (0 votes) 475 views824 pagesMurach's Java Programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
TRAINING & REFERENCE
murach’s
Java |
programming
Joel Murach
Mike Muracu & Associates, INc.
4340 N. Knoll Ave. + Fresno, CA 93722
.com + murachbooks@murach.comAuthor: 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 SOL Server for Developers
Books for web developers
Murach's HTMLS and CSS:
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 05/390 and /OS ICL
Murach’s Mainframe COBOL
Murach’s CICS for the COBOL Programmer
DB2 for the COBOL Programmer, Part 1
© 2011, Mike Murach & Associates, Ine.
All rights reserved.
Printed in the United States of America
10987654321
ISBN; 978-1-890774-65-3,Contents
Introduction
Section 1 Essential Java skills
Chapter 1 How to get started with Java and NetBeans
Chapter 2 Introduction to Java programming
Chapter 3. How to work with data
Chapter 4 How to code control statements
Chapter 5 How to validate input data
Chapter 6 How to test and debug an application
Section 2 Object-oriented programming with Java
Chapter 7 How to define and use classes
Chapter 8 How to work with inheritance
Chapter 9 How to work with interfaces
Chapter 10 Other object-oriented programming skills
Section 3 More Java skills
Chapter 11 How to work with arrays
Chapter 12 How to work with collections and generies
Chapter 13. How to work with dates and strings
Chapter 14 How to handle exceptions
Section 4 GUI programming with Swing
Chapter 15 How to develop a form
Chapter 16 How to work with controls and handle events
Chapter 17 How to develop and deploy applets
Section 5 Data access programming with Java
Chapter 18 How to work with text and binary files,
Chapter 19 How to work with XML
Chapter 20. How to work with a Derby database
Chapter 21 How to use JDBC to work with a database
Section 6 Advanced Java skills
Chapter 22 How to work with threads
Chapter 23. How to deploy an application
Appendixes
Appendix A How to set up your PC for this book
Appendix B_ How to set up your Mac for this book
xv
AL
145
167
185
237
215
Bll
339
363
405
431
459
501
937
559)
613
645
617
117
751
™
71Expanded contents
Sect
Chapter 1 How to get started with Java and NetBeans
Introduction to Java.
“Toolkits and platforms
How Java compares to C++ and Ci
Applications, applets, and serviets
‘The code for the console version ofthe Future Valve application.
How Java compiles and interprets code
Introduction to Java IDEs
How to use NetBeans to work with existing projects...
Intooduction to Java projects and the NetBeans IDE
How to open, close, and delete a project
How to compile and run a project
How to use the Output window with a console application
How to work with (wo oF more projects
How to use NetBeans to develop new projects .
How to create new projet
How to set the Java version for «projec
Howto work with va source code and files
Howto use the code completion feature
How to detect and correct syntax eors
Chapter 2 Introduction to Java programming
Basic coding skills,
How to code statements
How to code comments
How to ereate identifiers
How to declare a class and a main method
How to work with numeric variables ..
How to declare and initialize variables
How to code assignment statements
How to code arithmetic expressions
How to work with string variables
How to create a Sting object
How to join and append strings,
How to include special characters in
How to use Java classes, objects, and methods
How to create objects and call methods
How to import Java classes
How to use the API documentation to research Java classes
How to use the console for input and output
How to use the System out abject to print output tothe console
How to use the Scanner elass to read input from the console
Examples that get input from the console
How to code simple control statements ..
How to compare numeric variables
How to compare sting variables
How to code ifelse statements
How to code while statementsChapter 3
Chapter 4
Expanded contents
‘Two illustrative applications
Tae Invoice application
The Test Score application
How to test and debug an application
How to test an application
How to debug an application
How to work with data
Basic skills for working with data
The cight primitive datatypes
How to declare and initialize variables
How to declare and initialize constants
How to code assignment statements and arithmes
How to use the shortcut assignment operators
How to work withthe order of precedence:
How to work with casting
How to use Java classes for working with data types
How to use the NumberFormat class
How to use the Math class
How to use the Integer and Double classes
The formatted Invoice application
The code for the application
‘A bug inthe arithmetic
How to debug the application
How to use the BigDe
The constructors and methods
How to use BigDecimal arithmetic
expressions
al class
How to code control statements
How to code Boolean expression
How to compare primitive data types
How to compare stings
How to use the logical operators
How to code if/else and switch statements
How to code ifelse statements
How to code switch statements
‘An enhanced version ofthe Invoice application
How to code loops
How to code while and do-while loops
How to code for loops.
Tne Future Value application
How to code nested loops
How to code break and con
How to code break statements
How to code continue statements
How to code and call static methods ..
How to code static methods
How to call static methods
The Future Value application with a static methodvi
Expanded contents
Chapter 5
Chapter 6
Section 2
Chapter 7
How to validate input data
How to handle exceptions 146
How exceptions work 146
How to catch exceptions 8
‘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 o validate an entry 156
The Future Value application with data validation 158
The console. 158
The code 160
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 im
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 18
Object-oriented programming with Java
How to define and use classes
An introduction to classes
How classes can be used to structuze an application
How encapsulation works
Tae relationship between a class and its objects
How to code a class that defines an object...
How to use NetBeans to create a new class
“The code for the Product class
How to code instance variables
How to code constructors
How to code methods
How to overload methods
How to use the this keyword
How to use NetBeans to work with classes
How to create and use an object
How to create an object
How to call the methods of an abject
How primitive types and reference types are passed to @ method 212
A ProductDB class that creates a Product object
‘A ProductApp clas that uses @ Product abject
How to code and use static fields and methods.
How to code statie fields and methods
How to call stati fields and methods
How to code a static initialization block.
‘When to use static fields and methodsChapter 8
Chapter 9
Expanded contents
‘The Line Item application 224
The console 204
The class diagrams 224
The code for the classes 26
How to work with inheritance
An introduction to inheritance
How inheritance works
How the Java API uses inheritance
How the Odject class works
How to use inheritance in your applications
Basic skills for working with inheritance.
How to create a superclass
How to create a subclass
How polymorphism works
The Product application
The console
The ProductApp class
The Product, Book, and Software classes.
The ProductDB class
More skills for working with inheritance...
How to get information about an abjct’s type
How to cast objects
How to compare objects
How to work with the abstract and
How to work withthe abstract keyword
How to work withthe final keyword
al keywords.
How to work with interfaces
An introduction to interfaces
A simple interface
Interfaces compated to abstzact classes 218
Some interfaces of the Java API
How to work with interfaces.
How to code aa interface
How to implement an interface
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 2
How to use NetBeans to work with interfaces
A Product Maintenance application that uses interfaces
The class diagram
The console
The DAOFactory class
Tre ProductTexiFile class
The ProductMainApp clase
How to implement the Cloneable interface
A Product class that implements the Cloneable interface
A Lineltem class that implements the Cloneable interface
viivil
Expanded contents
Chapter 10
Section 3
Chapter 11
Chapter 12
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 ad 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 fora package 322
How to code classes that are closely related. 324
How to code more than ane clas 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
More Java skills
How to work with arrays
Basic skills for working with arrays 340
How to create an array 340
How to assign values tothe clemeats of an array 342
How to use for loops with arrays 34
How to use enhanced for loops with arrays 346
More skills for working with arrays .. 348
The methods ofthe 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 wit jagged arrays 358
How to work with collections and generics
An introduction to Java collections
‘A comparison of arrays and collections 364
‘An overview of the Java collection framework 366
{An introduction to generics 308
How to use the ArrayList class... 370
‘The ArrayList class 310
Code examples that work with aray lists 372
‘An Invoice application that uses an array list 374
‘An overview of the Invoice application 374
The code for the Invoice class 36
The code for the InvoiceAgp class 318Chapter 13
Chapter 14
Expanded contents
How to use the LinkedList class
The LinkedList cass
Code examples that work with linked lists
‘A class that uses a linked lis to implement a generic queue.
An enhanced version of the Invoice application.
‘An overview of the enbanced Invoice application
The code for the InvoiceApp class
How to work with maps ..
The HashMap and TreeMap classes
Code examples that work with hash maps and tree maps
How to work with legacy collections.
‘An introduction to legacy collection classes
How to use an untyped collection
How to use wrapper classes with untyped collections
How to work with dates and strings
How to work with dates and times
How to use the GregorianCalendar class to set dates and times 405
How to use the Calendar and GregorianCalendar fields and 408
How to use the Date class 410
How to use the DateFormat class to format dates and times 412
‘A DateUuils class that provides methods for handling dates 414
‘An Invoice class that includes an invoice date 416
How to work with the Stri
Constructors of the String class
Code examples that create strings
Methods of the String class
Code examples that work with strings
How to work with the StringBuilder class
Constructors and methods ofthe StringBuilder class
Code examples that work with the StringBuilder class 426
g class
How to handle exce;
An introduction to exceptions 432
The exception hierarchy 432
How exceptions are propagated 434
How to work with exceptions .. 436
How to use the ty statement 436
How to use the try-with-resourees statement 438
How to use the methods of an exception
How to use a multi-catch block
How to use the throws clause
How to use the throw statement
How to work with custom exception classes
How to create your own exception lass
How to use exception chaining
How to work with assertions
How to code assert statements
How to enable and disable assertionsx
Expanded contents
Section 4
Chapter 15
Chapter 16
Chapter 17
GUI programming with Swing
How to develop a form
An introduction to Swing ..
The user interface for the Future Value Calculator application
The inheritance hierarchy for Swing components
How to design a form.
How to create a projet for a GUI application
How to add a form 10 a project
How to add controls to a form
How to set properties
‘Common properties for forms and controls
How to add code to a form
How to set the variable name fora control
How to create an event handler fora control
How to rename or remove an event handler
How to enter the code fora form.
‘Common methods for controls
How to display and center a form
The code for the FutureValueFrame class
How to validate Swing input data ..
How to display error messages
How to validate the data entered into a textfield
‘The SwingValidator class
How to validate maltiple enties
The Future Value application ..
The user interface
The code
How to work with controls and handle events
How to work with components
How to work with text areas
How to work with check boxes
How to work with radio buttons
How to work with combo boxes
How to work with lists
The Payment application
‘The user interface
The code
How to code low-level events
A summary of low
How to work with focus events
How to work with keyboard events
The Product Maintenance application
The user interface
The code
wel events
How to develop and deploy applets
An introduction to applets
‘The Future Value Calculator applet
A brief history of applets
Applet security issues
Tae inheritance hierarchy for applets
Four methods of an applet
460
460
462
464
464
466
468
470
472
47
414
416
478
480
482
484
486
486
488
490
492
494
494
494
502
502
504
506
508
510
514
si4
sid
518
518
520
522
524
524
526
538
538
538
540
542
542Section 5
Chapter 18
Chapter 19
Expanded contents
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 withthe Applet Viewer 546
How to deploy applets 548,
‘A procedure for deploying an applet S48
How to create an HTML document for an applet 550
How to run an applet within a web browser 552
Data access programming with Java
How to work with text and binary fi
Introduction to directories and files ..
A package for working with directories and files 560
Coil examples that work with dretories and files 562
Introduction to file input and output
How files and streams work
file VO example
How to work with UO exceptions
How to work with text files
How to connect a character output steam to a file 510
How to write to a text file 572
How to connect a character input stream toa file 514
How to read from a text fle
‘An interface for working with file /O
A class that works with atext file
How to work with binary files.
How to connect a binary output stream to a file
How to write to a binary file
How to connect a binary input stream to a file
How to read from a binary fle
‘Two ways to work with binary strings
How to work with random-access files
How to connect toa random-access file
How to read to and write from a random-access file 596
How to read and write ixed-length strings 598
A clas that works with a random-access file 600
How to work with XML
Introduction to XML ..
‘An XML document
XML tags, declarations, and comments
XML elements
XML attributes
‘An introduction to DTDs
How to view and edit an XML file.
How to view an XML file
How to edit an XML file
An introduction to three XML APIs.
DoM
SAX
StAX
xixii
Expanded contents
Chapter 20
Chapter 21
How to use StAX to work with XML.
How to create an XMLStreamWriter object
How to waite XML.
How to create an XMLStreamReader abject
How to read XML.
‘A class that works with an XML fle
How to work with a Derby database
How a relational database is organized ..
How a table is organized
How the tables ina database are related
How the columns in database are defined
How to use SQL to work with the data in a database
How to query a single table
How to join data from two oF more tables
How to add, update, and delete data in a table
An introduction to Derby ...
‘An overview of Derby
How to configure your system to work with a Derby database
How to use the ij tool to work with a Derby database ..
How to start and stop the ij tool
How to connect to and disconnect froma database
How to ereate a database and connect to it
How to run SQL statements
How to run SQL scripts from the ij prompt
How to run SQL scripts from the command prompt
How to start and stop the Derby database server
How to start the server
How to stop the server
How to learn more about Derby
How to view the Derby documentation
How to navigate throug the documentation
How to use JDBC to work with databases
An introduction to Java database drivers
“The four driver types.
How to add a database driver to a project
How to use Java to connect to a database.
How to load a database driver.
How to connect to an embedded database
How to disconnect from an embedded database
How to connect to a networked database.
How to use Java to work with a database
How to return a result set
How to move the cursor through a result set
How to zeturn data from a result set
How to modify data in a database.
How to work with prepared statements
‘Two classes for working with databases
A ulility clas for working with strings
‘A class that works with a database
626
626
628
630
632
636
646
646
648
650
652
652
654
656
658
658
660
662
662
662
664
664
666
668
670
670
670
672
on
on
678
618
680
a2
682
684
686
688
690
690
692
694
696
698
700
700
702Section 6
Chapter 22
Chapter 23
Expanded contents
An introduction to working with metadata 708
How to work with metadata 708
How SQL data types map to Java data types no
Advanced Java skills
How to work with threads
An introduction to threads
How threads work 118
Typical uses for threads 718
Classes and interfaces for Working with threads 720
“The life eycle ofa thread m2
How to create threads...
Constructors and methods of the Taread class mA
How to create a thread by extending the Thread class 726
How to create a thread by implementing the Runnable interface 78
How to manipulate threads
How to set a thread’s priority 0
How to interrupt a thread 72
How to synchronize threads
How to create synchronized threads
How to communicate among threads
The Order Queue application
The operation
The classes
The OrderQueueApp class
The Order class
The OrderTaker class
The OrderHandler ciass
The OrderQuuc class
How to deploy an application
An introduction to deployment
How executable JAR files work
How Java Web Start works
How an installer program works
How to use an executable JAR file
How to create an executable JAR file
How to deploy a GUI application
How to deploy a console application
How to use Java Web Start
A procedure for using Java Web Start
How to ereate a INLP file
How to create an HTML document that launches an application 164
How to deploy an application toa remote web server 166
How to launch an application 168
How to fix a common problem 168
xiiiIntroduction
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 reason
First, developers can obtain Java and a wide variety of tools for working
with Java for free. Second, Java code can run on any modern 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 lear 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.
I, for example, you're developing programs using Windows on a PC, you
should know how to use Windows to perform tasks like opening, s:
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
(IDK). 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,7XVI 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 IDK 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. I'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 leam 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 earn 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 lear 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 lear 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 lear how
(o 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 lean how to use an API known as StAX (the Streaming
API for XML) that was introduced with IDK 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
IDBC 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.XVili Introduction
Why you'll learn faster and better with this book
How our downloadable
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.
les 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 (o 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
kelly@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 sec this book as the perfect companion for Murach's Java Servlets and
ISP.
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
xixSection 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
4
6
How Java compares to C++ and C#
Applications, applets, and servlets
‘The code for the console version of the Future Value application 8
How Fava compiles and interprets code 10
Introduction to Java IDEs 2
How to use NetBeans to work with e
Introduction to Java projects and the NetBeans IDE.
How to open, close, and delete project
How to compile and rum a project
How to use the Output window with a console application
How to work with two or more projects
How to use NetBeans to develop new projects.
How to create a new project
How to set the Java version for a project
How to work with Java source code and files
Tow to use the code completion feature
How to detect and correct syntax errors,
Perspective.
ing projectsSection 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
sittce 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
1996 January Sun releases Java Development Kit 1.0 (IDK 1.0).
1997 February Sun releases Java Development Kit 1.1 (IDK 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 (I2EE)
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 teleases JOSE 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#
Syotax Java syntax is similar to CH 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. Currenly, only
Windows has an interpreter for MSIL. C++ code must be compiled
once for each type of system that itis going to be run on,
Speed (CH and C# run faster than Java, but Java is geting 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 (SDR).
+ 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 JavaSection 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 (GUD 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 lear 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
earn 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
ISPs 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,A GUI application and a console application
Moti Payront:
‘Yoarymerest Rat:
unter of Years
ture Vale:
7) Fate Va Calais
[Lemons] [at
Chapter 1 How to get started with Java and NetBeans:
BE Aarinisratar Coneand Prone FutuVaieapp B= LS
Be Bt ew Hee
@rc
Tan ece
erviet
Dena
@-c
Lu
tar tert
[ite ach an noch
‘oar rest
[ie fit Yew Hay, Govimele Teck Up
Ae DD tpn meichsom riinrchi east <2 -) [89 P
ike tah Arsen Pui
ome Books | nia mrs nsincios|Caskomse Sic ay]
The Future Value Calculator serviet
‘The Future Value Calculator applet
ao
Figure 1-2 Applications, applets, and servletsSection 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
entersChapter 1 How to get started with Java and NetBeans:
The code for the Future Value application
import java.util. Scanne:
import java. text .NumberFormat;
public class FutureValueapp
{
public static void main(String[] args)
{
Systen.out.printin("\nWelcone to the Future Value Calculator\n");
Scanner gc = new Scanner (System. in);
String choice = "y";
while (choice
{
squalsTgnorecase (*y"))
// get the input from the user
System.out.print ("Enter monthly investment
double monthlyInvestment = sc.nextDouble()
System.out.print ("Enter yearly interest rate: ");
double interestRate = sc.nextDouble()
System.out.print ("Enter number of year!
int years = se.nextInt();
*)
”;
// calculate the future value
double monthlyInterestRate = interestRate/12/100;
int monthe = years * 12;
double futureValue = calculateFutureValue(
monthlyInvestment, monthlyInterestRate, months) ;
// format and display the result
NumberFormat currency = NunberFormat .getCurrencyInatance();
System.out.printin(*Future value: on
currency. format (futureValue) + "\n*);
// see if the user wants to continue
system.out.print (*Continue? (y/n): *);
choice = sc.next ();
system.out.printin ();
}
private static double calculateFutureValue (double monthlyInvestment,
double monthlyInterestRate, int months)
{
double futurevalue = 0;
for (int i = 1; i <= months; i¢+)
futureValue = (futureValue + monthlyInvestment) *
(1 + monthlytnterestate) ;
return futureValue;
Figure 1-3 The code for the console version of the Future Value application10 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
Thea, you use a Java tool (o 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 14
How Java compiles and interprets code
Java IDE
or
Text editor
source code
(“java files)
Java compiler
bytecodes
lass files)
Java virtual machine
(vm)
Java interpreter
Operating system
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 modern 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 code12 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 modern
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. 18
Popular Java IDEs
NetBeans _A free, open-source IDE that runs on most modern operating systems.
Eclipse A free, open-source IDE that runs on most modern operating systems
Intell IDEA The Community Edition of this IDE is a free, open-source IDE that
runs on most modern operating systems,
SCreator LE The Lite Edition (LE) of this IDE is free, but the code is not open-
souree, and it only runs on Windows.
Bluel ‘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 IDEs14
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
earn 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 (o 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
defaultChapter 1 How to get started with Java and NetBeans 15:
NetBeans with a Java project open
Cate am = ==)
[AMES OC woe - TBD EO
a aaa
[9 B-B-\USSRF es iaale eles
i
|
3) | ee omega y
3 i. ‘i aceite
a Lerwes ‘
fa eeeoas : 4-nan(scsnet} es)
li i Rt ee ee amc mannci I
z ie (amoral
3s i)
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 arc 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 IDE16 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:
€:\murach\java\netbeans\book_apps
To clearly indicate when a folder contains a Java project, the Open Project
dialog box displays a sinall 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. 17
The dialog box for opening a project
Doar
eat: 00k see oo
Poet:
(02 ance
| Open atin Prt
(S801 Iooeeforeated
(pcos Fares
Soot rmresvetvehoe
Bev invce
05 Fratton
(605 Frardevedston
Sos pare
‘Seer retin
eer mod
moet
Flerane: [Gruachipvaetearsback aps nvoce
esotom: rarer
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 File->Open 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
* Torun a project, press F6, use the Run>Run Project command, or click the Run Project
button in the toolbar.
When you num 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 skils for working with existing projects18
Section 1 Essential Java skills
How to use the Output window
with a console applica‘
‘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 19
An application that uses the Output window for input and output
Cxiee eae ao)
B-\VSSMFesiaseuies
eet nner re
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 application20 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 leamed 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 commandChapter 1 How to get started with Java and NetBeans. 24
NetBeans with two open projects
Cam nae tana . ==
JT BP B-O-
= ‘hile (2noLog-equalotgnorecase(“!"))
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.
«Torun 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.
* Ifyou don’t set a main project, you can run any project by selecting that project in
he Projects window and then using standard techniques.
Figure 1-9 How to work with two or more projects22
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:
€:\murach\java\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 ch01_test.ch01_Test, where
“ch01_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
Foes
[gp saltaien
[jp wacutey
[S Sanam srmsoves
[ mareremrope
|
i
|
fees,
peta
—
(rate ane Srv Sf aplctoe a Frc E opt Yu anagram ds
‘roe Stes on DE generated ANEBuld Seton sec
I a
| se ame and Location
Prsectanes [603 en 1
Djentsaten [Surchyneairebst or |
enfoeen gure jpebansbock eee Ta 1
cee cae Tevet
Petar Pont
@roeeraerareneysaarsert ene
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
2324 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 IDK 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 IDK 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 listChapter 1 How to get started with Java and NetBeans:
The Project Properties dialog box
(Chaetrapeie ata Ta
anaes
(Crater da Tet
=I Peptic meadinaetensbak BOs Tat
os
eaten
anaes
strane Fates
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
<< oo na a ST
> tna ‘Sheen
on
2526 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,
Ifthe 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. 27
Net Bean’s code editor with the starting source code for a project
(© 20 ex Neen SS
FEES OE Geiom 7 BD i @-
coon
BO QCM Pe siaaieuias
i116)
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 fora file, use the File>Save command (Curl+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,28 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
ficlds 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
Tused 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 printin 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
Cate ao
BEES OE cero 9 TW DO
7 as] reowme =]
SG-B-QSoR Pee aeu lie
teczz.. |B
eet TT eee
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
Cirl+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. Ifthe 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.
+ Ifyou 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
prime acne ©) wl
fOreist tims 2) =
2930 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 {ext 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 34
The code editor with an error displayed
Ver Se Rehr at he Pile Tem To We He
(SHES 96 woe IT HDG:
ki Testroesava | <
BS-S-\US5RPstiagieuias
ten ons
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 errors32
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 Sofiware Development Kit (SDK) for Java.
* Aso 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 (GUD 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 (EB) of Java, which is known as Java BE, 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 ofthe 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. 88
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_ex1_Invoice. The project should be stored in
this directory
¢:\murach\java\netbeana\ex_starte
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 Fé 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.34
Section 1 Essential Java skills
xercise 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.printin(
"This Java application has run successfully.
d
}
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 printin(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 (o 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 calculatior
and display output.
‘When you finish this chapter, you should be able to write comparable programs
of your own.
Basic coding skills
How to code satements
How to code comments
How to create identifiers
How to declare a class and a main method.
How to work with numeric variables ..
How to declare and initialize variables
How to code assignment statements
How to code arithmetic expressions
How to work with string variables
How to create a String object
How to join and append stings
How to include special character
in strings,
How to use Java classes, objects, and methods
How to create objects and call methods
How to impart Java classes
How to use the APT documentation to research Java classes
How to use the console for input and output
How to use the System out object to print output tothe 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 ..
How to compare numeri variables
How to compate sting variables
How to code itelse statements 4
How to code while statements
‘Two illustrative applications
rhe Invoice application
rhe Test Score application
How to test and debug an application...
How to test an application
How to debug an application
Perspective.36 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 tooChapter 2 Introduction to Java Programming 37
An application consists of statements and comments
import java.util. scanne:
public class Invoiceapp
{
public static void main(string{] args)
{
// display a welcome message
System.out.printin ("Welcome to the Invoice Total Calculator") ;
systen.out.printin(); // print a blank line
// get the input from the user
Scanner sc = new Scanner (Systen. 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 + *\a";
system.out.printin (message) ;
}
}
A block comment that could be coded at the start of a program
i
+ Author: J. Murach
* Purpose: This progran uses the console to get a subtotel fron the user,
: and it calculates the discount amount and total and displays chen.
v
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 (0 as a block of code.
+ To code a single-line comment, type II 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 comments38 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 arc 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 leam how to use almost all of these keywords.Chapter 2 Introduction to Java Programming 39
Valid identifiers
Invoiceapp Sordertotal =i
Invoice orderTotal x
Invoiceapp2 Tnput_string TITLE
subtotal _get_total MONTHS_PER_YEAR
AiscountPercent §_s4_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 fitch while throws
float private ca return native
void Protected break throw implements
short public default = try import
double static for catch synchronized
int new continue finally comet
eng this @o transient goto
abateact super extends instanceof auld
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 (|) 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 leam 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 afier 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 cither
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 itis 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.