Java Programming Language Handbook (1)
Java Programming Language Handbook (1)
HANDBOOK
Anthony Potts
David H. Friedel, Jr.
Publisher Keith Weiskamp
Editor Keith Weiskamp
Proofreader Kirsten Dewey
Cover Design Gary Smith
Interior Design Michelle Stroup
Layout Production Kim Eoff
Indexer Kirsten Dewey
10 9 8 7 6 5 4 3 2 1
To my wife who has been there through it all.
Anthony Potts
v
vi Contents
What’s in a Package? 30
Classes, Inheritance, and Interfaces 32
Types, Objects, and Constructors 35
Thank Goodness for Garbage Collection 37
Using Methods 38
Methods and Method Overriding 43
Graphic Methods 46
Working with Threads 49
Processing User Input 52
One Last Thing 53
That’s It—Run It 54
Passing Arguments 87
Reading in Arguments 87
Accessing Arguments 88
Dealing with Numeric Arguments 89
Chapter 4 Operators,
Expressions, and Control
Structures 91
Using Java Operators 93
Operator Precedence 93
Assignment Operators 95
Integer Operators 97
Boolean Operators 100
Floating-Point Number Operators 102
Using Casts 103
Writing Expressions and Statements 104
Control Flow Statements 106
if..else 106
while and do..while 108
switch 109
for 110
labels 111
Moving Ahead 112
As a brand new magazine editor at the end of 1984, I surveyed the IBM PC field
and commented under my breath, “These are the Crazy Years.” The IBM PC
world had begun exploding in 1983; PC Magazine hit 800 pages; new compa-
nies were forming every minute and spending huge amounts of money launch-
ing new products into an astonishingly hungry and immature market. The
machines of the time were almost unimaginably underpowered. 5Mhz. 8 bits.
256K of RAM. Only rich people had hard drives. And yet everyone spoke of
their miserable little IBM PCs as though they could do the work of mainframes—
we just hadn’t yet figured out quite how.
History doesn’t repeat itself—but it echoes, it echoes. Here we sit, eleven years
later, I’m still a magazine editor (though not nearly as new) and the Crazy Years
are back again. This time, plug the Internet into the place the IBM PC occupied
in 1984. Our PCs really are mainframes now; those 166 Mhz Pentiums that we
take for granted can handle anything we throw at them. What we’re enraptured
with today is the ability to connect to a server and bounce around the world like
manic pinballs, grabbing a Web page here, a shareware file there, a picture of
Cindy Crawford somewhere else. New Internet magazines are appearing weekly,
enormous sums of money are being spent and earned on Internet technology
companies, and Internet books have crowded almost everything else off of the
computer book shelves at the superstores. The Internet will become the OS of
the future. Applications will be fragmented and distributed around the world; a
piece in Britain, a piece in Finland; a piece in Rio. Faithful agent software will
wander around the globe, sniffing out what we want and paying for it with
digital cash. Our Internet boxes will be our phones, our faxes, our stereos, our
game platforms, and our personal bank machines.
xv
xvi Foreword
shuck, that it was ruining all our lives, that he was giving it up forever, and don’t
expect him to come back and rescue us from ourselves, farewell, good bye for-
ever, I’m leaving and I’m serious, don’t try to stop me, and on and on and on.
We waved good-bye. Now he’s gone. And not only is he not especially missed, I
doubt that one person in a hundred even remembers who he was. That’s how
our business works. If you stand back and let the train go by, you will not be
missed, and the train generally passes through your station only once.
That’s why I encourage you to stick with this stuff, no matter how crazy it gets. As
best we can tell right now, Java is the brand of pipe that we’ll be using to plumb
global communications software for the foreseeable future. No, we don’t have the
whole foundation poured, and no, we don’t have a stack of plans to go by. Still,
without the pipes in place, it won’t work. You have to develop the skills you’ll need
to do the work next year and the year after. What better time than now?
You’ve got the book in hand to take you through the Java language and make it
stick. So do it!
Or heads will bounce.
Chapter
1
Introducing
Java
Introducing
Java
Java has swept the computer industry with
its promise to deliver executable content to
the vast sea of computers connected to the
World Wide Web. Here’s a look at why
you’ll want to start developing with this
language as soon as you can.
I
1
n just a few months, Java has moved from the R&D labs at Sun Microsystems
to the center stage of the World Wide Web. Never before had a simple program-
ming language garnered so much attention and captured the imaginations of so
many software developers and computer users alike so quickly. Some cynics think
that the best part about Java is its name, which is also the reason they think Java
gets so much attention in the press. But most experts who follow Web develop-
ment think that Java is the most significant thing that has been developed or
announced for the Web.
Why has Java taken over so quickly? The short answer is found in its platform
independence and potential to turn the Web into a much more dynamic and
interactive environment—something that is badly needed. Other reasons are
because of Java’s similarity to C++ and its support of popular object-oriented
programming techniques, making it easier for hundreds of thousands of C and
C++ programmers to quickly master Java’s powerful features.
Our goal in this chapter is to set the stage for Java, exploring where this language
has come from and where it is going. We’ll introduce the key features of Java,
give you some insight into why Java was developed in the first place, and exam-
ine some of the key similarities between Java and C++. We think it is important
to spend as much time as possible looking at Java through the lenses of a C++
programmer because the syntax and object-oriented features are very similar.
3
4 Chapter 1
If you have seen Java in action by using your Web browser to view Web pages
that contain Java applets, you already know some of the types of programs you
can write. But Java applets are only half of the story. The Java language can be
used to write both applets and standalone applications. Applets are incorporated
into Web pages using a special <APPLET> HTML tag and they are downloaded
and launched automatically when their pages are displayed by a Java-enabled
Web browser. This process is similar to the way in which a Web browser might
process and display other elements such as images and hyperlinked text. The big
difference with an applet is that the browser processes dynamic executable content
instead of static data.
A Java application, on the other hand, looks suspiciously like a C++ program. It
can run on its own and perform a myriad of tasks from performing calculations
to specialized file I/O operations. The only problem with writing Java applica-
tions at the moment is that Java is an interpreted language, and thus programs
written in Java require the Java Virtual Machine in order to execute. Fortu-
nately, work is underway to develop compilers that enable Java applications to
run quicker and more independently.
that allows you to combine data and the code that must operate
on the data under one roof. Once classes have been defined,
they can easily be used to derive other classes.
Distributed Programming This emerging field of software
development involves the techniques of writing programs that
can be executed across networks like the Internet. In traditional
programming, applications run on a single computer and only
data is distributed across networks. In distributed programming,
programs can be downloaded from networks and executed at
the same time. As you might guess, this approach opens the
door wide for ways in much software can be shared and distrib-
uted.
Garbage Collection This is the memory management tech-
nique that Java programs use to handle dynamic memory allo-
cation. In traditional compiled languages like C and C++,
memory for dynamic variables and objects (pointers), must be
allocated and deallocated manually by the programmer. In Java,
memory allocation is handled by the Java runtime environment,
thus eliminating the need for explicit memory allocation and
pointers. Garbage collection is one key feature that many pro-
grammers claim make “Java a better and safer C++.”
HotJava This is Sun’s Web browser written in the Java lan-
guage. It contains the Java Virtual Machine and can download
and play any Java applet. Originally, HotJava was the rage on
the Web but since Netscape has licensed and incorporated the
Java Virtual Machine into Netscape Navigator, most Web users
have forgotten about HotJava.
Java Applet These are small programs written in Java that
can execute remotely over networks. They are downloaded from
the Web via a Java-enabled Web browser and then they are
executed from within the shell of the browser. An applet can be
anything from animations to search engines to games. In the
short time that Java has been available, hundreds of applets
have appeared on the Web written by programmers from all
around the world.
Java Virtual Machine This is the code that serves as the
engine or interpreter for Java programs. Any application that is
capable of running Java programs requires the use of the Java
Introducing Java 7
running standalone Java applications (java), and a debugger (jdbg). But don’t be
surprised to find that each of these development tools are somewhat primitive
and must be run from the command line. In the near future, we should have
much better Java visual development tools. If you don’t currently have the JDK,
you can visit Sun’s Java Web site to download a copy (http://www.javasoft.com/).
The syntax and command options for using the tools in the JDK are presented
with the Java Programming Language reference card included at the end of this
book.
All of the tools included in the JDK are designed to support Sun’s notion of
what the Java language is all about including:
• A compiler for the Java language that generates architecture-neutral bytecodes
• The Java Virtual Machine that interprets bytecodes at runtime.
• A set of class libraries to help Java programmers create applications. Some of
these libraries include interface tools, I/O, applet development, networking,
and so on.
• A Java runtime environment that supports bytecode verification,
multithreading, and garbage collection
• Java development support tools including a debugger, documentation gen-
erator, and so on.
• typedefs or structs
• Pointer arithmetic
• Multiple inheritance of classes
• General functions (Only methods are supported)
On May 23, 1995, Sun introduced the Java language and its corresponding
browser HotJava. The language and its associated development tools only took
about four years to create, but as the Green group proved, four years was ample
time to create a new standard for the rest of the world to follow. Soon after the
announcement of Java, alpha versions of the language started appearing across
the World Wide Web. Another noteworthy date to mark on your calendar is
December 7, 1995—the date Microsoft agreed to license Java, an endorsement
that has helped to accelerate Java’s popularity. (If you owned any of Sun’s stock,
you probably noticed that their stock increased by $336 million on that day!)
The visual benefits of running distributed software like Java applets are only the
tip of the iceberg. Of course, it is impressive to see a well-designed animated applet
dance across a Web page as its code is being downloaded across a network and
executed locally, but Java programmers are already looking forward to the day in
the not so distant future when they can develop major applications that can run
across networks. This dynamic flexibility will open up new possibilities for both
updatable entertainment and business-related software. And the best part is that
programmers will no longer have to write applications that they have to port to
multiple platforms. The same program written in Java can run on any type of
computer that can connect to a network and run the Java Virtual Machine.
But the best part is that you can use Java today in its current form and take
advantage of some of the key benefits the distributed software paradigm has
over the CGI client-server approach:
Develop Interactive Web Interfaces With Java you can create much more in-
teractive interfaces to the Web than you can with CGI languages like Perl. Applets
that you customize for Web pages can allow users to move objects on the screen,
view animations, and control multimedia features, such as sound and music.
Utilize Local Resources With the CGI model, a server is limited to processing
the data it has on hand. With Java, on the other hand, you can write applica-
tions that truly take advantage of resources available on a user’s local system. For
example, a Java program might use local hardware features in a way that a CGI
program never could. The Java approach allows the local computer to take full
control over how and where code is executed.
Greater Internet/Web Access One of the biggest problems with the Internet
and the Web is that content is scattered all over the place in a somewhat chaotic
fashion. Using Java, you can write better front-ends to the Web, such as agents
and search engines, to better access the Web.
Reduce the Cost of Distributing Software The software industry has rapidly
turned into a “hits” based business, which means that computer software outlets
typically only carry the major blockbuster products. One of the reasons this has
occurred is that the cost and risks of selling and distributing software have greatly
increased over the past five years. With distributed software, users can purchase
and download the software they need instead of having to order from a direct
mail catalog or buying it in a store. This approach of getting software from a
publisher or developer to a user also is ideal for updating software. If you need a
new version of your favorite tax program to get your taxes done by April 15, you
can simply point to the right place on the Web and quickly access the software
12 Chapter 1
you need.
method invocation of a Java class object. In C++ you can use stand-alone func-
tions, header files, global variables, and so on. This is an extremely important
point, so don’t gloss over it. The only thing in Java not placed in a class is inter-
faces, although they are used like classes but without implementations.
This strict OO nature means that you won’t be able to port C++ code as easily.
You will need to change the basic structure of your C++ applications, although
you should be able to keep the logic as long as you are not using any of the
features that have been removed.
What’s Missing?
As we’ve mentioned, one of big goals for the developers of Java was to look at all
the other programming languages and pull the best features of each and dump the
rest. Since C/C++ has such a large installed base of programmers, it is obvious why
they chose to mimic so much of its syntax and structure. There are, however,
several features that C++ has that Java does not implement. Many of these subtrac-
tions were made for security reasons, since Java was designed as a Web language.
Other features were left out because the Java creators thought they were to difficult
to use or just plain useless. Let’s look at some of the important subtractions.
Gone: Pointers
Pointer arithmetic is the bane of everyone who hates C++. For the few program-
mers who have mastered pointers, we salute you. For the rest of us, good riddance.
The major reason pointers are not used with Java is security. If a Java applet had
the ability to access memory directly, it could easily cause some real problems. By
forcing the Java interpreter to handle memory allocation and garbage collection, it
relieves you of a big burden and lessens the chance that anyone can do bad things
to your computer through a Java program.
There are a few areas where pointers seem necessary for performing certain op-
erations. But since we don’t have them in Java, we need to find a way around
them. In Java, objects are passed as arguments directly instead of passing a pointer
to an object’s memory space. You must also use indices to manipulate arrays
rather than accessing the values directly.
What’s New?
Since Java is supposed to be the next step in the evolution of programming
languages you would expect some advancements. Most of the new features focus
Introducing Java 15
Garbage Collection
When you finish using a resource in a C++ program, you must explicitly tell the
computer when to release the memory it was using. This is accomplished with
pointers. Since Java does not use pointers for security reasons, it needs a way to
clean up resources when they are not needed any more. That’s where garbage
collection comes in.
Garbage collection is a threaded run-time environment that keeps track of all
the parts of your program and automatically de-allocates the memory used when
the memory is no longer needed. For example, when you declare a variable,
memory is allocated to store its value. The garbage collection engine looks at
what scope of the program is seen by this variable. When the program leaves
that scope, the memory is cleared.
Lets look at a specific example. Here is a simple for loop:
The integer we are using to count to ten is actually declared within the declara-
tion of the loop. As soon as the expression is met and the loop ends, the x
variable’s memory space is cleared and put back into the shared memory pool.
This same idea works at all levels of the Java environment.
Security
Security was an issue that the creators of C++ did not have to deal with—they
left that up to individual programmers. However, since Java is designed to be a
distributed programming language, security is a prime concern. Java includes
many features that aid in preventing security problems. The omission of point-
ers is a key issue that reduces security risks. The functionality you lose is made
up for in the robustness of your applications and applets. Now, it’s just up to
browser creators to develop programs that can’t be hacked!
Exceptions
Exceptions are not really new—they were used in C++. However, using them was
difficult at best. In Java, exceptions are used heavily. Exceptions are error condi-
tions that are not expected during the course of a standard program run. Situa-
16 Chapter 1
New Modifiers
In C++, modifiers are used quite heavily. Java takes many of the C++ modifiers
and adds new ones. Most of the new modifiers are needed to help support secu-
rity issues. Table 1.1 provides a list of the new modifiers:
Table 1.1 Some of the New Java Modifiers
Modifier Descriptions
abstract Used to define classes and methods that must be subclassed or overridden to be useful.
synchronized Tells Java that a method can only be called by one object at a time.
native Used to create calls to languages like C.
final Tells Java that a class cannot be subclassed.
Introducing Java 17
Helper Programs
The Java Developer’s Kit (JDK) ships with two helpful programs: javadoc and
javap. javadoc is an automatic documentation program that creates HTML files
automatically to list your classes methods, interfaces, variables, and so on. We
discuss this program in greater detail in Chapter 3 so we won’t repeat it here.
The entire API documentation that shipped with the 1.0 JDK was created using
this program. Javadoc can only be used with source files.
Another useful utility is javap, a disassembler program that prints class signa-
tures. javap is used with the compiled class files. When javap is run, it outputs a
simple listing of a classes public methods and variables. Here is an example:
As you can see, this program can be very useful when trying to figure out how to
use a class that has little documentation or that you do not have the source for.
Chapter
2
Writing Your First
Java Applet
Writing Your
First Java
Applet
The best way to learn the elements of the
Java language is to dive in head first and
create a real-world applet.
2
Before we get into the down and dirty details behind the Java language, let’s
create a simple program that will introduce you to many of the basic concepts
of Java.
Once we decided to put a tutorial program at the beginning of this book, we tried
to find one that included many of the major programming elements that you will
encounter while coding your own programs. We had to decide if the program
would be an application or an applet. Applications and applets are very different
things. Creating one over the other is not as simple as changing a couple of lines of
code and recompiling. Java applications are free-standing programs; therefore, they
must create their own “space” to work within. Java applets, on the other hand, are
run from within another program, usually a Web browser. Applets have many
parts of their code already written for them and ready to go. For example, if you
wanted to display a graphic in a stand-alone Java application, you would first have
to create a window to run the program in, a frame, then the graphics you might
need. With an applet, most of that work is done for you. A simple call to a graphic
method can load an image into your applet’s space.
Does that mean that applets are better? Not necessarily, they are simply “differ-
ent.” Both applets and applications have their place in the programming world.
The one you use depends on your needs and the needs of the people who will
use your programs.
21
22 Chapter 2
// TickerTape Applet
import java.applet.*;
import java.awt.*;
Writing Your First Java Applet 23
// TickerTape Class
public class TickerTape extends Applet implements Runnable {
// Declare Variables
String inputText;
String animSpeedString;
Color color = new Color(255, 255, 255);
int xpos;
int fontLength;
int fontHeight;
int animSpeed;
Font font;
Thread ttapeThread = null;
Image im;
Graphics osGraphics;
boolean suspended = false;
// Initialize Applet
public void init(){
inputText = getParameter("TEXT");
animSpeedString = getParameter("SPEED");
animSpeed = Integer.parseInt(animSpeedString);
im=createImage(size().width, size().height);
osGraphics = im.getGraphics();
xpos = size().width;
fontHeight = 4 * size().height / 5;
font = new Font("Helvetica", 1, fontHeight);
}
} // End TickerTape
Before we discuss how the program works, why don’t you try it out and see how
it looks. You can type the code in for yourself and compile it or head up to the
Coriolis Group Web site at http://coriolis.com and download this applet as well as
all the other code examples listed in this book (look in the “What’s Free” sec-
tion). You can also view this entire chapter on-line by going into the Coriolis
books section on the site and searching for this book. There you can choose the
“sample chapter” option where you will see this chapter.
Recall that HTML is the language used to create Web pages. Each statement
in the language specifies one specific formatting, file processing or hypertext
(linking) operation, such as loading and displaying a graphic image, defin-
ing a hypertext link, displaying a word or sentence in bold, or loading and
playing a Java applet. (We’ll look at the HTML instructions for playing our
applet in much more detail in a moment.) If you are creating a new HTML
file, you might want to name it TTAPE.HTML.
26 Chapter 2
5. Start a Web browser like Netscape 2 that is capable of running Java applets.
Then, load in the HTML file you just created. Keep in mind that not all
Web browsers can run Java applets. If nothing happens after you load in
the HTML file, first check to make sure that you entered the HTML
instructions carefully. Then, check to make sure that you are using a Java-
playable browser.
After you open the HTML file that includes the required instructions, you should
see a screen similar to one shown in Figure 2.1. Once you get the applet to run,
you can experiment with it by changing the text and speed parameters. Just
replace the strings listed after each VALUE statement. For example, if you changed
the third HTML statement to be:
You would see the string “Buy stock in Java” scrolled across the screen. For the
SPEED parameter, lower numbers produce slower but smoother animation and
higher numbers create faster but sometimes jerky animation.
Even if you have created Web pages using HTML instructions, you might be
unfamiliar with the Java applet-specific HTML tags. (If you need to brush up
on the general techniques of creating Web pages with HTML, we suggest you
get a copy of a good tutorial book such as The Coriolis Group’s Netscape and
Figure 2.1
The TickerTape applet in action.
Writing Your First Java Applet 27
HTML Explorer.) The <APPLET> ... </APPLET> tag pair tells a Java-enabled
Web browser, such as Netscape 2, that a specified applet should be loaded and
played. Notice that in our example, one HTML line does this work for us:
The CODE parameter specifies the name of the applet—in this case it is the
name of our file, TickerTape.class. If you used a different filename, you would
need to change this instruction. The WIDTH and HEIGHT parameters specify
the width and height of the window or “space” that will be used to play the
applet. The dimensions are specified in units of screen pixels. Since our applet
needs to simulate a ticker tape-like device, we’ve defined it to be very wide but
short. The other HTML instructions, <PARAM>, are used to specify the pa-
rameters for our applet:
Notice that each parameter has a name and a value. The name must correspond
with the name of the parameter used in the Java applet. The VALUE clause
handles the work of assigning the parameter a default value. Later in this chapter
we’ll show you how parameters are processed using special Java functions. If you
change the values for either of these parameters and reload the HTML file,
you’ll see the effect of the changes immediately.
Don’t look too hard because you won’t find such a “main function” in a Java
applet. Instead, Java applets really are designed to run “inside” another applica-
tion—in our case the Netscape browser. You can think of an applet as if it were
a plug-in or component. This means that the routines and methods in a Java
applet are executed by the controlling program (the browser). Let’s step through
our applet to better understand how this process works.
The TickerTape applet contains a number of functions, which are actually called
methods in Java. (This terminology is borrowed directly from C++.) Take a
moment to look over the applet and you’ll find methods like init(), paintText(),
start(), run(), stop(), and so on. Some of these are standard Java applet methods
(they have names and perform operations that are pre-defined); and others are
user-defined (we made them up). When the applet runs, the browser running
the applet knows which methods are used and in which order to call them.
Figure 2.2 shows the order of how the methods are called. Notice, first that the
browser calls the init() method. Each statement in init() executes until the method
Applet(TickerTape)
Applet
Methods
Browser Overidden New Methods
Methods
getParameter()
init()
ttapeThread.start();
start()
setcoord()
Thread.sleep(50)
run()
paint() repaint()
paintText()
stop() ttapeThread.stop()
handleEvent()
ttapeThread.resume()
ttapeThread.suspend()
Figure 2.2
How the methods are controlled in the Java applet.
Writing Your First Java Applet 29
finishes. If you look closely, you’ll see that init() doesn’t call any of the other
TickerTape class methods. What gives?
To understand what happens next, keep in mind that the browser is the control-
ling program—not the applet itself. After init() is called, the start() method is
then called by the Web browser. start() sets up TickerTape as a thread. You’ll
learn more about threads later on, but for now you can think of a thread as a
mechanism for handing off control. If the applet were not set up as a thread, it
would run inefficiently and the browser performance would suffer as well. Once
the TickerTape applet is set up as a thread, the browser will know what to do
when events occur such as the mouse button being clicked, a window being
moved, and so on.
After start() has done its job of setting up the thread, typically the run() method
would be called next by the browser. This methods acts as a loop that keeps the
program in motion—in other words, it drives the operations to make our text
move across the screen. Table 2.1 provides a summary of each of the key meth-
ods used in the TickerTape applet. The methods like paint(), which are standard
Java applet methods, can be redefined to perform different operations. For ex-
Java also provides a new type of comment syntax that can be used to automati-
cally generate formatted documentation. This new syntax looks like this:
Back to our program, the first line of the code is actually just a comment that
tells us about the program:
// TickerTape Applet
Although Java allows us to use any or all of these styles within a single program,
we will only use the // notation in our TickerTape program. After all, we don’t
want to make things more complicated than they need to be.
What’s in a Package?
The next two lines of our applet are used to reference packages that contain
classes that contain the methods we wish to use. This may sound like a mouthful,
but the concepts involved are actually quite simple. Here’s the code in question:
import java.applet.*;
import java.awt.*;
Writing Your First Java Applet 31
Packages are used to group related classes for use in other programs. This is a
direct extension of the object-oriented techniques that languages like C++ pro-
vide for programmers.
There are several class packages that come with Java. Table 2.2 provides the
current set of them.
By default, every Java application imports the classes contained within the
java.lang package, so you do not have to manually import this package.
If you look closely at our import statements in the TickerTape program, you’ll
notice that the * character is used. This character tells the Java byte-code com-
piler to use all the classes stored within the package. You could also specify which
classes to use; but since you usually need many classes within a single package, it
is easier to simply use the asterisk. Also, the Java compiler is smart enough to
figure out which classes are used and which ones aren’t so that using the asterisk
does not eat up any additional memory.
In our program we import the applet package because we are creating an applet.
We also need to import the awt package because we want to use its graphics
capabilities. This package contains the classes we need so that we can display our
ticker tape-like graphics.
The AWT package was developed to aid in creating windowed applications and
applets. It does for Java what Visual C++ does for C. Instead of having to manu-
ally define graphical user elements like buttons, windows, and menus, and then
manually having to write code to handle mouse events, the AWT package takes
care of it for you.
We’re not showing the complete class here but it contains the following compo-
nents:
• Definition
• Variables
• Methods
The first line of code that actually sets up the class definition is illustrated in
Figure 2.3. Let’s take a close look at each section.
Class Modifier A class modifier tells the Java compiler how and where a class
can be used. The two main types of classes are called public and private. A public
class can be accessed from other packages, either directly or by using an import
statement. If you omit the public modifier at the beginning of the class defini-
tion, the class would become private and use of the class would be limited to the
package in which it is declared.
The two other modifiers that can be used to define classes are abstract and final.
We’ll cover these class modifiers in detail in Chapter 4.
Name Space
Class Modifier Superclass Specification
Interface
Figure 2.3
Setting up a class definition in Java.
34 Chapter 2
Name Space The name space in a class declaration is simply the name of the
class. In our case the name space is “TickerTape.”
Superclass The keyword extends indicates that we are inheriting all of the
methods, variables, and field declarations from the Applet class. Applet becomes
the superclass of our TickerTape class. This means that we can use any of the
methods and variables from the Applet class.
If we did not include the superclass specifier, the program would derive itself
from the Object class by default.
Once again, you must implement every method in the interface you are using.
Interface Runnable contains only the method run().
Writing Your First Java Applet 35
Let’s take a few of these variable declarations and break them down into their
components. As shown in Figure 2.4, a standard variable declaration consists of
a data type, variable name, and optional value.
variablename
typename
Value
Figure 2.4
Standard Java variable declaration.
The typename in a standard declaration needs to be one of the basic Java types
listed in Table 2.3. One potential problem to watch out for here is capitaliza-
tion. Spelling boolean with a capital B can really cause some errors. With the
current state of Java debuggers, don’t expect them to help much.
The variableName can be any ASCII string. You can even make the variablename
the same as the class name. Be careful though; this can get very confusing. Vari-
able names are also case-sensitive. This means the variable String1 is different
from the variable string1. You also cannot include spaces or any other whitespace
characters in your variable names.
When you declare a variable, you can also assign it a value at the same time. This
is a very useful feature that was introduced with the C language, which Java
heavily steals from. You can even perform a calculation or call a method to
obtain values while you are declaring a variable. However, the value sections of
any declaration do not need to be set when they are declared—they can be given
values later in your program. Here are some examples:
Variables can also use modifiers like classes do. However, there are several more
modifiers for variables, including static, final, transient, and volatile. We’ll cover
all of the variable modifiers in detail in Chapter 4.
Writing Your First Java Applet 37
variablename Value
typename Object
Figure 2.5
Using a constructor in a variable declaration.
38 Chapter 2
are very difficult to detect. Anyone who is active in the software development
industry is keenly aware of intermittent errors in their software that can cause
their release dates to slip. Every year millions of dollars are spent and lost be-
cause of extensive software testing that is required to find the errors caused by
troublesome pointers and mismanaged memory allocation.
So is there is a solution to this crippling problem? The answer is garbage collection.
Garbage collection is not a new invention, recently created for Java programmers.
It has been around for years; in fact, programmers who have used languages like
Lisp, Smalltalk, and Prolog, have been writing amazing programs that really push
this technology to the limit. The basic idea behind garbage collection is to offload
the work of managing memory and other resources to the program itself. If memory
is needed for a new data structure or object, the program automatically takes care
of this task and automatically releases the resources when they are no longer needed.
This frees the programmer from a number of complex tasks, such as declaring
pointers to access memory, passing pointers as arguments to functions, setting up
memory buffers to swap the contents of data structures, and so on.
Of course there is a price to pay for all of this convenience. Programming lan-
guages that use garbage collection tend to be bigger and run slower than programs
written in “the programmer does it all by hand” languages such as C and C++.
In developing Java, the language designers at Sun wanted to make it as flexible
yet robust as possible. They reasoned that a smart compiler, even for a language
that has a syntax like C++, could figure out for itself which program elements
require memory allocation and perform memory management operations auto-
matically. In Java, memory taken up by objects, methods, and variables is allo-
cated and then cleared when those items are no longer needed. This garbage
collection was designed not only to make life easier for programmers but be-
cause it is required for creating programs that can run on many different plat-
forms and allocate memory in the same way.
Using Methods
Now we’re ready to get into the meat of our program by exploring the imple-
mentation section of the applet:
We learned earlier that this code actually shows the definition of what is called
a method. (We’ll be looking at methods in more detail a little later.) The method
defined here is named init(). As we discussed earlier, it is the starting point for
all applets. Remember that it is called by the browser whenever the applet is first
loaded. You can think of this method as serving a similar role to the one carried
out by a main() function in a C program. When the applet is first loaded into a
runtime environment like a Web browser, the program execution will begin
with the first statement in the init() method.
The public modifier in front of this method tells us that this method may be
called from any object, and the void modifier states that the applet will not
return any values.
Init() performs a number of tasks. First, it loads in the two parameters used by
the applet. Then, it calculates the animation speed for the ticker tape using the
SPEED parameter. The remaining statements in this method are needed to set
up variables to support the graphics and text fonts used in the applet. Let’s look
at all of this code in a little more detail.
PROCESSING PARAMETERS
Many times when you create applets you will want the user to be able to specify
options such as font size or animation speed. If we were creating an application,
instead of an applet, these values could be passed as command line arguments.
Applets do not have command line arguments, but they do have parameters. As
we introduced earlier, parameters are embedded in HTML tags that reside be-
tween the opening and closing <APPLET> tags like this:
The idea behind parameters is very similar to arguments, but parameters allow
you a little more flexibility. Since parameters have a name associated with them,
they can be put in any order. It is also easier to determine if a parameter has been
left out and if so, which one.
When a getParameter() method executes in a applet, the method searches a
parameter list to locate a parameter with the corresponding NAME field. In our
applet, we need to read in the text that will be displayed in the applet and a
speed setting that effects how fast the text scrolls across the screen. Thus, notice
that the init() method contains two calls to getParameter():
inputText = getParameter("TEXT");
animSpeedString = getParameter("SPEED");
After these methods are called, the variable inputText will contain the string “The
Java TickerTape Applet...” and animSpeedString will contain the value “4.” But
there is one catch: All parameters must be read in as strings. Since the variable we
declared for animation speed animSpeed in the TickerTape class is an integer
int animSpeed;
we need to convert the speed parameter from a string to its integer representa-
tion. To perform the conversion, we use the parseInt() method of the Integer
class that resides in the java.lang package. (Make sure that you use the correct
capitalization here, or you will get errors when you try and compile the pro-
gram.) The code that performs this operation looks like this:
animSpeed = Integer.parseInt(animSpeedString);
Notice that the syntax for calling this method involves using the name of the
Integer class. The parseInt() method takes a string as its argument and returns a
32-bit signed integer. For larger numbers you could use the parseLong() method
that can return a 64-bit signed integer. The value of the converted string, 4, is
stored in the variable animSpeed—right where we want it.
ing area that is constructed until we are ready to update the screen. Then, we
blast the entire contents of the image buffer to the screen at once. To under-
stand how this process works in more detail, see the sidebar Double Buffering.
Fortunately, an image buffer is easy to set in a Java applet. In fact, we only need
a few lines of code. The following two lines in init() perform the work of setting
up the image buffer component that will store all the changes we make to the
graphics until we want to blast it onto the screen:
im=createImage(size().width, size().height);
osGraphics = im.getGraphics();
This code creates a graphics object called im with a width and height equal to
the size of the applet. We use the size().width and size().height objects to return
information about the applet’s client space. In this case, size().width and
size().height will always be equal to the width and height values we used when
we called the applet in our HTML file:
Our final bit of business for creating the buffer is to use thegetGraphics() method
to initialize the graphics and clear the buffer.
The next two lines of code in init() are used to set the values of the xpos and
fontHeight variables.
xpos = size().width;
fontHeight = 4 * size().height / 5;
The xpos variable will be used to track the current position of the left side of the
text. We start the applet with xpos equal to the width of the applet (size().width)
so that as it starts, the text begins scrolling from off of the applet. Figure 2.6
shows how this process works for scrolling the text to the left.
The fontHeight variable is used to store the height of the text. In this case, we
are setting the height of the text to be 80% of the height of the applet. By doing
this, we allow the HTML programmer to change the size of the applet and have
the size of the text reflect that change. You could also use another parameter to
input the size of the text, but our method is simpler and saves a step or two. Figure
2.7 shows you how all the applet and text sizes correspond with each other.
42 Chapter 2
Applet space
Text string
Figure 2.6
Starting the text off of the visible part of the applet.
Figure 2.7
Coordinates in our applet.
The final line of code in init() is used to initialize our font object:
Recall that we already created this variable in our declaration section at the be-
ginning of the applet (the TickerTape class) but we gave it no value. Here we are
setting up the name of the font (Helvetica), the style (sum of constants PLAIN,
BOLD, and/or ITALIC), and the size (points or pixels).
Notice also that we are using a constructor again. Recall that the new statement
tells Java that we want a “new” object, in this case with all the characteristics of
the standard Font class.
Writing Your First Java Applet 43
The declaration of the argument Graphics g may look a little strange. It sets up
the applet background to be printed to. (Java will set up the device context of
the applet itself as g.) The first line of this method calls another method,
paintText(), which prints the text onto the buffer image. The paintText() method
is a user-defined method that takes a single argument. In this case that argument
is the graphics object we want the text drawn onto—the osGraphics object.
Finally, we call the drawImage() method that copies the buffer data (im) onto
the applet space on the browser (g) for the user to see.
Double Buffering
Double buffering is an extremely powerful concept that has
helped make some of today’s flicker-free animation and game
play possible. It reduces flicker by performing all the graphics
functions on a hidden image that resides in memory instead of
drawing directly to the screen. Then, the entire image is dis-
played all at once instead of having to update the screen every
time a new bit of graphics is drawn.
If we removed the double buffering technique from our applet,
you would see the screen flicker every time the text moved even a
little bit. (As an experiment, you might want to try changing the
applet code so that the double buffering gets disabled.) If we
were drawing any extra graphics or additional text, you would
also see flickers for each of those events. These flashes and flick-
ers occur because the screen is updated multiple times during the
drawing of the object and the Applet class’ paint() method clears
the screen before it redraws it. With text, the screen can some-
times be redrawn for each letter! This causes the flicker and can
actually slow things down if you are drawing many items.
Double buffering improves performance because the graphics
can be drawn into memory faster than they can be drawn onto
the screen. Even with the extra step of blasting the graphics to
the screen, double buffering is still much faster. Figure 2.8 illus-
46 Chapter 2
Graphic Methods
Now that we are aware of the basics involved in overriding methods, let’s re-
turn to our applet and explore the other methods used to perform all of the
graphics drawing operations. Our next step is to see how the applet will print
our text onto the image buffer. This work is accomplished by the user-defined
paintText() method:
Figure 2.8
Double buffering the applet display to reduce flicker.
Writing Your First Java Applet 47
public void paintText(Graphics g){
g.setColor(Color.black);
g.fillRect(0, 0, size().width, size().height);
g.clipRect(0, 0, size().width, size().height);
g.setFont(font);
g.setColor(color);
FontMetrics fmetrics = g.getFontMetrics();
fontLength = fmetrics.stringWidth(inputText);
fontHeight = fmetrics.getHeight();
g.drawString(inputText, xpos, size().height - fontHeight / 4);
}
First, keep in mind that paintText() is a method that we created from scratch. In
other words, we did not create this method by overriding one that already exists
with Java.
This set of method calls found in paintText() start by setting the current pen
color to black by using the setColor() method. Then, we call the fillRect() method
to draw a filled rectangle that fills the applet. Next, comes the clipRect() method
that tells Java to clip any data or graphics that are written outside the given
boundaries, which in this case is the same as the size of the black rectangle. This
set of initializations is illustrated in Figure 2.9.
Next we set the font of the graphics buffer equal to the font we set up in the init()
method. We also need to change the pen color to something other than black so
that our text shows up. For this task, we use the color object we set up earlier.
Figure 2.9
Setting up the rectangle for displaying the ticker tape text.
48 Chapter 2
g.setFont(font);
g.setColor(color);
Now that we are set to print, we need to determine where to print. Recall that
we previously initialized a variable named xpos to keep track of the text posi-
tion. Thus, we can use this variable to tell us where to begin printing. Now we
need to find out how tall and long the text we want to print is. We will use this
data to center the text vertically and to tell us how long the text is so we can reset
the location of the text when it is done scrolling.
To accomplish these tasks, we use the FontMetrics constructor. Using font metrics
is an easy way to gather information about the physical characteristics of text as
it is related to certain components at certain font sizes, types, and so on:
To actually print the text onto the graphics buffer, we use the drawString()
method. This method takes several arguments as shown:
First, we must tell drawString() what string we want to print. In this case, inputText.
Next, we tell it where to start printing along the x-coordinate. Finally we send it
the vertical component to tell it where the bottom of the text should be. Figure
2.10 illustrates how drawString() sets up the required components. Here, we want
the height to be a quarter of the difference of the height of the applet and the
height of the text. This does a nice job of centering at any applet size.
xpos
Figure 2.10
Placing text in the buffer with drawString().
Writing Your First Java Applet 49
In looking over the call to the drawString() method, don’t get confused by the
use of g as the name of our graphic object. In the paint() method we used the g
variable to reference the applet’s device context. Here you should notice that g is
referencing the osGraphics object we created to act as an image buffer. This is an
example of how scoping works with variables in Java. Scoping is basically the
same as it is in other languages but we wanted to make sure you were aware of
what is going on here. Since the g variable is not declared anywhere outside the
methods, but simply declared within the method declaration as an argument, it
is available only to the method where it was created.
As you might have guessed, each of these methods is predefined in Java and they
have been overridden by our applet. The start() method is called after the init()
method finishes; start() actually belongs to the applet. It is called whenever the
applet is started, such as when the Web page the applet is assigned to is first
loaded and every time the page is referenced again from a Web browser.
The start() method checks to see if the thread for the applet has been created by
asking if the thread is equal to a null value. (A null value indicates that it has not
been created.) If the thread has not been created, Java creates a new thread using
the this keyword to tell Java to turn the current applet class we are running into
a thread. Then, start() calls the start() method of the thread to initiate its execu-
tion. We know this sounds weird! But make sure you understand that this start()
method is different then the start() method of the applet. Otherwise, you might
think this call will create an infinite loop.
The run() thread method is called repeatedly as the thread runs. It is the only
method that we were required to have because of the use of the runnable interface:
We use the sleep() method to pause the thread for a few milliseconds to slow it
down a little. This gives us a refresh rate of ten frames per second maximum. It
also gives the thread time to check for mouse clicks.
We then increment the xpos object to facilitate animation by calling the user-
defined setcoord() method. Here we also need to stop and check to see if the
text has gone completely off the left edge of the applet. We do this by checking
to see if xpos is less than negative fontLength:
Finally, we come to the stop() thread method, which is called whenever some-
one leaves the current Web page the applet is assigned to or otherwise closes the
applet.
In stop(), we check again to see if the thread is equal to null. If the thread is
active, we stop it using the thread’s stop() method. Then, we kill the thread by
setting it equal to null. You may think that garbage collection would take care of
killing the thread for us, but this is one case where you would not want to rely
on garbage collection. Why? There may be situations where you want to keep a
thread active as people move from page to page in the browser (of course, clos-
ing the browser will kill all applet threads).
At this point, the applet is ready to run. However, it would be nice to be able to start
and stop the TickerTape with a mouse click, so let’s add support for user input.
This handleEvent() method can be used for everything from mouse clicks to
key presses, to drag and drop functions. It is automatically called by the browser
whenever it senses that the user is trying to interact with the applet. The argu-
ment evt is the crucial part of this method. It tells us what event has occurred
and allows us to react accordingly.
Since we are filtering for all mouse clicks, we simply use an if..then statement to
check and see it the evt argument ever equals Event.MOUSE_DOWN. When
it does, we know that a button has been pressed. Since Java is a cross-platform
language, we do not have the ability to determine which button was pressed,
just that one was indeed pressed. If you are a Windows programmer only, it may
be possible to create code in C that detects the other mouse button clicks and
then passes that on to a Java program, but that’s more than we can get into here.
When we receive the word that a button has been pressed, we check to see if the
TickerTape is in motion (suspended is False or True). If it is not in motion, we
start it by calling the thread’s suspend() method. If it is already suspended, we
use the thread’s resume() method to start it back up again. Finally, we switch the
suspended Boolean object to be the opposite of what it was before the mouse
button was pressed.
If you do not have the Java Development Kit (JDK), check the Javasoft site
(http://www.javasoft.com). Read the online instructions to learn how to install
the JDK. Check out the resource guide from Appendix A for more information.
That’s It—Run It
Go ahead and compile the complete program, then run it. How does it look?
Try changing the parameters and the applet size. Does the text scale to the height
of the applet? If something does not work correctly go back and verify that all
your code is correct, recompile, and run the applet again. Make sure that when
you recompile an applet that you restart your browser. Many browsers, includ-
ing Netscape 2.0, do not reload Java applets when you hit the reload button.
They do however reread the HTML file. So, if you only made changes to the
parameters or size of the applet then you do not need to restart the browser.
Well, what do you think? Is Java going to rule the world? We can’t answer that,
but in just a few pages we have shown you how to create a fairly useful applet
that can be put to use immediately.
Now that we have hit many of the basics of Java programming, let’s look at the
details of the language. Over the next several chapters we will delve into the Java
language and explore the details of its structure and syntax.
Chapter
3
Java Language
Fundamentals
Java Language
Fundamentals
The language building blocks of Java are
similar to those found in C++, but keep a
close eye out because there are some subtle
differences. 3
After following the ticker tape adventure in the previous chapter, you should
now have a basic understanding of the Java language and its grammar—at least
you’ll know how to write a simple applet that can scroll text across the screen!
Unfortunately, we covered a number of Java programming features very quickly,
and we didn’t get a chance to explain the main language features in sufficient
detail. In this chapter and the ones that follow, we’ll slow down the pace a little and
uncover the key Java language features that you’ll need to know to write useful Java
programs. In particular, we’ll explain the basic Java language components in this
chapter—everything from comments to variable declarations. Then we’ll move
ahead and cover operators, expressions, and control structures in Chapter 4.
For those of you who are already familiar with programming, especially C or
C++ programming, this chapter and Chapter 4 should serve as a good hands-on
review. As we discuss Java, we’ll point out the areas in which Java differs from
other languages. If you don’t have much experience using structured program-
ming languages, this chapter will give you a good overview of the basic compo-
nents required to make programming languages like Java come alive.
The actual language components featured in this chapter include:
• Comments
• Identifiers
• Keywords
• Data types
• Variable declarations
57
58 Chapter 3
Lexical Structure
The lexical structure of a language refers to the elements of code that make the
code easy for us to understand, but have no effect on the compiled code. For
example, all the comments you place in a program to help you understand
how it works are ignored by the Java compiler. You could have a thousand
lines of comments for a twenty line program and the compiled bytecodes for
the program would be the same size if you took out all the comments. This
does not mean that all lexical structures are optional. It simply means that
they do not effect the bytecodes.
The lexical structures will discuss include:
• Comments
• Identifiers
• Keywords
• Separators
Java Language Fundamentals 59
Comments
Comments make your code easy to understand, modify, and use. But adding
comments to an application only after it is finished is not a good practice. More
often than not, you won’t remember what the code you write actually does after
you get away from it for a while. Unfortunately, many programmers follow this
time-honored tradition. We suggest you try to get in the habit of adding com-
ments as you write your code.
Java supports three different types of comment styles. The first two are taken
directly from C and C++. The third type of comment is a new one that can be
used to automatically create class and method documentation.
COMMENT STYLE #1
/* Comments here... */
/*
This program was written by Joe Smith.
It is the greatest program ever written!
*/
In the second example, the comment line is embedded within the program state-
ment. The compiler skips over the comment text, and thus the actual line of
code would be processed as:
/**
* Sample Java Application unique Java style comment
* @author Anthony Potts
* @version 1.0 superclass
*/ standard C++ style comment
class Test extends Object { // Begin Test class
// Define class variables
standard data type
variable static int i = 10;
variable
declarations static final double d = 3.09;
literal
/*
The main() method is automatically called when
the program is run. Any words typed after the program
name when it is run are placed in the args[] variable
which is an array of strings.
For this program to work properly, atleast one word must
be typed after the program name or else an error will occur.
*/
public static void main(String args[]) {
Test thisTest = new Test(); // Create instance (object) of class
String myName = "Anthony"; declaration and assignment
assignment operator
boolean returnValue;
string data type
System.out.println("Hello " + args[0] + " my name is " + myName);
if(thisTest.sameName(args[0], myName)) {
System.out.println("Your name is the same as mine!");
} else {
System.out.println("That's not my name!");
}
logical expression
while control while ( i > -1) {
statement
System.out.print(i + " ");
i -= 2;
}
Figure 3.1
A visual guide to the key Java language components.
62 Chapter 3
Programmers occasionally use this style of commenting while they are testing and de-
bugging code. For example, you could comment out part of an equation or expression:
COMMENT STYLE #2
// Comment here...
This style of commenting is borrowed from C++. Everything after the double
slash marks is ignored by the Java compiler. The comment is terminated by a
line return, so you can’t use multiple comment lines unless you start each line
with the double-slash. Examples:
base = 20;
// This comment example also won't work because the Java
compiler will treat this second line as a line of code
value = 50;
The comment used in the second example won’t work like you might intend
because the remainder of the line of code would be commented out (everything
after i <=). In the third example, the second comment line is missing the start-
ing // symbols, and the Java compiler will get confused because it will try to
process the comment line as if it were a line of code. Believe it or not, this type
of commenting mistake occurs often—so watch out for it!
COMMENT STYLE #3
/** Doc Comment here... */
This comment structure may look very similar to the C style of commenting,
but that extra asterisk at the beginning makes a huge difference. Of course,
remember that only one asterisk must be used as the comment terminator. The
Java Language Fundamentals 63
Java compiler still ignores the comment; but another program called
JAVADOC.EXE that ships with the Java Development Kit uses these comments
to construct HTML documentation files that describe your packages, classes,
and methods as well as all the variables they use.
Let’s look at the third style of commenting in more detail. If implemented cor-
rectly and consistently, this style of commenting can provide you with numer-
ous benefits. Figure 3.2 shows what the output of the JAVADOC program looks
like when run on a typical Java source file.
Figure 3.2
Sample output from the JAVADOC program.
64 Chapter 3
If you have ever looked at the Java API documentation on Sun’s Web site, Figure
3.2 should look familiar to you. In fact, the entire API documentation was cre-
ated this way.
JAVADOC will work if you have created comments or not. Figure 3.3 shows the
output from this simple application:
class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
Figure 3.3
Simple output from the JAVADOC program.
Java Language Fundamentals 65
/**
* Welcome to HelloWorld
* @author Anthony Potts
* @version 1.1
* @see java.lang.System
*/
class helloworld {
/**
* Main method of helloworld
*/
public static void main(String args[]) {
System.out.println("Hello World!");
}
}
If you now run JAVADOC, the browser will display what you see in Figure 3.4.
As you can see, this gives us much more information. This system is great for
producing documentation for public distribution. Just like all comments though,
it is up to you to make sure that the comments are accurate and plentiful enough
to be helpful. Table 3.1 lists the tags you can use in your class comments.
Identifiers
Identifiers are the names used for variables, classes, methods, packages, and in-
terfaces to distinguish them to the compiler. In the sample program from Chap-
ter 2 the identifier for the applet’s class was TickerTape. We also used identifiers
like fontHeight and fontWidth to name some of the variables.
Identifiers in the Java language should always begin with a letter of the alphabet,
either upper or lower case. The only exceptions to this rule are the underscore
symbol (_) and the dollar sign ($), which may also be used. If you try to use any
other symbol or a numeral as the initial character, you will receive an error.
After the initial character you are allowed to use numbers, but not all symbols.
You can also use almost all of the characters from the Unicode character set. If
you are not familiar with the Unicode character set or you get errors, we suggest
that you stick with the standard alphabetic characters.
The length of an identifier is basically unlimited. We managed to get up to a few
thousand characters before we got bored. It’s doubtful you will ever need nearly
that many characters, but it is nice to know that the Java compiler won’t limit
66 Chapter 3
Figure 3.4
The new JAVADOC output.
you if you want to create long descriptive names. The only limit you may en-
counter involves creating class names. Since class names are also used as file
names, you need to create names that will not cause problems with your operat-
ing system or anyone who will be using your program.
You must also be careful not to use any of the special Java keywords listed in the
next section. Here are some examples of valid identifiers:
Error Message:
D:\java\lib\test.java:1: Identifier expected.
Description:
An invalid character has been used in the class identifier. You will see this error
when the first character is invalid (especially when it is a number).
Code Example:
public class te?st {
}
Error Message:
D:\java\lib\test.java:1: '{' Expected
Description:
This is a common error that occurs when you have an invalid character in the
middle of an identifier. In this case, the question mark is invalid, so the compiler
gets confused where the class definition ends and its implementation begins.
Code Example:
public class #test {
}
Error Message:
D:\java\lib\test.java:1: Invalid character in input.
Description:
Here, the error stems from the fact that the initial character is invalid.
Code Example:
public class catch {
}
Error Message:
D:\java\lib\test.java:1: Identifier expected.
Description:
This error shows up when you use a protected keyword as an identifier.
Keywords
In Java, like other languages, there are certain keywords or “tokens” that are re-
served for system use. These keywords can’t be used as names for your classes,
variables, packages, or anything else. The keywords are used for a number of tasks
such as defining control structures (if, while, and for) and declaring data types (int,
char, and float). Table 3.2 provides the complete list of the Java keywords.
Java Language Fundamentals 69
The words marked with an asterisk (*) are not currently used in the Java lan-
guage, but you still can’t use them to create your own identifiers. More than
likely they will be used as keywords in future versions of the Java language.
Java Language Fundamentals 71
Literals
Literals are the values that you assign when entering explicit values. For ex-
ample, in an assignment statement like this:
i = 10;
the value 10 is a literal. But do not get literals confused with types. Even though
they usually go hand in hand, literals and types are not the same.
Types are used to define what type of data a variable can hold, while literals are
the values that are actually assigned to those variables.
Literals come in three flavors: numeric, character, and boolean. Boolean literals
are simply True and False
NUMERIC LITERALS
Numeric literals are just what they sound like—numbers. We can subdivide the
numeric literals further into integers and floating-point literals.
Integer literals are usually represented in decimal format although you can use
the hexadecimal and octal format in Java. If you want to use the hexadecimal
format, your numbers need to begin with an 0x or 0X. Octal integers simply
begin with a zero (0).
Integer literals are stored differently depending on their size. The int data type is
used to store 32-bit integer values ranging from -2,147,483,648 to 2,147,483,648
(decimal). If you need to use even larger numbers, Java switches over to thelong data
type, which can store 64 bits of information for a range of - 9.223372036855e+18
to 9.223372036855e+18. This would give you a number a little larger than 9 mil-
lion trillion—enough to take care of the national debt! To specify a long integer, you
will need to place an “l” or “L” at the end of the number. Don’t get confused by our
use of the terms int and long. There are many other integer data types used by Java,
but they all use int or longliterals to assign values. Table 3.3 provides a summary of
the two integer literals.
Here are some examples of how integer literals can be used to assign values in
Java statements:
int i;
i = 1; // All of these literals are of the integer type
i= -9;
i = 1203131;
float f;
f = 1.3; // All of these literals are of the floating-point
// type float (32-bit)
f = -9.0;
f = 1203131.1241234;
double d;
d = 1.0D; // All of these literals are of the floating-
// point type double(32-bit)
d = -9.3645e235;
d = 7.0001e52D;
Java Language Fundamentals 73
CHARACTER LITERALS
The second type of literal that you need to know about is the character literal. Char-
acter literals include single characters and strings. Single character literals are en-
closed in single quotation marks while string literals are enclosed in double quotes.
Single characters can be any one character from the Unicode character set. There
are also a few special two-character combinations that are non-printing characters
but perform important functions. Table 3.5 shows these special combinations.
The string character literal are any number of characters enclosed in The charac-
ter combinations from Table 3.5 also apply to strings. Here are some examples
of how character and string literals can be used in Java statements:
char ch;
ch = 'a'; // All of these literals are characters
ch = \n; // Assign the newline character
ch = \'; // Assign a single quote
ch = \x30; // Assign a hexadecimal character code
String str;
str = "Java string";
Operators
Operators are used to perform computations on one or more variables or ob-
jects. You use operators to add values, comparing the size of two numbers, as-
signing a value to a variable, incrementing the value of a variable, and so on.
Table 3.6 lists the operators used in Java. Later in this chapter, we’ll explain in
detail how each operator works; and we’ll also explain operator precedence.
continued
Java Language Fundamentals 75
Separators
Separators are used in Java to delineate blocks of code. For example, you use curly
brackets to enclose a method’s implementation, and you use parentheses to en-
close arguments being sent to a method. Table 3.7 lists the seperators used in Java.
byte
The byte type can be used for variables whose value falls between -256 and 255.
byte types have an 8-bit length. Here are some examples of byte values:
-7 5 238
short
The short numeric type can store values ranging from -32768 to 32767. It has a
16-bit depth. Here are some examples:
-7 256 -29524
int
The int data type takes the short type to the next level. It uses a 32-bit signed
integer value that takes our minimal and maximal value up to over 2 billion.
Because of this tremendous range, it is one of the most often used data types
for integers.
Often, unskilled programmers will use the int data type even though they
don’t need the full resolution that this data type provides. If you are using
smaller integers, you should consider using the short data type. The rule of
thumb to follow is if you know exactly the range of values a certain variable will
store, use the smallest data type possible. This will let your program use less memory
and therefore run faster, especially on slower machines or machines with lim-
ited RAM.
Here are some examples of int values:
long
The long data type is the mother of all integer types. It uses a full 64-bit data
path to store values that reach up to over 9 million trillion. But be extremely
careful when using variables of the long type. If you start using many of them or
God forbid, an array of longs, you can quickly eat up a ton of resources.
float
The float data type is one of two types used to store floating-point values. The
float type is compliant with the IEEE 754 conventions. The floating-point types
of Java can store gargantuan numbers. We do not have enough room on the page
to physically show you the minimal and maximal values the float data type can
store, so we will use a little bit of tricky sounding lingo taken from the Java manual.
“The finite nonzero values of type float are of the form s * m * 2e , where s is +1
or -1, m is a positive integer less than 2^24 and e is an integer between -149 and
104, inclusive.”
Whew, that’s a mouthful. Here are a few examples to show you what the float
type might look like in actual use:
double
As if the float type could not hold enough, the double data type gives you even
bigger storage space. Let’s look again at Sun’s definition of the possible values for
a double.
“The finite nonzero values of type float are of the form s * m * 2e , where s is +1
or -1, m is a positive integer less than 2^53 and e is an integer between -1045
and 1000, inclusive.”
Again, you can have some truly monstrous numbers here. But when you start
dealing with hard core programming, this type of number becomes necessary
from time to time, so it is wise to understand its ranges. Here are a few examples:
boolean
In other languages, the boolean data type has been represented by an integer
with a nonzero or zero value to represent True and False, respectively. This method
works well because it gives the user the ability to check for all kinds of values and
perform expression like this:
x=2;
if x then...
Java Language Fundamentals 79
This can be handy when performing parsing operations or checking string lengths.
In Java, however, the boolean data type has its own True and False literals that
do not correspond to other values. In fact, as you will learn later in this chapter,
Java does not even allow you to perform casts between the boolean data type
and any others. There are ways around this limitation that we will discuss in a
few pages when we talk about conversion methods.
char
The char data type is used to store single characters. Since Java uses the Unicode
character set, the char type needs to be able to store the thousands of characters,
so it uses a 16-bit signed integer. The char data type has the ability to be cast or
converted to almost all of the others, as we will show you in the next section.
string
The string type is actually not a primitive data type; it is a class all its own. We
decided to talk about it a little here because it is used so commonly that it might
as well be considered a primitive. In C and C++, strings are stored in arrays of
chars. Java does not use the char type for this but instead has created its own
class that handles strings. In Chapter 5, when we get into the details of declaring
variables within classes, you will see the difference between declaring a primitive
variable and declaring an instance of a class type.
One big advantage to using a class instead of an array of char types is that we are
more or less unlimited in the amount of information we want to place in a string
variable. In C++, the array of chars was limited, but now that limitation is taken
care of within the class, where we do not care how it is handled.
Variable Declarations
Declaring variables in Java is very similar to declaring variables in C/C++ as long
as you are using the primitive data types. As we said before, almost everything in
Java is a class—except the primitive data types. We will show you how to instan-
tiate custom data types (including strings) in Chapter 5. For now, let’s look at
how primitive data types are declared.
Here is what a standard declaration for a primitive variable might look like:
int i;
80 Chapter 3
We have just declared a variable “i” to be an integer. Here are a few more
examples:
byte i, j;
int a=7, b = a;
float f = 1.06;
String name = "Tony";
These examples illustrate some of the things you can do while declaring vari-
ables. Let’s look at each one individually.
int i;
This is the most basic declaration, with the data type followed by the variable
you are declaring.
byte i, j;
In this example, we are declaring two byte variables at one time. There is no
limit to the number of variables you can declare this way. All you have to do is
add a comma between each variable you wish to declare of the given type, and
Java takes care of it for you.
You also have the ability to assign values to variables as you declare them. You can
even use a variable you are declaring as part of an expression for the declaration of
another variable in the same line. Before we confuse you more, here is an example:
int i = 1;
int j = i, k= i + j;
Here we have first declared a variable i as int and assigned it a value of 1. In the
next line, we start by declaring a variable j to be equal to i. This is perfectly legal.
Next, on the same line, we declare a variable k to be equal to i plus j. Once again,
Java handles this without a problem. We could even shorten these two state-
ments to one line like this:
int i = 1, j = i, k= i + j;
One thing to watch out for is using variables before they have been declared.
Here’s an example:
Java Language Fundamentals 81
This would cause an “undefined variable” error because Java does not know to
look ahead for future declarations. Let’s look at another example:
float f = 1.06;
Does this look correct? Yes, but it’s not. This is a tricky one. By default, Java
assumes that numbers with decimal points are of type double. So, when you try
and declare a float to be equal to this number, you receive the following error:
Sounds complicated, but all this error message means is that you need to explicitly
tell Java that the literal value 1.06 is a float and not a double. There are two ways
to accomplish this. First, you can cast the value to a float like this:
float f = (float)1.06;
This works fine, but can get confusing. Java also follows the convention used by
other languages of placing an “f” at the end of the literal value to indicate explicitly
that it is a float. This also works for the double data type, except that you would
use a “d.” (By the way, capitalization of the f and d does not make a difference.)
float f = 1.06f;
double d = 1.06d;
You should realize that the “d” is not needed in the double declaration because
Java assumes it. However, it is better to label all of your variables when possible,
especially if you are not sure.
We will cover variables and declarations in more detail in Chapter 5, but you
should have enough knowledge now to be able to run a few basic programs and
will delve deeper into the Java fundamentals and look at operators, expressions,
and control statements.
82 Chapter 3
Using Arrays
It’s difficult to imagine creating any large application or applet without having
an array or two. Java uses arrays in a much different manner than other lan-
guages. Instead of being a structure that holds variables, arrays in Java are actu-
ally objects that can be treated just like any other Java object.
The powerful thing to realize here is that because arrays are objects that are
derived from a class, they have methods you can call to retrieve information
about the array or to manipulate the array. The current version of the Java lan-
guage only supports the length method, but you can expect that more methods
will be added as the language evolves.
One of the drawbacks to the way Java implements arrays is that they are only
one dimensional. In most other languages, you can create a two-dimensional
array by just adding a comma and a second array size. In Java, this does not
work. The way around this limitation is to create an array of arrays. Because this
is easy to do, the lack of built-in support for multi-dimensional arrays shouldn’t
hold you back.
Declaring Arrays
Since arrays are actually instances of classes (objects), we need to use construc-
tors to create our arrays much like we did with strings. First, we need to pick a
variable name and declare it as an array object and also specify which data type
the array will hold. Note that an array can only hold a single data type—you
can’t mix strings and integers within a single array. Here are a few examples of
how array variables are declared:
int intArray[];
String Names[];
As you can see, these look very similar to standard variable declarations, except
for the brackets after the variable name. You could also put the brackets after the
data type if you think this approach makes your declarations more readable:
int[] intArray;
String[] Names;
Java Language Fundamentals 83
Sizing Arrays
There are three ways to set the size of arrays. Two of them require the use of the
new operator. Using the new operator initializes all of the array elements to a
default value. The third method involves filling in the array elements with val-
ues as you declare it.
The first method involves taking a previously declared variable and setting the
size of the array. Here are a few examples:
Or, you can size the array object when you declare it:
Finally, you can fill in the array with values at declaration time:
intArray[i] = 1;
for(int p = 0; p <i; p++) intArray[i] *= 2 ;
}
for (int i = 0; i < intArray.length; i++)
System.out.println("2 to the power of " + i + " is " +
intArray[i]);
}
}
2 to the power of 0 is 1
2 to the power of 1 is 2
2 to the power of 2 is 4
2 to the power of 3 is 8
2 to the power of 4 is 16
2 to the power of 5 is 32
2 to the power of 6 is 64
2 to the power of 7 is 128
2 to the power of 8 is 256
2 to the power of 9 is 512
2 to the power of 10 is 1024
2 to the power of 11 is 2048
2 to the power of 12 is 4096
2 to the power of 13 is 8192
2 to the power of 14 is 16384
2 to the power of 15 is 32768
2 to the power of 16 is 65536
2 to the power of 17 is 131072
2 to the power of 18 is 262144
2 to the power of 19 is 524288
So, how does the program work? We first create our array of integer values and
assign it to the intArray variable. Next, we begin a loop that goes from zero to
intArray.length. By calling the length method of our array, we find the number
of indexes in the array. Then, we start another loop that does the calculation and
stores the result in the index specified by the i variable from our initial loop.
Now that we have filled in all the values for our array, we need to step back
through them and print out the result. We could have just put the print state-
ment in the initial loop, but the approach we used gives us a chance to use
another loop that references our array.
Java Language Fundamentals 85
arrayName[index];
Pretty simple. If you try and use an index that is outside the boundaries of the
array, a run-time error occurs. If we change the program to count to an index of
21 instead of the actual array length of 20, we would end up getting an error
message like this:
java.lang.ArrayIndexOutOfBoundsException: 20
at powersOf2.main(powersOf2.java:10)
This is a pretty common error in any programming language. You need to use
some form of exception handling to watch for this problem unless you are posi-
tive you can create code that never does this (in your dreams). See Chapter 7 for
additional information on exception handling.
Multidimensional Arrays
Multidimensional arrays are created in Java in using arrays of arrays. Here are a
few examples of how you can implement multidimensional arrays:
int intArray[][];
String Names[][];
We can even do the same things we did with a single dimension array. We can
set the array sizes and even fill in values while we declare the arrays:
We can also create arrays that are not “rectangular” in nature. That is, each array within
the main array can have a different number of elements. Here are a few examples:
Accessing the data in a multidimensional array is not much more difficult than
accessing data in a single-dimensional array. You just need to track the values for
each index. Be careful though, as you add dimensions, it becomes increasingly
easy to create out of bounds errors. Here are a few examples of how you can
declare multidimensional arrays, assign values, and access array elements:
We will cover variables and declarations in more detail in Chapter 5, but you
should have enough knowledge now to be able to run a few basic programs and
get the feel for Java programming.
Passing Arguments
The syntax for passing arguments themselves to a program is extremely simple.
Just start your programs as you usually would and add any number of argu-
ments to the end of the line with each one separated by a space. Here is a sample
call to a program named “myApp”:
In this case, we are calling the Java run-time interpreter and telling it to run he class
file “myApp.” We then are passing in three arguments: “open,” “640,” and “480.”
If you wanted to pass in a longer string with spaces as an argument, you could.
In this case, you enclose the string in quotation marks and Java will treat it as a
single argument. Here is an example:
Once again the name of the program is “myApp.” However, this time we are
only sending it two arguments: “Nice program!” and “640x480.” Note that the
quotes themselves are not passed, just the string between the quotes.
Reading in Arguments
Now that we know how to pass arguments, where are they stored? How can we
see them in our application? If you’ll recall, all applications have a main() method.
You should also notice that this method has an interesting argument structure:
Here, main() indicates that it takes an array named args[] of type String. Java
takes any command-line arguments and puts them into the args[] string array.
The array is dynamically resized to hold just the number of arguments passed,
or zero if none are passed. Note that the use of the args identifier is completely
arbitrary. You can use any word you want as long as it conforms to the Java
naming rules. You can even get a little more descriptive, like this:
88 Chapter 3
That may be a bit much, but you will never get confused as to what is in the array!
Accessing Arguments
Once we’ve passed in the arguments to an application and we know where they
are stored, how do we get to them? Since the arguments are stored in an array,
we can access them just like we would access strings in any other array. Let’s look
at a simple application that takes two arguments and prints them out:
class testArgs {
public static void main(String args[]) {
System.out.println(args[0]);
System.out.println(args[1]);
}
}
hello
world
onearg
java.lang.ArrayIndexOutOfBoundsException: 1
at testArgs.main(testArgs.java:4)
What happened? Since we only were passing a single argument, the reference to
args[1] is illegal and produces an error.
Java Language Fundamentals 89
So, how do we stop from getting an error? Instead of calling each argument in
line, we can use a for loop to step through each argument. We can check the
args.length variable to see if we have reached the last item. Our new code will
also recognize if no arguments have been passed and will not try and access the
array at all. Enough talking, here is the code:
class testArgs {
public static void main(String args[]) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
Now, no matter how many arguments are passed (or none) the application can
handle it.
Table 3.9 Classes and Their Associated Methods for Handling Data Types
Class Method Return
Integer parseInt(String) An integer value
Integer valueOf(String) An Integer object initialized to the value
represented by the specified String
Long parseLong(String) A long value
Long valueOf(String) A Long object initialized to the value rep
resented by the specified String
Double valueOf(String) A Double object initialized to the value
represented by the specified String
Float valueOf(String) A Float object initialized to the value rep
resented by the specified String
Chapter
4
Operators,
Expressions,
and Control
Structures
Operators,
Expressions,
and Control
Structures
To build useful Java programs you’ll need to
master the art of using operators, expres-
sions, and control structures.
4
Now that you know about the types of data you can use in Java, you need to
learn how to manipulate your data. The tools for manipulating data fall into
three categories—operators, expressions, and control structures—each playing a
more powerful role as you move up the ladder. In this chapter, we’ll discuss each
of the key Java operators—everything from assignment statements to bitwise
operators. Although Java operators are very similar to C/C++ operators, there
are a few subtle differences which we’ll point out. Next, we’ll show you the
basics for creating expressions with Java. Finally, in the last part of the chapter,
we’ll investigate the world of Java control structures.
Operator Precedence
As you are writing your code, you need to keep in mind which operators have
precedence over the others—the order in which operators take effect. If you are
93
94 Chapter 4
an experienced programmer or you can remember some of the stuff you learned
in your high school algebra classes, you shouldn’t have any problem with under-
standing the principles of operator precedence. The basic idea is that the out-
come or result of an expression like this
x = 5 * (7+4) - 3;
is determined by the order in which the operators are evaluated by the Java com-
piler. In general, all operators that have the same precedence are evaluated from
left to right. If the above expression were handled in this manner, the result
would be 36 (multiply 5 by 7, add 4, and then subtract 3). Because of prece-
dence, we know that some operators, such as (), are evaluated before operators
such as *. Therefore, the real value of this expression would be 52 (add 7 and 4,
multiply by 5, and then subtract 3).
The actual rules for operator precedence in Java are nearly identical to those
found in C/C++. The only difference is that C/C++ includes a few operators,
such as ->, that are not used in Java. Table 4.1 lists the major operators in order
of precedence. Notice that some operator symbols such as (-) show up twice.
The reason for this is because the operator has different meanings depending on
how it is used in an expression. For example, in an expression like this
x = 7 + -3;
the (-) operator is used as a unary operator to negate the value 3. In this case, it
would have a higher precedence than a standard additive operator (+ or -). In an
expression like this, on the other hand,
x = 7 - 3 + 5;
the (-) operator is used as a binary additive operator, and it shares the same
precedence with the (+) operator.
Assignment Operators
The most important and most often used operator is the assignment operator
(=). This operator does just what it looks like it should do; it takes whatever
variable is on the left and sets it equal to the expression on the right:
i = 35;
The expression on the right can be any valid Java expression—a literal, an equa-
tion with operands and operators, a method call, and so on. When using an
assignment operator, you must be careful that the variable you are using to re-
ceive the expression is the correct size and type to receive the result of the expres-
sion on the right side. For example, statements like the following could cause
you a lot of headaches:
short count;
// This number is way too big for a short type!
count = 500000000000;
char ch;
// Oops! We should be assigning a character here
ch = 100;
In the first example, the variable count is declared as a short, which means that
the variable can only hold a number as large as 32767. Obviously, the number
being assigned to the variable is way too large. In the second example, the vari-
able ch expects to receive a character but in reality is assigned something else
entirely.
If you look closely at the last line in Table 4.1, you’ll see that Java offers a num-
ber of variations of the standard assignment statement. They are all borrowed
from the C language. An assignment statement like this
num *= 5;
num = num * 5;
The combination assignment operators turn out to be very useful for writing
expressions inside loops that perform counting operations. Here’s an example:
In this case i is used as the loop “counting” control variable, and it is incremented
by using a combination assignment statement.
Integer Operators
In the category of integer operators, there are two flavors to choose from: unary
and binary. A unary operator performs a task on a single variable at a time.
Binary operators, on the other hand, must work with two variables at a time.
Let’s start with the unary operators.
UNARY OPERATORS
There are four integer unary operators: negation, bitwise complement, increment,
and decrement. They are used without an assignment operation. They simply
perform their operation on a given variable, changing its value appropriately.
NEGATION (-)
Unary negation changes the sign of an integer. You must be careful when reach-
ing the lower limits of integer variables because the negative limit is always one
greater than the positive limit. So, if you had a variable of type byte with a value
of -256 and you performed a unary negation on it, an error will occur because
the byte data type has a maximum positive value of 255. Here are some ex-
amples of how this operator can be used:
- k;
-someInt;
x = -50 + 10;
As we learned earlier, the negation operator is at the top end of the precedence
food chain; thus, you can count on operands that use it to be evaluated first.
++intIncrement;
--intDecrement;
BINARY OPERATORS
When you need to perform operations that involve two variables, you will be
dealing with binary operators. Simple addition and subtraction are prime ex-
amples of binary operators. These operators do not change the value of either of
the operands, instead they perform a function between the two operands that is
placed into a third. Table 4.3 lists the complete set of the binary integer opera-
tors. Let’s look at each of these operators in detail.
cause we assume you already know this stuff. We will, however, give you a
few examples:
MODULUS
The modulus operator divides the first operand by the second operand and
returns the remainder:
BITWISE OPERATORS
The bitwise binary operators perform operations at the binary level on integers.
They act much like custom if..then statements. They compare the respective bits
from each of the operands and set the corresponding bit of the return variable to
a 1 or 0 depending on which operator is used. The AND operator works as
follows: “if both bits are 1 then return a 1, otherwise return a 0.” The OR
operators works like this: “if either bit is a 1 then return a 1, otherwise return a
0.” Finally, the XOR operator works like this: “if the bits are different return a 1,
if they are the same return a 0.” Table 4.4 provides a set of examples that illus-
trate how each bitwise operator works.
And here are some code examples to show you how to incorporate bitwise op-
erators into your Java statements:
// X=3 (00000011)
// Y=2 (00000010)
Z = X & Y; // Answer: Z = 2X 00000011
// Y 00000010
// Z 00000010
Z = X | Y; // Answer: Z = 3X 00000011
// Y 00000010
// Z 00000011
Z = X ^ Y; // Answer: Z = 1X 00000011
// Y 00000010
// Z 00000001
100 Chapter 4
1 1 OR True
1 0 OR True
0 1 OR True
0 0 OR False
1 1 XOR False
1 0 XOR True
0 1 XOR True
0 0 XOR False
Boolean Operators
The boolean data type adds several new operators to the mix. All of the opera-
tors that can be used on boolean values are listed in Table 4.5.
// Bool1 = True
!Bool1; // Answer: Bool1 = False
Bool2 = true;
Bool3 = true;
Operators, Expressions, and Control Structures 101
Bool4 = False;
Bool5 = False;
Bool1 = Bool2 & Bool3; // Answer: Bool1 = True
Bool1 = Bool2 & Bool4; // Answer: Bool1 = False
Bool1 = Bool2 | Bool3; // Answer: Bool1 = False
Bool1 = Bool2 | Bool4; // Answer: Bool1 = True
Bool1 = Bool3 ^ Bool4; // Answer: Bool1 = False
Bool1 = Bool4 ^ Bool5; // Answer: Bool1 = True
op1 = True;
if (result == op1); // Answer: result = true
if (result != op1); // Answer: result = false
TERNARY OPERATOR
This powerful little operator acts like an extremely condensed if..then statement. If
you look at the example below you will see that if the operand is True, the expres-
sion before the colon is evaluated. If the operand is False, the expression after the
colon is evaluated. This type of coding may look a little strange at first. But once
you understand the logic, you’ll begin to see just how useful this operator can be.
In the following example, the parentheses are not actually needed, but when you
use more complicated expressions they will make the code much easier to follow:
behave just because integers behave a certain way. For example, just because an
expression like a==b may be true for two floating-point values, don’t assume that
an expression like a<b || a>b will be true. This is because floating-point values
are not ordered like integers. You also have to deal with the possibility of a
floating-point variable being equal to negative or positive infinity, -Inf and Inf,
respectively. You can get a positive or negative Inf when you perform an opera-
tion that returns an overflow.
Using Casts
In some applications you may need to transfer one type of variable to another.
Java provides us with casting methods to accomplish this. Casting refers to the
process of transforming one variable of a certain type into another data type.
Casting is accomplished by placing the name of the data type you wish to cast a
particular variable into in front of that variable in parentheses. Here is an ex-
ample of how a cast can be set up to convert a char into an int:
int a;
char b;
b = 'z';
a = (int) b;
short a;
char b;
a = 40;
b = (char) a; // Convert value 40 into a character
Casting is extremely simple when you are using the primitive data types—int,
char, short, double, and so on. You can also cast classes and interfaces in Java,
which we’ll show you how to do in Chapter 5.
The most important thing to remember when using casts is the space each vari-
able has to work with. Java will let you cast a variable of one data type into a
104 Chapter 4
variable of a different data type if the size of the data type of the target variable is
smaller than the other data type, but you may not like the result. Does this sound
confusing? Let’s explain this a little better. If you had a variable of type long, you
should only cast it into another variable of type float or double because these data
types are the only other two primitives with at least 64-bits of space to handle your
number. On the other hand, if you had a variable of type byte, then you could cast
it into any of the other primitives except boolean because they all have more space
than the lowly byte. When you are dealing with double variables, you are stuck,
since no other data type offers as much space as the double.
If you have to cast a variable into another variable having less space, Java will do
it. However, any information in the extra space will be lost. On the plus side
though, if the value of a larger variable is less than the maximum value of the
variable you are casting into, no information will be lost.
i = x + 10;
the variable x and the literal 10 are the operands and + is the operator. The evalu-
ation of an expression performs one or more operations that return a result. The
data type of the result is always determined by the data types of the operands(s).
When multiple operands are combined, they are referred to as a compound ex-
pression. The order in which the operators are evaluated is determined by the
precedence of the operators that act upon them. We discussed precedence earlier
and showed you the relative precedence of each Java operator.
The simplest form of expression is used to calculate a value, which in turn is
assigned to a variable in an assignment statement. Here are a few assignment
statements that use expressions that should look very familiar to you by now:
i = 2;
thisString = "Hello";
Operators, Expressions, and Control Structures 105
Here are a few assignment statements that are a little more involved:
Bool1 != Bool2;
i += 2;
d *= 1.9
Byte1 ^= Byte2;
An assignment expression involves a variable that will accept the result, followed
by a single assignment operator, followed by the operand that the assignment
operator is using.
The next step up the ladder is to create expressions that use operators like the
arithmetic operators we have already discussed:
i = i + 2;
thisString = "Hello";
Expressions with multiple operands are probably the most common type of ex-
pressions. They still have a variable that is assigned the value of the result pro-
duced by evaluating the operands and operators to the right of the equal sign.
You can also have expressions with many operators and operands like this:
i = i + 2 - 3 * 9 / 3;
thisString = "Hello" + "World, my name is " + myName;
The art of programming in Java involves using operators and operands to build
expressions, which are in turn used to build statements. Of course, the assign-
ment statement is just one type of statement that can be constructed. You can
also create many types of control statements, such as while and for loops, if-then
decision making statements, and so on. (We’ll look at all of the control state-
ments that can be written in Java in the last part of this chapter.)
There are essentially two types of statements you can write in Java: simple and com-
pound. A simple statement performs a single operation. Here are some examples:
The important thing to remember about simple statements in Java is that they
are always completed with a semicolon (;). (Some of the others like class declara-
106 Chapter 4
tions and compound if..else statements don’t need semicolons, but if you leave it
off the end of an expression, you’ll get an error.)
Compound statements involve the grouping of simple statements. In this case,
the characters ({ }) are used to group the separate statements into one compound
statement. Here are a few examples:
if (x < 10)
{
i = 20;
p = getvalue(i);
}
Notice that the (;) terminating character is not used after the final (}). The braces
take care of this for us.
if..else
The if..else control structure is probably used more than all the others com-
bined. How many programs have you written that didn’t include one? Not very
many, we’ll wager.
Operators, Expressions, and Control Structures 107
In its simplest terms, the if..else structure performs this operation: if this is true
then do that otherwise do something else. Of course, the “otherwise” portion is
optional. Since you probably already know what if..else statements are used for,
we will just show you a few examples so you can see how they work in Java.
Here is the structure labeled with standard terms:
if (boolean) statement
else statement;
Here is a sample of what an if..else statement might look like with actual code:
if (isLunchtime) {
Eat = true;
Hour = 12;
}
else {
Eat = False;
Hour = 0;
}
108 Chapter 4
if (isLunchtime) {
Eat = true;
Hour = 12;
}
else if (isBreakfast) {
Eat = true;
Hour = 6;
}
else if (isDinner) {
Eat = true;
Hour = 18;
}
else {
Eat = false;
Hour = 0;
}
The curly braces are used when multiple statements need to take place for each
option. If we were only performing a single operation for each part of the if..else
statement, we would not need the braces. Here is an example of an if..else state-
ment that uses curly braces for one part but not the other:
if (isLunchtime) {
Eat = true;
Hour = 12;
}
else Eat = False;
while (boolean) {
statement;
}
Operators, Expressions, and Control Structures 109
do {
statement
} while(boolean);
while and do..while loops are used if you want to repeat a certain statement or
block of statements until a certain expression becomes false. For example, as-
sume you wanted to send e-mail to all of the people at a particular Web site. You
could set up a while loop that stepped through all the people, one-by-one, send-
ing them e-mail until you reached the last person. When the last person is reached,
the loop is terminated and the program control flow moves on to the statement
following the loop. Here is what that loop might look like in very simple terms:
while (!done){
emailUser();
goNextuser();
if (noNewuser) done = true;
}
switch
The switch control flow structure is useful when you have a single expression
with many possible options. The same thing can be done using recursed if..else
statments, but that can get very confusing when you get past just a few options.
The if..else structure is also difficult to change when it becomes highly nested.
The swtich statement is executed by comparing the value of an initial expression
or variable with other variables or expressions. Let’s look at the labeled structure:
switch(expression) {
case expression: statement;
case expression: statement;
case expression: statement;
default: statement;
}
Now let’s look at a real piece of code that uses the switch structure:
char age;
110 Chapter 4
The break statement is extremely important when dealing with switch struc-
tures. If the switch finds a case that is true, it will execute the statements for that
case. When it is finished with that case, it will move on to the next one. This
process continues until a match is found or the default statement is reached.
The break statement tells the switch “OK, we found a match, let’s move on.”
The default clause serves as the “catch-all” statement. If all of the other cases fail,
the default clause will be executed.
for
for loops are another programming standard that would be tough to live with-
out. The idea behind a for loop is that we want to step through a sequence of
numbers until a limit is reached. The loop steps through our range in whatever
step increment we want, checking at the beginning of each loop to see if we have
caused our “quit” expression to become true.
Here is the labeled structure of a for loop:
The variable we use can either be one we have previously created, or it can be
declared from within the for structure. Expression1 from the above example is
the expression we need to stay true until the loop is finished. More often than
not, this expression is something like x<10 which means that we will step through
Operators, Expressions, and Control Structures 111
the loop until x is equal to 10 at which time the expression (x<10) becomse false
and drops us out of the loop.
Here is an example of a for loop that actually works:
If you put this code into an empty main method you should get the following
output:
0
1
2
3
4
5
6
7
8
9
For loops are used for many different applications. They are a necessity when dealing
with arrays and can really help when creating lookup tables or indexing a database.
labels
Java labels provide a means of controlling different kinds of loops. Sometimes,
when you create a loop, you need to be able to break out of it before it finishes
on its own and satisfies its completion expression. This is where labels come in
very handy.
The key to labels is the break statement that you learned to use with the switch
statement. You can also use the break statement to exit out of any loop. It is
great for breaking out of for loops and while loops especially.
However, sometimes you have embedded loops and you need to be able to break
out of a certain loop. A great example of this is two embedded for loops that are
setting values in an array. If an error occurs or you get a strange value, you may
want to be able to break out of one loop or another. It gets confusing if you have
112 Chapter 4
all these embedded loops and break statements all over with no apparent link to
one loop or another. labels rectify this situation.
To use a label, you simply place an identifier followed by a colon at the beginning
of the line that initiates a loop. Let’s look at an example before we go further:
Labels are probably new to most of you, so you may not see a need for them
right away. However, as your programs become more complicated you should
think about using lables where appropriate to make your code simple and
more readable.
Moving Ahead
We covered a lot of ground in this chapter and the previous one. If you are
new to Java programming and have little C or C++ background, make sure
you understand these concepts well so that you do not get confused in the
upcoming chapters.
Let’s now move on and discuss another basic structure of Java programming. In
fact, we would have to call it the basic structure of Java programming—the class.
Index
parameters, 39
A passing information, 367
Abstract classes, 33, 121, 158 sounds, 297
Abstract methods, 132 tags, 39
Abstract Window Toolkit, 32 threading, 51
Action( ) method, 294 ticker tape sample, 22
Add method, 274 vs. applications, 21
Addition, 98 Appletviewer, 7
Addressing Applications
Internet, 353 command line arguments, 86
Animation defined, 21
buffering, 40 networking, 353
speed, 26 sample menu, 268
API documentation, 64 vs. applets, 21
Applet class Architecture natural, 5
hierarchy, 288 Arguments
methods available, 288 accessing, 88
methods derived, 290 indexing, 89
Applets, 5, 6 numeric, 89
browser interaction, 294 passing, 87
class, 287 reading, 87
closing, 51 Arrays, 16, 82
compiling, 53 accessing data, 86
defined, 21 declaring, 82
drawbacks, 291 elements, 83
file access, 292 indexing, 85
file execution, 292 multidimensional, 85
fonts, 43 sizing, 83
images, 298 Assignment boolean operators, 102
navigation sample, 293 Assignment operators, 93, 95
network communication, 292 Audio clips, 297
package, 31 AWT, 31, 227
AWTError, 191
403
404 Index