Pages

Wednesday, November 14, 2012

JAVA 1

Chapter 1 How to get started with Java 1
Section 1
The essence of
Java programming
The best way to learn Java programming is to start doing it, and that’s the
approach the chapters in this section take. So in chapter 1, you get started right
as you learn how to get Java on your system and how to compile and run Java
programs. Then, in chapters 2 and 3, you learn how to use the Java language
essentials as you write your first Java applications. At this point, you’re using
some of the basic Java classes and objects, but you’re not writing objectoriented
programs.
To develop programs the way the professionals do, however, you need to
write object-oriented programs. So that’s what you’ll learn how to do in the
next two chapters. In chapter 4, you learn how to write programs that consist
of two or more classes. In chapter 5, you are introduced to all of the objectoriented
concepts and skills that you need as you work with Java. These are
useful as you create and use your own classes and objects, and they are
absolutely essential for making effective use of the hundreds of classes that
Java provides.
Before you can write an effective object-oriented program, though, you
need to know how to design and test an object-oriented program. So that’s
what you’ll learn to do in the last chapter of this section. When you complete
it, you’ll have the essential skills that you need for designing, coding, and
testing object-oriented Java programs. You’ll also have a clear view of what
Java programming is and what you have to do to become proficient at it. That’s
why we call this section “The essence of Java programming.”
Mike Murach & Associates
2560 West Shaw Lane, Suite 101
Fresno, CA 93711-2765
(559) 440-9071 • (800) 221-5528
murachbooks@murach.com • www.murach.com
Copyright © 2002 Mike Murach & Associates. All rights reserved.
Chapter 1 How to get started with Java 3
1
How to get started with
Java
Before you can begin learning the Java language, you need to install Java and
you need to learn how to use some tools for working with Java. So that’s what
you’ll learn in this chapter. Along the way, you’ll be introduced to some of the
concepts and terms you need for working with Java.
Introduction to Java .............................................................. 4
Toolkits and platforms ..................................................................................... 4
Java compared to C++ .................................................................................... 4
Applications, applets, and servlets ................................................................. 6
How Java compiles and interprets code .......................................................... 8
How to get Java on your system ....................................... 10
How to install the SDK ................................................................................. 10
A summary of the directories and files of the SDK ..................................... 12
How to configure Windows to work with the SDK ...................................... 14
How to use Windows tools to work with Java .................. 16
How to use Notepad to save and edit source code ........................................ 16
How to use the DOS prompt to compile source code .................................. 18
How to use the DOS prompt to run an application ...................................... 18
Common error messages and solutions ........................................................ 20
Essential DOS skills for working with Java ................................................. 22
How to use TextPad to work with Java .............................. 24
How to use TextPad to save and edit source code ........................................ 24
How to use TextPad to compile source code ................................................ 26
How to use TextPad to run an application .................................................... 26
Introduction to Java IDEs ................................................... 28
Why we don’t recommend using an IDE when you’re learning Java .......... 28
Why we recommend using an IDE once you’ve mastered Java ................... 28
Perspective .......................................................................... 30
4 Section 1 The essence of Java programming
Introduction to Java
In 1996, Sun Microsystems released a new programming language called
Java. This language had some unique features that gave it great promise as a
language that could be used on all platforms for all types of applications. In the
three figures that follow, you’ll learn more about this language, its features, and its
applications.
Toolkits and platforms
Figure 1-1 describes all major releases of Java to date starting with version
1.0 and ending with version 1.4. As you can see, Sun referred to versions 1.0 and
1.1 of the Java toolkit as the Java Development Kit (JDK). With version 1.2,
however, Sun began using the term Software Development Kit (SDK) to describe
the Java toolkit. In practice, these two terms are often used interchangeably. In
this book, we’ll use the term SDK since it’s the most current term.
All versions of the SDK since version 1.2 are referred to as Java 2 because
they all run under the Java 2 Platform. This book will show you how to use the
Java 2 Platform, Standard Edition (J2SE). Once you master the Standard Edition,
you will have all the skills you need to begin learning how to use the Java 2
Platform, Enterprise Edition (J2EE). In fact, many of the same skills apply to
both editions.
One reason that Java has become so widely used is that it can create programs
that can run on any of the operating systems shown in this figure. In addition, Java
programs can also be run under the Macintosh operating system. You’ll learn
more about the details of how this works later in this chapter.
Java compared to C++
When Sun’s developers created Java, they tried to keep the syntax for Java
similar to the syntax for Microsoft C++ so it would be easy for C++ programmers
to learn Java. That’s one of the four features that are used for comparing Java and
C++ in this figure.
The second feature is one of the most touted Java features. Specifically, Java
is designed so its applications can be run on any computer platform. In contrast,
C++ needs to have a specific compiler for each platform that its applications are
going to run on. You’ll learn more about this in figure 1-3.
The third feature, though, indicates one of the weaknesses of Java. Specifically,
the speed (or performance) of its applications is often considerably slower
than the speed of traditional applications. In fact, this is an issue that limits the use
of Java for some types of applications.
The fourth feature has to do with the use of internal memory. Specifically,
Java is easier to use than C++ because it handles many operations involving the
creation and destruction of memory automatically. This also makes it easier to
write bug-free code.
Chapter 1 How to get started with Java 5
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.
Operating systems supported by Sun
• Win-32 (Windows NT, Windows 95, Windows 98, Windows 2000, Windows ME, and
Windows XP)
• Solaris (SPARC or Intel platform)
• Linux
Java compared to C++
Feature Description
Syntax Since Sun wanted to make Java easy to learn for C++ programmers, they made the syntax
similar to the syntax for C++.
Platforms After a Java program has been compiled, it can be run on any platform that has a Java
interpreter (see figure 1-3). In contrast, a C++ program needs to be compiled once for each
type of system that it is going to be run on.
Speed C++ runs faster than Java, partly because it is compiled for a specific platform, but Java is
getting faster with each new version.
Memory Since most memory operations are handled automatically by Java, it’s easier to write bug-free
code with Java than it is with C++.
Description
• Versions 1.0 and 1.1 of the Java toolkit were called the Java Development Kit, or JDK.
• Versions 1.2 through 1.4 of the Java toolkit are called the Software Development Kit, or
SDK.
• The Java 2 Platform, Standard Edition, or J2SE, supports versions 1.2 through 1.4 of the
SDK.
• The Java 2 Platform, Enterprise Edition, or J2EE, can be used to create enterprise-level,
server-side applications.
Figure 1-1 Introduction to Java
6 Section 1 The essence of Java programming
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. This figure shows an application
that uses a graphical user interface, or GUI, to get user input and perform
a calculation. In this book, you’ll be introduced to a variety of applications
with the emphasis on GUI applications that get data from files and databases.
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 application 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. After you master the
basics of building GUI applications, chapter 15 shows you how to create
applets.
The Enterprise Edition of the Java 2 Platform can be used to create a special
type of server-side application known as a servlet. Servlets can access enterprise
databases and make that data available via the web. Since servlets are an
advanced subject, they aren’t presented in this book.
Chapter 1 How to get started with Java 7
An application
An applet
Description
• An application is a program that runs in a window. The application shown above uses a
graphical user interface, or GUI, to get input and display output.
• An applet is a special type of program that runs within a web browser after it has been
retrieved from the Internet or an intranet. You’ll learn how to create applets in chapter 15.
• A servlet is a special type of program that does server-side processing.
Figure 1-2 Applications, applets, and servlets
8 Section 1 The essence of Java programming
How Java compiles and interprets code
Figure 1-3 shows how Java compiles and runs an application. To start, you
can use any text editor to enter and edit Java source code. 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 platform 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, or JVM.
To enhance the platform independence of Java, some web browsers like
Netscape and the Internet Explorer are Java-enabled. In other words, these
browsers contain Java interpreters. This allows applets, which are bytecodes that
are downloaded from the Internet or an intranet, to run within a web browser.
The problem with this is that both Netscape and the Internet Explorer only
support older versions of the Java interpreter. In addition, Netscape and the
Internet Explorer support slightly different subsets of the Java language. To
solve this problem, Sun has developed a tool known as the Java plug-in, which
lets the user upgrade the interpreter to a later version. This makes it possible to
develop applets that take advantage of the latest features of Java, but this works
better for intranet applications than Internet applications. You’ll learn more
about this in chapter 15.
Chapter 1 How to get started with Java 9
How Java compiles and interprets code
Description
• Any text editor can save and edit the source code for a Java application. Source code
files use the java extension.
• The Java compiler translates source code into a platform-independent format known as
Java bytecodes. Files that contain Java bytecodes use the class extension.
• The Java interpreter executes Java bytecodes. Since Java interpreters exist for all major
operating systems, Java bytecodes can be run on most platforms. Any computer with a
Java interpreter can be considered an implementation of a Java virtual machine (JVM).
• Some web browsers like Netscape and the Internet Explorer contain Java interpreters.
This lets applets run within these browsers. However, both Netscape and the Internet
Explorer only provide older versions of the Java interpreter.
• Sun provides a tool known as the Java plug-in that allows the Netscape and Internet
Explorer browsers to use the most current version of the Java virtual machine.
Figure 1-3 How Java compiles and interprets code
source code
(*.java files)
bytecodes
(*.class files)
Text editor Java compiler Java interpreter
Java virtual machine (JVM)
Operating system
10 Section 1 The essence of Java programming
How to get Java on your system
Before you can start to use Java, the SDK must be installed on your system.
In addition, your system may need to be configured to work with the SDK. If
Java isn’t already installed and your system isn’t already configured, you can
use the next three figures to make sure it is. Then, you’ll be ready to create your
first Java application. Even if Java is already installed on your system, though,
you should read the summary of files and directories that are part of the SDK.
How to install the SDK
Figure 1-4 shows how to install version 1.4 of the SDK. If you’re using
Windows, the easiest way to do that is to use the CD that comes with this book.
Just navigate to the directory that holds the Windows SDK and run the setup
file. Then, respond to the resulting dialog boxes. However, if you want to install
a different version of Java, you can download that version from the Java web
site as described in this figure.
Since Sun is continually updating the Java web site, the procedure shown in
this figure may not be up-to-date by the time you read this. As a result, you may
have to do some searching to find the current version of the SDK. In general,
you can start by looking for products for the Java 2 Platform, Standard Edition.
Then, you can find the most current version of the SDK for your operating
system.
Chapter 1 How to get started with Java 11
The Java web site address
www.java.sun.com
How to download and install the SDK from the Java web site
1. Go to the Java web site.
2. Locate Java products and find the Java 2 Platform, Standard Edition.
3. Go to the download page for the most current SDK version that’s available for your
platform.
4. After clicking on the download button, follow the instructions. Note the name of the file
and the download size.
5. Select one of the FTP download options, unless you’re behind a firewall and you need to
use the HTTP option.
6. Save the setup file to your hard disk. On a 56K modem, it takes about 2 hours to download
this file.
7. Once the entire package has downloaded, check to make sure that you got the executable
and that the size is correct. Otherwise, you will get an error when you try to run the
executable.
8. Run the exe file, and respond to the resulting dialog boxes. When you’re prompted for
the SDK directory, use the default directory and install all of the components unless disk
space is a problem.
How to install the Windows SDK from the CD that comes with this book
1. Put the CD that comes with this book into your CD drive, and navigate to the
WindowsSDK directory. (If you want to use some other platform, you need to download
it from the Java web site.)
2. Double-click on the exe file, and respond to the resulting dialog boxes. When you’re
prompted for the SDK directory, use the default directory. Then, install all of the components
unless disk space is a problem.
Figure 1-4 How to install the SDK
12 Section 1 The essence of Java programming
A summary of the directories and files of the SDK
Figure 1-5 shows the directories and files that are created when you install
the SDK. Here, the SDK is stored in the c:\j2sdk1.4.0 directory. By default, this
directory has five subdirectories: bin, demo, include, jre, and lib.
The bin directory holds all the tools necessary for developing and testing a
program including the Java compiler. The demo directory contains many sample
applications and applets. You can browse through these to learn more about
what Java can do, and you can review the source code. The include directory
holds header files for the C programming language that allow you to incorporate
C code into a Java program.
The jre directory contains the Java interpreter, or Java Runtime Environment
(JRE), that’s needed to run Java applications once they’ve been compiled.
Although the SDK uses this internal version of the JRE, you can also download
a standalone version of the JRE from the Java web site. Once you’re done
developing a Java application, for example, you can distribute the standalone
JRE to other computers so they can run your application. The lib directory
contains libraries and support files required by the development tools.
The last directory is the docs directory, which is used to store the Java
documentation. In chapter 3, you’ll learn how to download and install this
documentation.
In the j2sdk1.4 .0 directory, you can find two readme files that contain much
of the information that’s presented in this figure as well as more technical and
detailed information about the SDK. You can view the HTML file with a web
browser, and you can open the text file with a text editor.
The j2sdk1.4 .0 directory also contains the src.zip file. This file holds the
source code for the SDK. Before you can view the source code, though, you
must extract the files that contain the source code from this ZIP file.
When you work with Windows, you’ll find that it uses the terms folder and
subfolder to refer to DOS directories and subdirectories. For consistency,
though, we use the term directory throughout this book. In practice, these terms
are often used interchangeably.
Chapter 1 How to get started with Java 13
The file structure of the SDK
The subdirectories of the SDK
Directory Description
bin The Java development tools and commands
demo Sample applications and applets with source code
include C header files for combining C code with Java code
jre The root directory of the Java Runtime Environment (JRE)
lib Additional libraries of code that are required by the development tools
docs (optional) The online documentation that you can download (see chapter 3)
The files of the SDK
File Description
readme.html An HTML page that provides information on Java 2, including system requirements,
features, and documentation links
readme.txt The text version of the readme.html file
src.zip A file containing the source code for the SDK
Description
• The Java Runtime Environment, or JRE, is the Java interpreter that allows you to run
compiled programs in Java. The jre directory is an internal copy of the runtime environment
that works with the SDK. You can also download a standalone version of the JRE
for computers that don’t have the SDK installed on them.
Figure 1-5 A summary of the directories and files of the SDK
14 Section 1 The essence of Java programming
How to configure Windows to work with the SDK
Figure 1-6 shows you how to configure Windows to make it easier to work
with the SDK. If you’re not using Windows, you can refer to the Java web site
to see what you need to do to configure Java for your system.
To configure Windows to work with the SDK, you need to add the bin
directory to the command path. That way, Windows will know where to look to
find the Java commands that you use.
One way to update the path for Windows 95, 98, or ME is to use the first
procedure in this figure to edit the Path or Set Path command in the
autoexec.bat file. This is the file that is automatically executed every time you
start your computer. After you edit the file, you can restart your computer to run
the autoexec.bat file and establish the new path. Then, you can enter path or set
at the command prompt to make sure that the bin directory is now in the command
path.
When you edit the autoexec.bat file, be careful! Since this file may affect
the operation of other programs on your PC, you don’t want to delete or modify
any of the commands that this file contains. You only want to add one directory
to the command path. If that doesn’t work, be sure that you’re able to restore the
autoexec.bat file to its original condition.
If you’re using a later version of Windows, you can use the second procedure
in this figure to set the command path. It is easier to use with less chance
that you’ll do something that will affect the operation of other programs.
If you don’t configure Windows in this way, you can still compile and run
Java programs, but it’s more difficult. In particular, you need to enter the
complete path for each command. For instance, you need to enter
\j2sdk1.4.0\bin\javac
instead of just
javac
to run the javac command that’s stored in the c:\j2sdk1.4.0\bin directory. If you
understand DOS, you should understand how this works.
To configure Windows to work with Java classes, you can set the classpath.
That way, Java will know where to look to find Java classes. By default, the
classpath for a Windows system includes the current directory, which is all you
need to run the programs included with this book. However, if your system is
using a classpath that doesn’t specify the current directory, you’ll need to add
the current directory to the classpath. To do that, you can follow a similar
procedure that you used to modify the path. However, you can modify the
classpath instead of the path. To specify the current directory, you use a period
(.). For example, here’s a classpath setting that includes the c:\murach\classes
directory and the current directory
CLASSPATH=c:\murach\classes;.;
Like the path setting, you must use a semicolon to separate each directory.
Chapter 1 How to get started with Java 15
A typical Path statement in the autoexec.bat file
How to set the path for Windows 95/98/ME
1. Start the Windows Explorer and navigate to the autoexec.bat file, which should be
stored in the root drive (c:\autoexec.bat).
2. Right-click on the autoexec.bat file and select the Edit command. This should open the
file in a text editor.
3. If the file contains a Path or Set Path command, type a semicolon at the end of the
command. Then, type “c:\j2sdk1.4.0\bin” as shown above. If the file doesn’t contain a
Path or Set Path command, enter “path=c:\j2sdk1.4.0\bin” at the beginning of the file.
4. Save the file and exit the text editor.
5. To have the new path take effect, you can restart your computer (which runs the
autoexec.bat file).
How to set the path for Windows 2000/NT/XP
1. Go to the Start menu, point to Settings, and select the Control Panel.
2. Edit the environment variables for your system. For NT, select the System icon, and the
Environment tab. For 2000, select the System icon, the Advanced tab, and the Environment
Variables button. For XP, select the Performance and Maintenance icon, the
System icon, the Advanced tab, and the Environment Variables button.
3. Add c:\j2sdk1.4.0\bin to the far right side of the current path in System Variables and
select OK.
How to check the current path and classpath
• Start a DOS prompt and enter the set command. When you do, the DOS window will
display various configuration data including the path and classpath.
When and how to modify the classpath
• If your system doesn’t have a classpath, the default classpath will allow you to run all of
the programs described in this book. As a result, you won’t need to modify the
classpath. However, if your system has a classpath that doesn’t include the current
directory, which is specified by a period (.), you need to add the current directory to the
classpath.
• To modify the classpath, follow the procedure shown above for modifying the path, but
modify the classpath command instead. When you do, make sure that the current
directory is included in the classpath.
Description
• For more information about configuring your system, or for information about configuring
non-Windows operating systems, you can refer to the Java web site.
Figure 1-6 How to configure Windows to work with the SDK
16 Section 1 The essence of Java programming
How to use Windows tools to work
with Java
Once the SDK is installed on your computer and configured for your
operating system, you’re ready to create your first application. Since most Java
programmers use Windows, you will now learn how to use the Windows tools
for compiling and running Java programs. In particular, you will learn how to
use Notepad for entering and editing a program and the DOS prompt for compiling
and testing it.
This will give you the general idea of how a Java program is developed on
any platform. Then, if you’re using another operating system, you can learn
similar procedures for developing programs on that system.
Note, however, that this chapter will soon show you how to use a product
named TextPad for entering, compiling, and running Java programs on a Windows
system. Since this is simpler than using Notepad and DOS commands and
since TextPad is included on the CD for this book, we recommend that you use
TextPad as you develop the programs for this book. As a result, you should read
the procedures that follow primarily for the perspective that they give. Later, if
you actually need to use these procedures, you can refer back to them for
specific details.
How to use Notepad to save and edit source code
Figure 1-7 shows how to use the Notepad text editor to save and edit the
source code for an application. After you start Notepad, you can enter and edit
the code just as you would with any text editor. However, saving a source code
file can be tricky for two reasons.
First, you must use the four-letter java extension. Second, since Java is a
case-sensitive language, you must save the file with the proper capitalization. If
the capitalization of the filename doesn’t match the capitalization of the class
name that’s used in the Java code, you’ll get an error message when you try to
compile the code. In this figure, you can see that “BookOrderApp” is used in
both the code and the filename.
To make sure you get the capitalization and the java extension right, you
should enclose the filename in quotation marks as shown in this figure. Otherwise,
Notepad may truncate the extension to jav or change the capitalization in
the filename. Either way, you’ll get errors when you try to compile the source
code.
In addition, you must save the source code in a standard text-only format
such as the ASCII format or the ANSI format. Since Notepad only supports
ASCII, you can’t go wrong when you’re using Notepad. If, however, you’re
using a text editor or word processor that supports other formats, you’ll need to
make sure that you save the file in one of these standard text-only formats.
Chapter 1 How to get started with Java 17
The Notepad text editor with source code in it
The bottom part of Notepad’s Save As dialog box
Syntax to save the code in a file
"ProgramName.java"
Typical capitalization for file names
Book.java
BookOrderApp.java
Operation
• To start Notepad, click on the Start menu, select Programs, select Accessories, and select
Notepad.
• To enter or edit code, use the same techniques that you use with any other text editor or
word processor.
• To save the source code, select the Save command from the File menu and enter the
filename within quotation marks. That way, the file will be saved with the capitalization
that you’ve used and with the java extension. Otherwise, the capitalization may be
changed or the extension may be truncated to jav. (On some versions of Windows, the
quotation marks may not be necessary, so you may want to experiment with this.)
Figure 1-7 How to use NotePad to save and edit source code
18 Section 1 The essence of Java programming
How to use the DOS prompt to compile source
code
Figure 1-8 shows how to use the DOS prompt, or command prompt, to
compile and run applications. To start, you should use the change directory (cd)
command to change the current directory to the directory that holds the application.
In this figure, for example, you can see that the directory has been changed
to c:\java\ch01 because that’s the directory that the BookOrderApp.java file is
stored in.
Then, to compile an application, you use the javac command to start the
Java compiler. When you enter the javac command, you follow it by a space and
the complete name of the *.java file that you want to compile. Here again,
because Java is case-sensitive, you need to use the same capitalization that you
used when you saved the *.java file.
If the application doesn’t compile successfully, the Java compiler will
display one or more error messages. Usually, you can get an idea of what
caused each error by reading its message. Then, you can use Notepad to correct
and resave the *.java file, and you can compile the program again. Since this
means that you’ll be switching back and forth between Notepad and the DOS
prompt, you’ll want to leave both windows open.
When you compile an application successfully, the Java compiler will create
a *.class file that has the same filename as the *.java file. For example, a
successful compilation of the BookOrderApp.java file will create the
BookOrderApp.class file.
How to use the DOS prompt to run an application
To run a program, you use the java command to start the Java interpreter.
Although you need to use the proper capitalization when you use the java
command, you don’t need to include an extension for the file. When you enter
the java command correctly, the Java interpreter will run the *.class file for the
application.
Most of the time, running a Java program will display a graphical user
interface like the one shown in figure 1-2. However, you can also print information
to the DOS prompt, which in that case is called the console. For example,
the BookOrderApp file in this figure prints a single line of text to the console.
When an application ends properly, you will be returned to the DOS
prompt. Then, you can enter another command. If an application doesn’t end
properly, though, you can press Ctrl+C to cancel the execution of the program
and return to the DOS prompt.
Chapter 1 How to get started with Java 19
The commands for compiling and running an application
Syntax to compile an application
javac ProgramName.java
Syntax to run an application
java ProgramName
Description
• The DOS prompt, or command prompt, is the prompt that indicates that the operating
system is waiting for the next command. When you use DOS, this prompt usually shows
the current directory, and it always ends with >. In the example above, the last line is the
command prompt, which shows that the current directory is c:\java\ch01.
Operation
• To open the DOS Prompt window with Windows 95, 98 or NT, click on the Start button,
select Programs, and select MS-DOS Prompt. With Windows 2000, ME, or XP, click on
the Start button, select Accessories, and select Command Prompt.
• To change to the directory that contains the file with your source code, use the change
directory command (cd) as shown above.
• To compile the source code, enter the Java compile command (javac), followed by the
filename (including the java extension).
• If the code compiles successfully, the compiler generates another file with the same
name, but with class as the extension. This file contains the bytecodes.
• If the code doesn’t compile successfully, the java compiler will generate error messages.
Then, you must switch back to your text editor, fix the errors, save your changes, and try
compiling the program again.
• To run the compiled version of your source code, enter the Java command (java), followed
by the program name without any extension. Since this is a case-sensitive command,
make sure to use the same capitalization that you used when naming the file.
Note
• The code shown in the DOS Prompt window above will only work if c:\j2sdk1.4.0\bin
has been added to the command path as shown in figure 1-6. If the code compiles but
doesn’t execute, you may need to edit your classpath setting as shown in figure 1-6.
Figure 1-8 How to use the DOS prompt to compile and run an application
20 Section 1 The essence of Java programming
Common error messages and solutions
Figure 1-9 summarizes some common error messages. The first two errors
illustrate compile-time errors. These are errors that occur when the Java compiler
tries to compile the program. In contrast, the third error illustrates a runtime
error. That is an error that occurs while the Java interpreter is trying to run
the program.
The first error message in this figure involves a syntax error. When the
compiler encounters a syntax error, it prints two lines for each error. The first
line prints the name of the *.java file, followed by a colon, followed by the line
number for the error, followed by a brief description of the error. The second
line prints the code that caused the error including a caret character that tries to
identify the location where the syntax error occurred. In this example, the
syntax error is that a semicolon is missing at the end of the line.
The second error message in this figure involves a problem defining the
public class for the file. The compiler displays an error message like this when
the filename for the *.java file doesn’t match the name of the public class
defined in the source code. For example, a *.java file that defines a class named
BookOrderApp must contain this code
public class BookOrderApp{
and this file must be saved as BookOrderApp.java. If the name of the file
doesn’t match the name of the public class (including capitalization), the
compiler will give you an error like the one shown in this figure. You’ll learn
more about the syntax for defining a public class in the next chapter.
The third error message in this figure occurs if you enter the wrong name
after the java command. If, for example, you enter “bookorderapp” after the java
command, you’ll get an error like this. That’s because the capitalization for the
class isn’t correct. If, on the other hand, you enter “BookOrderApp.class” after
the java command, you’ll get a similar error. That’s because you shouldn’t
include the extension when you use the java command.
Most of the time, the information displayed by an error message will give
you an idea of how to fix the problem. Sometimes, though, the compiler doesn’t
give you accurate error messages. In that case, you’ll need to double-check all
of your code. You’ll learn more about debugging error messages like these as
you progress through this book.
Chapter 1 How to get started with Java 21
A common error message
Two common compile-time error messages and solutions
Error: BookOrderApp.java:3: ';' expected
System.out.println("Title: War and Peace")
^
Description: The first line in this error message displays the filename of the *.java file, a
number indicating the line where the error occurred, and a brief description
of the error. The second line displays the line of code that may have caused
the error with a caret symbol (^) below the location where there may be
improper syntax.
Solution: Use a text editor to correct the problem and save the file.
Error: BookOrderApp.java:1: class BookOrder is public, should be
declared in a file named BookOrder.java
public class BookOrder{
^
Description: The *.java filename doesn’t match the name of the public class. Remember,
you must save the file with the same name as the name that’s coded after the
words “public class”. In addition, you must add the java extension to the
filename.
Solution: Enter the correct filename after the javac command. Or, use the text editor to
save the java file with the proper spelling and capitalization.
A common run-time error message and solution
Error: Exception in thread "main"
java.lang.NoClassDefFoundError:
bookorderapp (wrong name: BookOrderApp)
Description: The name that was entered for the *.class file isn’t correct. Remember, you
must use the proper capitalization and you must omit the class extension.
Solution: Enter the correct name after the java command. You can use the dir command
to check the capitalization for the file as shown in the next figure. If necessary,
you may need to use the javac command to recreate the *.class file from
the *.java file.
Figure 1-9 Common error messages and solutions
22 Section 1 The essence of Java programming
Essential DOS skills for working with Java
Figure 1-10 summarizes some of the most useful commands and keystrokes
for working with DOS. In addition, it shows how to install and use a DOS
program called DOSKey, which makes entering and editing DOS commands
easier. If you’re going to use DOS to work with Java, you should review these
DOS commands and keystrokes, and you will probably want to turn on the
DOSKey program. If you aren’t going to use DOS, of course, you can skip this
figure.
At the top of this figure, you can see a DOS Prompt window that shows two
DOS commands and a directory listing. In this window, the first command
changes the current directory to c:\java\ch01. The next command displays a
directory listing. If you study this listing, you can see that this directory contains
two files with one line of information for each file. At the right side of each line,
you can see the complete filenames for these two files (BookOrderApp.java and
BookOrderApp.class), and you can see the capitalization for these files as well.
If you master the DOS commands summarized in this figure, you should be
able to use DOS to work with Java. To switch to another drive, type the letter of
the drive followed by a colon. To change the current directory to another
directory, use the cd command. To display a directory listing for the current
directory, use the dir command. To return to the DOS prompt when an application
hasn’t ended properly, press Ctrl+C. Although DOS provides many more
commands that let you create directories, move files, copy files, and rename
files, you can also use the Windows Explorer to perform those types of tasks.
Although you don’t need to use the DOSKey program, it can save you a lot
of typing and frustration. If, for example, you compile a program and you
encounter a syntax error, you will need to use a text editor to fix the error in the
source code. Then, you will need to compile the program again. If you’re using
DOSKey, you can do that by pressing the up-arrow key to display the command
and by pressing the Enter key to execute the command. And if you make a
mistake when entering a command, you can use the left- and right-arrow keys to
edit the command instead of having to enter the entire command again.
Chapter 1 How to get started with Java 23
A directory listing
A review of DOS commands and keystrokes
Command Description
dir Displays a directory listing.
dir /p Displays a directory listing that pauses if the listing is too long to fit on one screen.
cd \ Changes the current directory to the root directory for the current drive.
cd .. Changes the current directory to the parent directory.
cd directory name Changes the current directory to the subdirectory with the specified name.
letter: Changes the current drive to the drive specified by the letter. For example, entering
d: changes the current drive to the d drive.
Keystroke Description
Ctrl+C Interrupts the execution of the program and cancels it.
Ctrl+S Stops the scrolling of the display screen.
F3 Types the last command that was run.
How to start the DOSKey program
• To start the DOSKey program, enter “doskey /insert” at the command prompt.
• To automatically start the DOSKey program for all future sessions, enter the
“doskey /insert” statement after the “path” statement in the autoexec.bat file. For help on
editing the autoexec.bat file, see figure 1-6.
How to use the DOSKey program
Key Description
Up or down arrow Cycles through previous DOS commands in the current session.
Left or right arrow Moves cursor to allow normal editing of the text at the DOS prompt.
Figure 1-10 Essential DOS skills for working with Java
24 Section 1 The essence of Java programming
How to use TextPad to work with Java
Now that you’ve learned how to use Notepad and the DOS prompt for
working with Java, you’re ready to learn how to use TextPad. Since this text
editor is designed for working with Java, it’s a big improvement over Notepad.
As a result, we recommend that you use the trial version that’s included on the
CD that comes with this book.
Unfortunately, TextPad only runs under Windows. So if you’re not using
Windows, you can use the text editor that comes with your operating system or
you can search the web to find a better text editor.
How to use TextPad to save and edit source code
Figure 1-11 shows how to use TextPad to save and edit source code. In
short, you can use the standard Windows shortcut keystrokes and menus to
enter, edit, and save your code. You can use the File menu to open and close
files. You can use the Edit menu to cut, copy, and paste text. And you can use
the Search menu to find and replace text. In addition, TextPad color codes the
source files so it’s easier to recognize the Java syntax, and TextPad makes it
easier to save *.java files with the proper capitalization and extension.
Unlike Notepad, TextPad doesn’t come as a part of Windows. As a result,
you must install it before you can use it. To do that, run the setup file that’s on
the CD that comes with this book. Then, respond to the resulting dialog boxes.
Since this version of TextPad is a trial version, you should pay for TextPad if
you decide to use it beyond the initial trial period. Fortunately, this program is
relatively inexpensive (about $27), especially when you consider how much
time and effort it can save you.
Chapter 1 How to get started with Java 25
The TextPad text editor with source code in it
TextPad’s Save As dialog box
How to install TextPad on your PC
• Navigate to the TextPadSetup directory on the CD that comes with this book. Then,
double-click on the exe file and respond to the resulting dialog boxes.
How to enter, edit, and save source code
• To enter and edit source code, you can use the same techniques that you use for
working with any other Windows text editor.
• To save the source code, select the Save command from the File menu (Ctrl+S). Then,
enter the filename so it’s exactly the same as the class name, and select the Java option
from the Save As Type list so TextPad adds the four-letter java extension to the filename.
(On earlier versions of Windows, you may need to enter the four-letter extension
with the filename as in BookOrderApp.java. Otherwise, the extension will be truncated
to jav.)
Figure 1-11 How to use TextPad to save and edit source code
26 Section 1 The essence of Java programming
How to use TextPad to compile source code
Figure 1-12 shows how to use TextPad to compile the source code for a Java
application. The quickest way to do that is to press Ctrl+1 to execute the Compile
Java command of the Tools menu. If the source code compiles cleanly,
TextPad will generate a Command Results window and return you to the
original source code window.
However, if the source code doesn’t compile cleanly, TextPad will leave you
at a Command Results window like the one shown in this figure. In this case,
you can read the error message, switch to the source code window, correct the
error, and compile the source code again. Since each error message identifies
the line number of the error, you can make it easier to find the error by selecting
the Line Number option from the View menu. That way, TextPad will display
line numbers as shown in this figure.
When you have several Java files open at once, you can use the Document
Selector pane to switch between files. In this figure, only two documents are
open (BookOrderApp and Command Results), but you can open as many Java
files as you like. You can also use the Window menu and standard Windows
keystrokes (Ctrl+F6 and Ctrl+Shift+F6) to switch between windows.
To edit as efficiently as possible, you can use the Document Properties
command in the View menu to set formatting options. In particular, you should
set the tab settings so you can easily align the code in a program. You’ll learn
more about that in the next chapter.
How to use TextPad to run an application
Once you’ve compiled the source code for an application, you can run that
application by pressing Ctrl+2. If the application that you run prints text to the
console, TextPad will start a DOS Prompt window like the one shown in this
figure. Then, you can press any key to end the application. If necessary, you can
also click on the Close button or press Alt+F4 to close the DOS Prompt window.
Chapter 1 How to get started with Java 27
The Tools menu
A compile-time error
Text printed to the console
How to compile and run an application
• To compile the current source code, press Ctrl+1 or select the Compile Java command
from the Tools menu.
• To run the current application, press Ctrl+2 or select the Run Java Application command.
• If you encounter compile-time errors, TextPad will print them to a window named
Command Results. To switch between this window and the window that holds the source
code, you can press Ctrl+F6 or use the Document Selector pane that’s on the left side of
the TextPad window.
• When you print to the console, a DOS window like the one above is displayed, and you
need to press any key to end the application. If necessary, you can press Alt+F4 or click
on the Close button to close the window.
How to display line numbers and set options
• To display the line numbers for the source code, check Line Numbers in the View menu.
• To set formatting options like tab settings, choose Document Properties in the View
menu.
Figure 1-12 How to use TextPad to compile and run an application
28 Section 1 The essence of Java programming
Introduction to Java IDEs
Many Integrated Development Environments (IDEs) are available for
working with Java. A typical IDE not only provides a text editor, but also visual
tools for designing forms and debugging code. To illustrate a typical IDE, this
topic uses Forte for Java, an IDE that’s available for free from the Java web site.
However, many other IDEs are available such as Borland’s JBuilder, WebGain’s
VisualCafĂ©, Oracle’s JDeveloper, and Metrowerk’s CodeWarrior.
The first screen in figure 1-13 shows two of the Forte windows that can be
used to edit source code. Here, the Explorer window has been used to open the
source code for a program named ClockFrame in the Editor window.
The second screen in this figure shows the windows that can be used to
visually create the forms of a graphical user interface. Here, you can place
visual components such as labels, text boxes, and buttons on a form. Then, you
can use the Component Inspector window to view and modify the properties of
these components. When you’re done, you can use Forte to generate the appropriate
code for the form.
In addition, Forte provides many advanced debugging features that aren’t
available from a simple tool like TextPad. For example, Forte provides a
Debugger window and a Debug menu that allows you to set breakpoints and
step through code line by line.
Why we don’t recommend using an IDE when
you’re learning Java
We don’t recommend using an IDE when you’re learning Java for two
reasons. First, an IDE will often generate code for you. Although this can save
time and effort once you’ve learned Java, this won’t help you learn. While
you’re learning, you need to have complete control over the code. Second, an
IDE is a complex tool with operational details that are themselves difficult to
learn. And that can distract you from your learning goals.
Why we recommend using an IDE once you’ve
mastered Java
Once you’ve got a solid grasp on the use of Java, an IDE is a sophisticated
tool that can make working with Java easier. In particular, an IDE can make it
easier to develop graphical user interfaces and to debug your code. So when
you’re through reading this book, you’ll be ready to start using one of these
tools. That’s why we’ve included Forte for Java on the CD that comes with this
book.
Chapter 1 How to get started with Java 29
Forte’s Editing workspace
Forte’s GUI Editing workspace
Figure 1-13 The Integrated Development Environment for Forte
30 Section 1 The essence of Java programming
Perspective
In this chapter, you learned how to install and configure the SDK for developing
Java programs. You also learned how to use either the Windows tools or
TextPad to enter, edit, compile, and run a program. With that as background,
you’re ready to start writing your own Java programs. And that’s what you’ll learn
to do in the next chapter.
Summary
• You use the Software Development Kit (SDK) to develop Java programs. This used
to be called the Java Development Kit (JDK). Versions 1.2 and later of the SDK
run under the Java 2 Platform, Standard Edition (J2SE) so they are referred to as
Java 2.
• You can use the Standard Edition of Java to create applications and a special type
of Internet-based application known as an applet. In addition, you can use the Java
2 Platform, Enterprise Edition (J2EE) to create server-side applications known as
servlets.
• The Java compiler translates source code into a platform-independent format
known as Java bytecodes. Then, the Java interpreter, or Java Runtime Environment
(JRE), translates the bytecodes into instructions that can be run by a specific
operating system. Any machine that has a Java interpreter installed on it can be
considered an implementation of a Java virtual machine (JVM).
• When you use the SDK with Windows, you should add the bin directory to the
command path.
• When you use Windows for developing Java programs, you can use Notepad as the
text editor. Then, you can use the DOS prompt to enter the commands for compiling
and running an application.
• To compile an application, you use the javac command to start the Java compiler.
To run an application, you use the java command to start the Java interpreter.
• When you compile a program, you may get compile-time errors. When you run a
program, you may get run-time errors.
• A text editor like TextPad provides features that make it easier to enter, edit,
compile, and test Java programs.
• Once you’ve mastered the basics of Java, an Integrated Development Environment
(IDE) can make working with Java easier. While you’re learning, though, it’s better
to use a text editor like TextPad.
Chapter 1 How to get started with Java 31
Terms
Java Development Kit (JDK)
Software Development Kit (SDK)
Java 2
Java 2 Platform, Standard Edition
(J2SE)
Java 2 Platform, Enterprise Edition
(J2EE)
application
graphical user interface (GUI)
applet
servlet
source code
Java compiler
bytecodes
Java interpreter
platform independence
Java virtual machine (JVM)
Java plug-in
Java Runtime Environment (JRE)
Java Archive file (JAR file)
folder
subfolder
directory
subdirectory
command path
autoexec.bat file
text editor
case-sensitive
ASCII format
ANSI format
DOS prompt
command prompt
javac command
java command
console
compile-time error
run-time error
Integrated Development Environment (IDE)
Objectives
• Describe how Java compares with C++ based on these features: syntax, platform
independence, and speed.
• Name and describe the three types of programs that you can create with Java.
• Explain how the use of bytecodes helps Java achieve platform independence.
• Install version 1.4 of the SDK for the Java 2 Platform, Standard Edition. If necessary,
configure your system to work with the SDK.
• Given the source code for a Java application, use Notepad and the DOS prompt to
enter, edit, compile, and run a program.
• Given the source code for a Java application, use TextPad to enter, edit, compile,
and run the program.
Before you do the exercises for this chapter
Before you begin the exercises that follow, you should run the install program
for the CD that comes with this book to install its directories and files. Then, you
should copy the Java directory that’s in the c:\Murach\Java2\ExerciseStarts directory
to your c drive. You should use the procedure in figure 1-4 to install the SDK. You
should use the procedure in figure 1-6 to set the command path for your system.
And you should use the procedure in figure 1-11 to install TextPad.
32 Section 1 The essence of Java programming
Exercise 1-1 Use TextPad to develop an
application
This exercise will guide you through the process of using TextPad to enter,
save, compile, and run a simple application.
Enter and save the source code
1. Start TextPad. You should be able to do that by clicking on the Start button,
pointing to Programs, pointing to TextPad, and clicking on TextPad.
2. Enter this code (type carefully and use the same capitalization):
public class TextPadTest{
public static void main(String[] args){
System.out.println("TextPad test");
}
}
3. Use the Save command in the File menu to display the Save As dialog box.
Next, navigate to the c:\java\ch01 directory and enter TextPadTest in the File
name box. If necessary, select the Java option from the Save as Type combo
box. Then, click on the Save button to save the file. (If this saves the file with
jav as the extension, use the Save As command to save the file again. This time,
type TextPadTest.java as the filename.)
Compile the source code and run the application
4. Press Ctrl+1 to compile the source code.
5. If you get an error message, read the error message, edit the text file, save your
changes, and compile the application again. Repeat this process until you
compile the application cleanly.
6. Press Ctrl+2 to run the application.
7. This application should start a DOS prompt that displays a line that reads
“TextPad test” followed by a line that reads “Press any key to continue…” so
press any key. Then, press Alt+F4 to close the DOS Prompt window if it’s still
open. You should be returned to the TextPad window.
Introduce and correct a compile-time error
8. In the TextPad window, delete the semicolon at the end of the
System.out.println statement. Then, press Ctrl+1 to compile the source code.
TextPad should display an error message in the Command Result window that
indicates that the semicolon is missing.
9. In the Document Selector pane, click on the TextPadTest.java file to switch
back to the source code. Then, press Ctrl+F6 twice to toggle back and forth
between the Command Result window and the source code.
10. Correct the error and compile the file again (this automatically saves your
changes). This time the file should compile cleanly. Then, close the file and
exit TextPad.
Chapter 1 How to get started with Java 33
Exercise 1-2 Use Windows tools to develop
an application
If you want to see how the Windows tools work for developing an application,
this exercise will guide you through the process of using Notepad and the DOS
prompt to save, compile, and run a simple application. This will also give you
a good idea of how you can use a text editor and the command prompt on any
operating system.
Use Notepad to enter and save the source code
1. Start Notepad. On most systems, you can do that by clicking on the Start
button, pointing to Programs, pointing to Accessories, and clicking on Notepad.
2. Enter this code (type carefully and use the same capitalization):
public class NotepadTest{
public static void main(String[] args){
System.out.println("Notepad test");
}
}
3. Select the Save command from the File menu to display the Save As dialog
box. Next, navigate to the c:\java\ch01 directory. Then, enter
“NotepadTest.java” in the File Name text box (with the quotation marks), and
click on the Save button to save the file. (If you want to see whether the
quotation marks are needed, use the Save As command again without the
quotation marks to see if the file already exists. If it does, you don’t need the
quotation marks the next time you save a new file.)
Use the DOS prompt to compile and run the application
4. Open a DOS Prompt window. On most systems, you can do that by clicking on
the Start button, pointing to Programs, and clicking on MS-DOS Prompt.
5. Use the cd command to change the current directory to the c:\java\ch01
directory.
6. Use the dir command to view the files that are stored in this directory. If you
are in the correct directory, you should see the NotepadTest.java file. Notice
how the right side of the directory listing shows the long filename.
7. Use the javac command to compile the NotepadTest.java file. If you get an
error message, read the error message, edit the text file, save your changes, and
compile the application again. Repeat this process until you compile the
application cleanly.
8. Use the dir command to view the files again. Notice that the file named
NotepadTest.class has been created.
9. Use the java command to run the NotepadTest application (make sure to use
the proper capitalization). This should display the words “Notepad test” after
the DOS prompt. Then, close the Notepad and DOS Prompt windows.
34 Section 1 The essence of Java programming
Exercise 1-3 Use the DOS prompt to run an
existing application
This exercise shows how to run any Java application from the DOS prompt.
1. Open the DOS Prompt window (see step 4 of exercise 1-2). Then, use the cd
command to change the current directory to c:\java\ch01.
2. Use the java command to run the InvoiceApp application. When the first dialog box is
displayed, enter 1000 as the order total. Then, note the results that are displayed in the
second dialog box, and press the Enter key to try this again. When you’re done
experimenting, enter “x” to end the application. Then, close the DOS Prompt window.
This is the application that you’ll learn how to develop in the next chapter. And this
shows how the Java virtual machine can be used to run any Java application, whether
or not it has been compiled on that machine.
Exercise 1-4 Use any tools to develop an
application
If you aren’t going to use Windows tools or TextPad to develop your Java programs,
you can try whatever tools you are going to use with this generic exercise.
Use any text editor to enter and save the source code
1. Start the text editor and enter this code (type carefully and use the same
capitalization):
public class Test{
public static void main(String[] args){
System.out.println("Test");
}
}
2. Save this code in the c:\java\ch01 directory in a file named “Test.java”.
Compile the source code and run the application
3. Compile the source code. If you’re using a text editor that has a compile command,
use this command. Otherwise, use your command prompt to compile the source code.
To do that, start your command prompt and navigate to the c:\java\ch01 directory.
Then, enter the javac command like this (make sure to use the same capitalization):
javac Test.java
4. Run the application. If you’re using a text editor that has a run or execute command,
use this command. Otherwise, use your command prompt to run the application. To do
that, enter the java command like this (make sure to use the same capitalization):
java Test
5. When you enter this command, the application should print “Test” to the console (the
console’s appearance will depend on the tool that you’re using).

No comments:

Post a Comment

 

Blogger news

Blogroll

About