Javp ch01
Javp ch01
murach’s
Java
programming
(Chapter 1)
Thanks for downloading this chapter from Murach’s Java Programming. We hope it
will show you how easy it is to learn from any Murach book, with its paired-pages
presentation, its “how-to” headings, its practical coding examples, and its clear, concise
style.
To view the full table of contents for this book, you can go to our web site. From there,
you can read more about this book, you can find out about any additional downloads
that are available, and you can review our other books on Java development.
Thanks for your interest in our books!
"Finally there is a Java book for serious programmers doing real life business
applications."
Donna Dean, IS Trainer, Chicago, Illinois
"I bought your Java book a week ago and I am already writing useful
programs, not ‘toys!’"
Richard Cooper, Programmer
"The absolute best teaching text for Java among the gazillions of self-hyped
tutorials and skills books on the market today."
Posted at Amazon.com
"I love your Java book. It cuts right to the essential information, providing the
perfect balance between too many details and too little information. Example
apps are incredible. Keep up the good work."
Steve, Programmer, Denver, Colorado
"Murach's Java is now my go-to source for reference and learning and
brushing up, well above and beyond the other books in my collection."
Jeff Salter, Sacramento Java Users Group (SacJUG)
"If I’d seen this book first, I would not have wasted money (and time) on 6
other books! This one is highly organized, clear, and very effective as a
learning tool."
Posted at Amazon.com
"The style is clean, very user friendly, and simple. The narrative is totally
accurate and focuses on important issues; it is not dumbed down. This book is
a winner!"
Dr. Richard Wiener, Editor-in-Chief, Journal of Object Technology
iii
Contents
Introduction xv
Section 1 Essential Java skills
Chapter 1 How to get started with Java and NetBeans 3
Chapter 2 Introduction to Java programming 35
Chapter 3 How to work with data 79
Chapter 4 How to code control statements 111
Chapter 5 How to validate input data 145
Chapter 6 How to test and debug an application 167
Section 2 Object-oriented programming with Java
Chapter 7 How to define and use classes 185
Chapter 8 How to work with inheritance 237
Chapter 9 How to work with interfaces 275
Chapter 10 Other object-oriented programming skills 311
Section 3 More Java skills
Chapter 11 How to work with arrays 339
Chapter 12 How to work with collections and generics 363
Chapter 13 How to work with dates and strings 405
Chapter 14 How to handle exceptions 431
Section 4 GUI programming with Swing
Chapter 15 How to develop a form 459
Chapter 16 How to work with controls and handle events 501
Chapter 17 How to develop and deploy applets 537
Section 5 Data access programming with Java
Chapter 18 How to work with text and binary files 559
Chapter 19 How to work with XML 613
Chapter 20 How to work with a Derby database 645
Chapter 21 How to use JDBC to work with a database 677
Section 6 Advanced Java skills
Chapter 22 How to work with threads 717
Chapter 23 How to deploy an application 751
Appendixes
Appendix A How to set up your PC for this book 771
Appendix B How to set up your Mac for this book 777
Chapter 1 How to get started with Java and NetBeans 1
Section 1
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
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.
Java timeline
Year Month Event
1996 January Sun releases Java Development Kit 1.0 (JDK 1.0).
1997 February Sun releases Java Development Kit 1.1 (JDK 1.1).
1998 December Sun releases the Java 2 Platform with version 1.2
of the Software Development Kit (SDK 1.2).
1999 August Sun releases Java 2 Platform, Standard Edition (J2SE).
December Sun releases Java 2 Platform, Enterprise Edition (J2EE).
2000 May Sun releases J2SE with version 1.3 of the SDK.
2002 February Sun releases J2SE with version 1.4 of the SDK.
2004 September Sun releases J2SE 5.0 with version 1.5 of the JDK.
2006 December Sun releases Java SE 6 with version 1.6 of the JDK.
2010 April Oracle buys Sun.
2011 July Oracle releases Java SE 7 with version 1.7 of the JDK.
Description
• Versions 1.2 through 1.4 of Java are called the Software Development Kit (SDK).
• Versions 1.5 through 1.7 of Java are called the Java Development Kit (JDK).
Note
• Java SE 8 with version 1.8 of the JDK is expected to be released late in 2012.
An applet
A servlet
while (choice.equalsIgnoreCase("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 years: ");
int years = sc.nextInt();
Figure 1-3 The code for the console version of the Future Value application
10 Section 1 Essential Java skills
Java IDE
or source code
Text editor (*.java files)
Java compiler
bytecodes
(*.class files)
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.
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.
Description
• A NetBeans project consists of a top-level folder that contains the subfolders and
files for an application.
• The Source Packages subfolder contains the .java files that make up the project.
These files define classes that are later compiled into .class files.
• By default, a project consists of a single class that contains the main method. The
main method is the starting point for the application, and the class that contains it is
called the main class.
• The .java files that make up a project can be organized into one or more packages.
If you don’t specify a package for the main class when you create a project, it’s
stored in the default package.
• The Libraries subfolder contains the libraries that are available to your project.
These libraries contain the Java classes that you can use in your projects. By
default, you can use the classes in the JDK libraries.
• The folders, files, and libraries that make up a Java project are listed in the Projects
window. If this window isn’t visible, you can display it by using the
WindowProjects command. Then, you can expand and collapse the nodes in this
window by clicking on the plus and minus signs.
• You can display and work with the source code in a .java file in the code editor
window. For details, see figure 1-11.
Figure 1-6 Introduction to Java projects and the NetBeans IDE
16 Section 1 Essential Java skills
An application that uses the Output window for input and output
Description
• When you run an application that prints data to the console, that data is displayed
in the Output window.
• When you run an application that requests input from the console, the Output
window pauses to accept the input. Then, you can click in the Output window, type
the input, and press the Enter key.
• In addition to displaying output and accepting input, the Output window can
display other information. For example, it can display messages when the applica-
tion is compiled, and it can display errors that are encountered when an application
is run.
Figure 1-8 How to use the Output window with a console application
20 Section 1 Essential Java skills
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
RunRun Main Project command, or by clicking the Run Main Project button in
the toolbar. The Run Main Project command and toolbar button replace the Run
Project command and toolbar button when a main project is set.
• To run a project other than the main project, right-click on the project and select the
Run command, or right-click on the file that contains the main method you want to
run and select the Run File command.
• If you don’t set a main project, you can run any project by selecting that project in
the Projects window and then using standard techniques.
Description
• To create a new project, use the FileNew 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.
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
26 Section 1 Essential Java skills
Net Bean’s code editor with the starting source code for a project
Description
• To open a .java file in the code editor, double-click on it in the Projects window. Then,
you can use normal editing techniques to work with the source code.
• To collapse the code for a method or comment, click the minus sign (-) to its left. Then,
a plus sign (+) appears to the left of the method or comment, and you can click the plus
sign to display the code again.
• To save the source code for a file, use the FileSave command (Ctrl+S) or click the
Save All Files button in the toolbar. This automatically compiles the file so it doesn’t
have to be compiled when the project is run.
• To rename a file, right-click on it, select the RefactorRename 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
Description
• You can use the code completion feature to help you enter the names of classes and
objects and select from the methods and fields that are available for a class or
object.
• To activate the code completion feature for entering a class or object name, press
Ctrl+Spacebar after entering one or more letters of the class or object name. Then,
a list of all the classes and objects that start with those letters is displayed.
• To activate the code completion feature for a method or field of a class or object,
enter a period after a class or object name. Then, a list of all the methods and fields
for that class or object is displayed.
• To insert an item from a code completion list, select the item and then press the
Enter key. If the item requires parentheses, they’re added automatically. If the item
requires one or more arguments, default values are added for those arguments and
the first argument is highlighted so you can enter its value. Then, you can press the
Tab key and enter the values for any remaining arguments.
• If you enter the opening quote for a string value, the code completion feature
automatically adds the closing quote and places the cursor between the two quotes
so you can enter a value.
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.
Perspective
In this chapter, you were introduced to Java, and you learned how to use
NetBeans to create and run a Java application. With that as background, you’re
ready to learn how to write your own Java applications. But first, I recommend
that you familiarize yourself with NetBeans by doing the exercises at the end
of this chapter.
Summary
• You use the Java Development Kit (JDK) to develop Java applications. This used
to be called the Software Development Kit (SDK) for Java.
• As of version 6, the Standard Edition (SE) of Java is called Java SE. In older
versions, it was called the Java 2 Platform, Standard Edition (J2SE).
• You can use Java SE to create applications (also known as desktop applications)
that run on your computer and a special type of Internet-based application known
as an applet.
• A desktop application can use a graphical user interface (GUI) or a console to
display output and get user input. Applications that use a console to interact with
the user are known as console applications.
• You can use the Enterprise Edition (EE) of Java, which is known as Java EE, to
create server-side applications using servlets and JavaServer Pages (JSPs).
• The Java compiler translates source code into a platform-independent format
known as Java bytecodes.
• Any machine that has a Java interpreter installed on it can be considered an
implementation of a Java virtual machine (JVM).
• An Integrated Development Environment (IDE) such as NetBeans can make
working with Java easier.
• In NetBeans, a project is a folder that contains all of the files that make up an
application.
• Java code is stored in classes. To organize multiple classes, you can store them in
packages.
• The main class of an application is the class that contains the main method, which
is the starting point of the application.
• If an application prints text to the console, NetBeans displays the text in the Output
window. NetBeans also allows you to enter input into the Output window.
• When multiple projects are open, NetBeans identifies the main project by
boldfacing its name in the Projects window.
• You can use the NetBeans code editor to enter and edit code. As you enter code,
you can use the code completion feature to help you enter the names of classes and
objects and select from fields and methods.
Chapter 1 How to get started with Java and NetBeans 33
3. Modify the generated code for the TestApp class so it looks like this (type
carefully and use the same capitalization):
public class TestApp
{
public static void main(String[] args)
{
System.out.println(
"This Java application has run successfully.");
}
}
4. Press F6 to compile and run the application. This should display “This Java
application has run successfully.” in the Output window.
Use the code completion feature
5. Enter the statement that starts with System.out again, right after the first
statement. This time, type “sys” and then press Ctrl+Spacebar. Then, use the
code completion feature to select the System class, and complete the
statement.
6. Enter this statement a third time, right after the second statement. This time,
type System, enter a period, and select out from the list that’s displayed. Then,
enter another period, select println(String x), and complete the statement. You
should now have the same statement three times in a row.
7. Run the application again to see that the message is displayed three times in a
row in the Output window.
Introduce and correct a syntax error
8. In the code editor window, delete the semicolon at the end of the first println
statement, and NetBeans will display an error icon to the left of the statement.
9. Correct the error, and NetBeans will remove the error icon.
10. Use the FileSave command (Ctrl+S) to save the changes.
How to build your
Java programming skills
The easiest way is to let Murach’s Java Programming be
your guide! So if you’ve enjoyed this chapter, I hope you’ll
get your own copy of the book today. And don’t miss its
companion text for web programming, Murach’s Java
Servlets and JSP. You can use both books to:
· Teach yourself how to code desktop and web applications
in Java
· Take advantage of all the time- and work-saving features Mike Murach, Publisher
· Pick up a new skill whenever you want or need to by focusing on material that’s
new to you
· Look up coding details or refresh your memory on forgotten details when you’re
in the middle of developing a Java application
· Loan to your colleagues who will be asking you more and more questions about
Java programming
To get your copy of either or both books, you can order online at www.murach.com
or call us at 1-800-221-5528 (toll-free in the U.S. and Canada). And remember, when
you order directly from us, this book comes with my personal guarantee:
100% Guarantee