Java Programming
Java Programming
net
ing
r
Sams.
Learn
Cente
Teach Yourself
JAVA
in 21 Days
S
S
F
Laura Lemay
Charles L. Perkins R
W
T
M
net
ing
r
Sams.
Learn
Cente
About This Book
This book teaches you all about the Java language and how to use it to create
applets and applications. By the time you get through with this book, you’ll know
enough about Java to do just about anything, inside an applet or out.
Conventions
Note: A Note box presents interesting pieces of information related to the surround-
ing discussion.
Technical Note: A Technical Note presents specific technical information related to
the surrounding discussion.
Tip: A Tip box offers advice or teaches an easier way to do something.
Caution: A Caution box alerts you to a possible problem and gives you advice to
! avoid it.
Warning: A Warning box advises you about potential problems and helps you steer
clear of disaster.
NEW☛
TERM New terms are introduced in New Term boxes, with the term in italics.
Type A type icon identifies some new HTML code that you can type in yourself.
Output An Output icon highlights what the same HTML code looks like when viewed by
either Netscape or Mosaic.
ii
vi
net
ing
r
Sams.
Learn
Cente
Overview
Introduction xxi
Week 1 at a Glance
Day 1 An Introduction to Java Programming 3
S
2 Object-Oriented Programming and Java 19
3 Java Basics 41
S
4 Working with Objects 61
5 Arrays, Conditionals, and Loops 79
F
6 Creating Classes and Applications in Java 95
7 More About Methods 111
Week 2 at a Glance
Day 8 Java Applet Basics R
129
9
10
Graphics, Fonts, and Color
Simple Animation and Threads
W 149
173
11
12
More Animation, Images, and Sound
Managing Simple Events and Interactivity T 195
217
M
13 User Interfaces with the Java Abstract Windowing Toolkit 237
14 Windows, Networking, and Other Tidbits 279
Week 3 at a Glance
Day 15 Modifiers 305
16 Packages and Interfaces 323
17 Exceptions 341
18 Multithreading 353
19 Streams 375
20 Native Methods and Libraries 403
21 Under the Hood 421
Appendixes
A Language Summary 473
B The Java Class Library 483
C How Java Differs from C and C++ 497
D How Java Differs from C and C++ 507
Index 511
vii
net
ing
r
Sams.
Learn
Cente
Contents
Introduction xxi
Week 1 at a Glance 1
Day 1 An Introduction to Java Programming 3
What Is Java? .............................................................................................. 4
Java’s Past, Present, and Future ................................................................... 6 S
Why Learn Java? ......................................................................................... 7
Java Is Platform-Independent................................................................. 7
S
F
Java Is Object-Oriented ......................................................................... 9
Java Is Easy to Learn .............................................................................. 9
Getting Started with
Programming in Java .............................................................................. 10
Getting the Software ............................................................................ 10
Applets and Applications ..................................................................... 11 R
W
Creating a Java Application .................................................................. 11
Creating a Java Applet ......................................................................... 13
T
Summary .................................................................................................. 16
Q&A ........................................................................................................ 16
M
Day 2 Object-Oriented Programming and Java 19
Thinking in Objects: An Analogy ............................................................. 20
Objects and Classes .................................................................................. 21
Behavior and Attributes ............................................................................ 23
Attributes ............................................................................................. 23
Behavior .............................................................................................. 24
Creating a Class ................................................................................... 24
Inheritance, Interfaces, and Packages ........................................................ 28
Inheritance........................................................................................... 29
Creating a Class Hierarchy................................................................... 30
How Inheritance Works ...................................................................... 32
Single and Multiple Inheritance ........................................................... 34
Interfaces and Packages ........................................................................ 34
Creating a Subclass ................................................................................... 35
Summary .................................................................................................. 38
Q&A ........................................................................................................ 39
Day 3 Java Basics 41
Statements and Expressions ...................................................................... 42
Variables and Data Types ......................................................................... 43
Declaring Variables .............................................................................. 43
Notes on Variable Names .................................................................... 44
ix
net
ing
r
Sams.
Learn
Cente
Day 5 Arrays, Conditionals, and Loops 79
Arrays ....................................................................................................... 80
Declaring Array Variables .................................................................... 80
Creating Array Objects ........................................................................ 81
Accessing Array Elements ..................................................................... 81
Changing Array Elements .................................................................... 82
Multidimensional Arrays...................................................................... 83
Block Statements ...................................................................................... 83
if Conditionals .......................................................................................... 83
The Conditional Operator ................................................................... 84
switch Conditionals ................................................................................... 85
for Loops .................................................................................................. 86
while and do Loops ................................................................................... 88
while Loops .......................................................................................... 88
do...while Loops ................................................................................... 89
Breaking Out of Loops ............................................................................. 89
Labeled Loops ...................................................................................... 90
Summary .................................................................................................. 91
Q&A ........................................................................................................ 92
Day 6 Creating Classes and Applications in Java 95
Defining Classes ....................................................................................... 96
Creating Instance and Class Variables ....................................................... 96
Defining Instance Variables ................................................................. 97
Constants ............................................................................................. 97
Class Variables ..................................................................................... 98
Creating Methods ..................................................................................... 99
Defining Methods ............................................................................... 99
The this Keyword ............................................................................... 101
Variable Scope and Method Definitions ............................................ 101
Passing Arguments to Methods .......................................................... 102
Class Methods ................................................................................... 104
Creating Java Applications ...................................................................... 105
Java Applications and Command-Line Arguments ................................. 106
Passing Arguments to Java Programs .................................................. 106
Handling Arguments in Your Java Program ....................................... 106
Summary ................................................................................................ 108
Q&A ...................................................................................................... 109
Day 7 More About Methods 111
Creating Methods with the Same Name, Different Arguments ............... 112
Constructor Methods ............................................................................. 115
Basic Constructors ............................................................................. 116
Calling Another Constructor ............................................................. 117
Overloading Constructors .................................................................. 117
xi
net
ing
r
Sams.
Learn
Cente
Day 10 Simple Animation and Threads 173
Creating Animation in Java .................................................................... 174
Painting and Repainting .................................................................... 174
Starting and Stopping
an Applet’s Execution ...................................................................... 175
Putting It Together ............................................................................ 175
Threads: What They Are
and Why You Need Them ................................................................... 177
The Problem with the Digital Clock Applet ...................................... 178
Writing Applets with Threads ............................................................ 179
Fixing The Digital Clock ................................................................... 180
Reducing Animation Flicker ................................................................... 182
Flicker and How to Avoid It .............................................................. 182
How to Override Update ................................................................... 183
Solution One: Don’t Clear the Screen ............................................... 183
Solution Two: Redraw
Only What You Have To ................................................................ 186
Summary ................................................................................................ 192
Q&A ...................................................................................................... 192
Day 11 More Animation, Images, and Sound 195
Retrieving and Using Images .................................................................. 196
Getting Images .................................................................................. 196
Drawing Images ................................................................................. 198
Modifying Images .............................................................................. 201
Creating Animation Using Images .......................................................... 201
An Example: Neko............................................................................. 201
Retrieving and Using Sounds .................................................................. 209
Sun’s Animator Applet ........................................................................... 211
More About Flicker: Double-Buffering................................................... 212
Creating Applets with Double-Buffering............................................ 212
An Example: Checkers Revisited ........................................................ 213
Summary ................................................................................................ 214
Q&A ...................................................................................................... 215
Day 12 Managing Simple Events and Interactivity 217
Mouse Clicks .......................................................................................... 218
mouseDown and mouseUp ................................................................... 219
An Example: Spots ............................................................................. 220
Mouse Movements ................................................................................. 223
mouseDrag and mouseMove ................................................................. 223
mouseEnter and mouseExit .................................................................. 223
An Example: Drawing Lines .............................................................. 224
Keyboard Events ..................................................................................... 228
The keyDown Method ....................................................................... 228
Default Keys ...................................................................................... 229
xiii
xiv
net
ing
r
Sams.
Learn
Cente
Networking in Java ................................................................................. 289
Creating Links Inside Applets ............................................................ 290
Opening Web Connections ............................................................... 292
openStream() ...................................................................................... 293
The URLconnection Class ................................................................... 296
Sockets ............................................................................................... 296
Other Applet Hints ................................................................................ 297
The showStatus Method ..................................................................... 297
Applet Information ............................................................................ 298
Communicating Between Applets ...................................................... 298
Summary ................................................................................................ 299
Q&A ...................................................................................................... 300
Week 3 at a Glance 303
Day 15 Modifiers 305
Method and Variable Access Control ...................................................... 307
The Four P’s of Protection ................................................................. 307
The Conventions for Instance Variable Access ................................... 312
Class Variables and Methods .................................................................. 314
The final Modifier .................................................................................. 316
final Classes ....................................................................................... 316
final Variables .................................................................................... 317
final Methods .................................................................................... 317
abstract Methods and Classes .................................................................. 319
Summary ................................................................................................ 320
Q&A ...................................................................................................... 320
Day 16 Packages and Interfaces 323
Packages ................................................................................................. 324
Programming in the Large ................................................................. 324
Programming in the Small ................................................................. 327
Hiding Classes ................................................................................... 329
Interfaces ................................................................................................ 331
Programming in the Large ................................................................. 331
Programming in the Small ................................................................. 335
Summary ................................................................................................ 338
Q&A ...................................................................................................... 339
Day 17 Exceptions 341
Programming in the Large ...................................................................... 342
Programming in the Small ...................................................................... 345
The Limitations Placed on the Programmer ........................................... 348
The finally Clause ................................................................................... 349
Summary ................................................................................................ 350
Q&A ...................................................................................................... 351
xv
xvi
net
ing
r
Sams.
Learn
Cente
A Native Library ..................................................................................... 417
Linking It All ..................................................................................... 418
Using Your Library ............................................................................ 418
Summary ................................................................................................ 418
Q&A ...................................................................................................... 419
Day 21 Under the Hood 421
The Big Picture ...................................................................................... 422
Why It’s a Powerful Vision ................................................................ 423
The Java Virtual Machine ....................................................................... 423
An Overview ...................................................................................... 424
The Fundamental Parts...................................................................... 426
The Constant Pool ............................................................................ 430
Limitations ........................................................................................ 430
Bytecodes in More Detail ....................................................................... 431
The Bytecode Interpreter ................................................................... 431
The “Just-in-Time” Compiler ............................................................ 432
The java2c Translator ........................................................................ 433
The Bytecodes Themselves ................................................................ 434
The _quick Bytecodes ........................................................................ 450
The .class File Format ............................................................................. 452
Method Signatures ................................................................................. 454
The Garbage Collector ........................................................................... 455
The Problem ...................................................................................... 455
The Solution ...................................................................................... 456
Java’s Parallel Garbage Collector ........................................................ 459
The Security Story .................................................................................. 459
Why You Should Worry .................................................................... 459
Why You Might Not Have To .......................................................... 460
Java’s Security Model ......................................................................... 460
Summary ................................................................................................ 470
Q&A ...................................................................................................... 470
A Language Summary 473
Reserved Words ...................................................................................... 474
Comments .............................................................................................. 475
Literals .................................................................................................... 475
Variable Declaration ............................................................................... 476
Variable Assignment ............................................................................... 476
Operators ............................................................................................... 477
Objects ................................................................................................... 478
Arrays ..................................................................................................... 478
Loops and Conditionals .......................................................................... 478
Class Definitions .................................................................................... 479
Method and Constructor Definitions ..................................................... 479
Packages, Interfaces, and Importing ........................................................ 480
Exceptions and Guarding ....................................................................... 481
xvii
xviii
net
ing
r
Sams.
Learn
Cente
Acknowledgments
From Laura Lemay:
To Sun’s Java team, for all their hard work on Java the language and on the browser, and
particularly to Jim Graham, who demonstrated Java and HotJava to me on very short notice in
May and planted the idea for this book.
To everyone who bought my previous books, and liked them. Buy this one too.
From Charles L. Perkins:
To Patrick Naughton, who first showed me the power and the promise of OAK (Java) in early
1993.
To Mark Taber, who shepherded this lost sheep through his first book.
xix
Charles L. Perkins is the founder of Virtual Rendezvous, a company building what it spent two
years designing: a software layer above Java that will foster socially focused, computer-mediated,
real-time filtered interactions between people’s personas in the virtual environments of the near
future. In previous lives, he has evangelized NeXTSTEP, Smalltalk, and UNIX, and has degrees
in both physics and computer science. Before attempting this book, he was an amateur
columnist and author. He’s done research in speech recognition, neural nets, gestural user
interfaces, computer graphics, and language theory, but had the most fun working at Thinking
Machines and Xerox PARC’s Smalltalk group. In his spare time, he reads textbooks for fun.
You can reach him via e-mail at virtual@[Link], or visit his Java page at http://
[Link]/java.
xx
net
ing
r
Sams.
Learn
Cente
Introduction
The World Wide Web, for much of its existence, has been a method for distributing passive
information to a widely distributed number of people. The Web has, indeed, been exceptionally
good for that purpose. With the addition of forms and image maps, Web pages began to become
interactive—but the interaction was often simply a new way to get at the same information. The
limitations of Web distribution were all too apparent once designers began to try to stretch the
boundaries of what the Web can do. Even other innovations, such as Netscape’s server push to
create dynamic animations, were merely clever tricks layered on top of a framework that wasn’t
built to support much other than static documents with images and text.
Enter Java, and the capability for Web pages of containing Java applets. Applets are small
programs that create animations, multimedia presentations, real-time (video) games, multi-user
networked games, and real interactivity—in fact, most anything a small program can do, Java
applets can. Downloaded over the net and executed inside a Web page by a browser that supports
Java, applets are an enormous step beyond standard Web design.
The disadvantage of Java is that to create Java applets right now, you need to write them in the
Java language. Java is a programming language, and as such, creating Java applets is more
difficult than creating a Web page or a form using HTML. Soon there will be tools and programs
that will make creating Java applets easier—they may be available by the time you read this. For
now, however, the only way to delve into Java is to learn the language and start playing with the
raw Java code. Even when the tools come out, you may want to do more with Java than the tools
can provide, and you’re back to learning the language.
That’s where Teach Yourself Java in 21 Days comes in. This book teaches you all about the Java
language and how to use it to create not only applets, but also applications, which are more
general Java programs that don’t need to run inside a Web browser. By the time you get through
with this book, you’ll know enough about Java to do just about anything, inside an applet or
out.
xxi
■ You had some Basic or Pascal in school, you’ve got a basic grasp of what programming
is, but you’ve heard Java is easy to learn, really powerful, and very cool.
■ You’ve programmed C and C++ for many years, you’ve heard this Java thing is
becoming really popular, and you’re wondering what all the fuss is all about.
■ You’ve heard that Java is really good for Web-based applets, and you’re curious about
how good it is for creating more general applications.
What if you know programming, but you don’t know object-oriented programming? Fear not.
Teach Yourself Java in 21 Days assumes no background in object-oriented design. If you know
object-oriented programming, the first couple of days will be easy for you.
What if you’re a rank beginner? This book might move a little fast for you. Java is a good language
to start with, though, and if you take it slow and work through all the examples, you may still
be able to pick up Java and start creating your own applets.
xxii
net
ing
r
Sams.
Learn
Cente
■ On Day 2, you’ll explore basic object-oriented programming concepts as they apply to
Java.
■ On Day 3, you start getting down to details with the basic Java building blocks: data
types, variables, and expressions such as arithmetic and comparisons.
■ Day 4 goes into detail about how to deal with objects in Java: how to create them,
how to access their variables and call their methods, and how to compare and copy
them. You’ll also get your first glance at the Java class libraries.
■ On Day 5, you’ll learn more about Java with arrays, conditional statements. and
loops.
■ Day 6 is the best one yet. You’ll learn how to create classes, the basic building blocks
of any Java program, as well as how to put together a Java application (an application
being a Java program that can run on its own without a Web browser).
■ Day 7 builds on what you learned on Day 6. On Day 7, you’ll learn more about how
to create and use methods, including overriding and overloading methods and
creating constructors.
Week 2 is dedicated to applets and the Java class libraries:
■ Day 8 provides the basics of applets—how they’re different from applications, how to
create them, and the most important parts of an applet’s life cycle. You’ll also learn
how to create HTML pages that contain Java applets.
■ On Day 9, you’ll learn about the Java classes for drawing shapes and characters to the
screen—in black, white, or any other color.
■ On Day 10, you’ll start animating those shapes you learned about on Day 9, includ-
ing learning what threads and their uses are.
■ Day 11 covers more detail about animation, adding bitmap images and audio to the
soup.
■ Day 12 delves into interactivity—handling mouse and keyboard clicks from the user
in your Java applets.
■ Day 13 is ambitious; on that day you’ll learn about using Java’s Abstract Windowing
Toolkit to create a user interface in your applet including menus, buttons, checkboxes,
and other elements.
■ On Day 14, you explore the last of the main Java class libraries for creating applets:
windows and dialogs, networking, and a few other tidbits.
Week 3 finishes up with advanced topics, for when you start doing larger and more complex Java
programs, or when you want to learn more:
■ On Day 15, you’ll learn more about the Java language’s modifiers—for abstract and
final methods and classes as well as for protecting a class’s private information from
the prying eyes of other classes.
xxiii
■ Day 16 covers interfaces and packages, useful for abstracting protocols of methods to
aid reuse and for the grouping and categorization of classes.
■ Day 17 covers exceptions: errors and warnings and other abnormal conditions,
generated either by the system or by you in your programs.
■ Day 18 builds on the thread basics you learned on Day 10 to give a broad overview of
multithreading and how to use it to allow different parts of your Java programs to run
in parallel.
■ On Day 19, you’ll learn all about the input and output streams in Java’s I/O library.
■ Day 20 teaches you about native code—how to link C code into your Java programs
to provide missing functionality or to gain performance.
■ Finally, on Day 21, you’ll get an overview of some of the “behind-the-scenes” techni-
cal details of how Java works: the bytecode compiler and interpreter, the techniques
Java uses to ensure the integrity and security of your programs, and the Java garbage
collector.
to mimic the way text looks on your screen. Variables and placeholders will appear in monospace
italic.
The end of each chapter offers common questions asked about that day’s subject matter with
answers from the authors.
xxiv
net
ing
SWEEK
r
Sams.
Learn
Cente
S
1
F 1
AT A GLANCE
R
W 2
T
M 3
4
■ An Introduction to Java Programming
Platform independence
The Java compiler and the java interpreter
■ Object-Oriented Programming and Java 5
Objects and classes
Encapsulation
Modularity
■ Java Basics 6
Java statements and expressions
Variables and data types
Comparisons and logical operators
■ Working with Objects 7
Testing and modifying instance variables
Converting objects
■ Arrays, Conditionals, and Loops
Conditional tests
Iteration
Block statements
1
M
T
W
R
WEEK
1 Week 1 at a Glance
net
ing
r
Sams.
Learn
Cente
1
1
S
S WEEK
1
F
R
W
An Introduction to
T Programming
Java
M
by Laura Lemay
M
T
W
R
DAY
Hello and welcome to Teach Yourself Java in 21 Days! Starting today and for the next three weeks
you’ll learn all about the Java language and how to use it to create applets, as well as how to create
stand-alone Java applications that you can use for just about anything.
NEW☛ An applet is a dynamic and interactive program that can run inside a Web page displayed
TERM by a Java-capable browser such as HotJava or Netscape 2.0.
The HotJava browser is a World Wide Web browser used to view Web pages, follow links, and
submit forms. It can also download and play applets on the reader’s system.
That’s the overall goal for the next three weeks. Today, the goals are somewhat more modest,
and you’ll learn about the following:
■ What exactly Java and HotJava are, and their current status
■ Why you should learn Java—its various features and advantages over other program-
ming languages
■ Getting started programming in Java—what you’ll need in terms of software and
background, as well as some basic terminology
■ How to create your first Java programs—to close this day, you’ll create both a simple
Java application and a simple Java applet!
What Is Java?
Java is an object-oriented programming language developed by Sun Microsystems, a company
best known for its high-end Unix workstations. Modeled after C++, the Java language was
designed to be small, simple, and portable across platforms and operating systems, both at the
source and at the binary level (more about this later).
Java is often mentioned in the same breath as HotJava, a World Wide Web browser from Sun
like Netscape or Mosaic (see Figure 1.1). What makes HotJava different from most other
browsers is that, in addition to all its basic Web features, it can also download and play applets
on the reader’s system. Applets appear in a Web page much in the same way as images do, but
unlike images, applets are dynamic and interactive. Applets can be used to create animations,
figures, or areas that can respond to input from the reader, games, or other interactive effects on
the same Web pages among the text and graphics.
Although HotJava was the first World Wide Web browser to be able to play Java applets, Java
support is rapidly becoming available in other browsers. Netscape 2.0 provides support for Java
applets, and other browser developers have also announced support for Java in forthcoming
products.
net
ing
r
Sams.
Learn
Cente
Figure 1.1.
The HotJava browser.
1
To create an applet, you write it in the Java language, compile it using a Java compiler, and refer
to that applet in your HTML Web pages. You put the resulting HTML and Java files on a Web
site much in the same way that you make ordinary HTML and image files available. Then, when
someone using the HotJava browser (or other Java-aware browser) views your page with the
embedded applet, that browser downloads the applet to the local system and executes it, and
then the reader can view and interact with your applet in all its glory (readers using other
browsers won’t see anything). You’ll learn more about how applets, browsers, and the World
Wide Web work together further on in this book.
The important thing to understand about Java is that you can do so much more with it besides
create applets. Java was written as a full-fledged programming language in which you can
accomplish the same sorts of tasks and solve the same sorts of problems that you can in other
programming languages, such as C or C++. HotJava itself, including all the networking, display,
and user interface elements, is written in Java.
M
T
W
R
DAY
net
ing
r
Sams.
Learn
Cente
tools to help develop Java applications (debuggers, development environments, and so on) most
likely will be rapidly available as well.
1
Why Learn Java?
At the moment, probably the most compelling reason to learn Java—and probably the reason
you bought this book—is that HotJava applets are written in Java. Even if that were not the case,
Java as a language has significant advantages over other languages and other programming
environments that make it suitable for just about any programming task. This section describes
some of those advantages.
Java Is Platform-Independent
Platform independence is one of the most significant advantages that Java has over other
programming languages, particularly for systems that need to work on many different platforms.
Java is platform-independent at both the source and the binary level.
NEW☛ Platform-independence is a program’s capability of moving easily from one computer
TERM system to another.
At the source level, Java’s primitive data types have consistent sizes across all development
platforms. Java’s foundation class libraries make it easy to write code that can be moved from
platform to platform without the need to rewrite it to work with that platform.
Platform-independence doesn’t stop at the source level, however. Java binary files are also
platform-independent and can run on multiple problems without the need to recompile the
source. How does this work? Java binary files are actually in a form called bytecodes.
NEW☛ Bytecodes are a set of instructions that looks a lot like some machine codes, but that is not
TERM specific to any one processor.
Normally, when you compile a program written in C or in most other languages, the compiler
translates your program into machine codes or processor instructions. Those instructions are
specific to the processor your computer is running—so, for example, if you compile your code
on a Pentium system, the resulting program will run only on other Pentium systems. If you want
to use the same program on another system, you have to go back to your original source, get a
compiler for that system, and recompile your code. Figure 1.2 shows the result of this system:
multiple executable programs for multiple systems.
Things are different when you write code in Java. The Java development environment has two
parts: a Java compiler and a Java interpreter. The Java compiler takes your Java program and
instead of generating machine codes from your source files, it generates bytecodes.
M
T
W
R
DAY
Binary File
Figure 1.2. (Pentium)
Traditional compiled
programs.
Your Code
Compiler (Pentium) Binary File
(PowerPC)
Compiler (SPARC)
To run a Java program, you run a program called a bytecode interpreter, which in turn executes
your Java program (see Figure 1.3). You can either run the interpreter by itself, or—for applets—
there is a bytecode interpreter built into HotJava and other Java-capable browsers that runs the
applet for you.
Figure 1.3.
Window
Java programs.
Java Interpreter
Java Bytecode (Pentium)
Java Code Java Compiler (Platform- Window
(Pentium) Independent)
Java Compiler
(PowerPC) Java Interpreter
(PowerPC)
Window
Java Compiler
(SPARC)
Java Interpreter
(SPARC)
net
ing
r
Sams.
Learn
Cente
Why go through all the trouble of adding this extra layer of the bytecode interpreter? Having
your Java programs in bytecode form means that instead of being specific to any one system, your
programs can be run on any platform and any operating or window system as long as the Java 1
interpreter is available. This capability of a single binary file to be executable across platforms
is crucial to what enables applets to work, because the World Wide Web itself is also platform-
independent. Just as HTML files can be read on any platform, so applets can be executed on any
platform that is a Java-capable browser.
The disadvantage of using bytecodes is in execution speed. Because system-specific programs
run directly on the hardware for which they are compiled, they run significantly faster than Java
bytecodes, which must be processed by the interpreter. For many Java programs, the speed may
not be an issue. If you write programs that require more execution speed than the Java interpreter
can provide, you have several solutions available to you, including being able to link native code
into your Java program or using tools to convert your Java bytecodes into native code. Note that
by using any of these solutions, you lose the portability that Java bytecodes provide. You’ll learn
about each of these mechanisms on Day 20.
Java Is Object-Oriented
To some, object-oriented programming (OOP) technique is merely a way of organizing
programs, and it can be accomplished using any language. Working with a real object-oriented
language and programming environment, however, enables you to take full advantage of object-
oriented methodology and its capabilities of creating flexible, modular programs and reusing
code.
Many of Java’s object-oriented concepts are inherited from C++, the language on which it is
based, but it borrows many concepts from other object-oriented languages as well. Like most
object-oriented programming languages, Java includes a set of class libraries that provide basic
data types, system input and output capabilities, and other utility functions. These basic classes
are part of the Java development kit, which also has classes to support networking, common
Internet protocols, and user interface toolkit functions. Because these class libraries are written
in Java, they are portable across platforms as all Java applications are.
You’ll learn more about object-oriented programming and Java tomorrow.
M
T
W
R
DAY
Java is modeled after C and C++, and much of the syntax and object-oriented structure is
borrowed from the latter. If you are familiar with C++, learning Java will be particularly easy for
you, because you have most of the foundation already.
Although Java looks similar to C and C++, most of the more complex parts of those languages
have been excluded from Java, making the language simpler without sacrificing much of its
power. There are no pointers in Java, nor is there pointer arithmetic. Strings and arrays are real
objects in Java. Memory management is automatic. To an experienced programmer, these
omissions may be difficult to get used to, but to beginners or programmers who have worked
in other languages, they make the Java language far easier to learn.
Note: The Java Development Kit is currently in beta release. By the time you read
this, The JDK may be available for other platforms, or other organizations may be
selling Java development tools as well.
Although Netscape and other Java-aware browsers provide an environment for playing Java
applets, they do not provide a mechanism for developing Java applications. For that, you need
separate tools—merely having a browser is not enough.
10
net
ing
r
Sams.
Learn
Cente
Applets and Applications
Java applications fall into two main groups: applets and applications. 1
Applets, as you have learned, are Java programs that are downloaded over the World Wide Web
and executed by a Web browser on the reader’s machine. Applets depend on a Java-capable
browser in order to run (although they can also be viewed using a tool called the appletviewer,
which you’ll learn about later today).
Java applications are more general programs written in the Java language. Java applications don’t
require a browser to run, and in fact, Java can be used to create most other kinds of applications
that you would normally use a more conventional programming language to create. HotJava
itself is a Java application.
A single Java program can be an applet or an application or both, depending on how you write
that program and the capabilities that program uses. Throughout this first week, you’ll be
writing mostly HotJava applications; then you’ll apply what you’ve learned to write applets in
Week 2. If you’re eager to get started with applets, be patient. Everything that you learn while
you’re creating simple Java applications will apply to creating applets, and it’s easier to start with
the basics before moving onto the hard stuff. You’ll be creating plenty of applets in Week 2.
11
M
T
W
R
DAY
! Warning: The numbers before each line are part of the listing and not part of the
program; they’re there so I can refer to specific line numbers when I explain what’s
going on in the program. Do not include them in your own file.
Note: In these examples, and in all the examples throughout this book, we’ll be
using Sun’s Java compiler, part of the JDK. If you have a third-party development
environment, check with the documentation for that program to see how to
compile your Java programs.
The compiler should compile the file without any errors. If you get errors, go back and make
sure that you’ve typed the program exactly as it appears in Listing 1.1.
When the program compiles without errors, you end up with a file called [Link], in
the same directory as your source file. This is your Java bytecode file. You can then run that
bytecode file using the Java interpreter. In the JDK, the Java interpreter is called simply java.
Make sure the java program is in your path and type java followed by the name of the file without
the .class extension:
java HelloWorld
12
net
ing
r
Sams.
Learn
Cente
If your program was typed and compiled correctly, you should get the string “Hello World!”
printed to your screen as a response.
1
Note: Remember, the Java compiler and the Java interpreter are different things.
You use the Java compiler (javac) for your Java source files to create .class files, and
you use the Java interpreter (java)to actually run your class files.
Note: Actually, if you run the Hello World application as an applet, the Hello
World message prints to a special window or to a log file, depending on how the
browser has screen messages set up. It will not appear on the screen unless you
write your applet to put it there.
In the next example, you create that simple Hello World applet, place it inside a Web page, and
view the result.
First, you set up an environment so that your Java-capable browser can find your HTML files
and your applets. Much of the time, you’ll keep your HTML files and your applet code in the
same directory. Although this isn’t required, it makes it easier to keep track of each element. In
this example, you use a directory called HTML that contains all the files you’ll need.
mkdir HTML
13
M
T
W
R
DAY
Save that file inside your HTML directory. Just like with Java applications, give your file a name
that has the same name as the class. In this case, the filename would be [Link].
Features to note about applets? There are a couple I’d like to point out:
■ The import line at the top of the file is somewhat analogous to an #include statement
in C; it enables this applet to interact with the JDK classes for creating applets and for
drawing graphics on the screen.
■ The paint() method displays the content of the applet onto the screen. Here, the
string Hello World gets drawn. Applets use several standard methods to take the place
of main(), which include init() to initialize the applet, start() to start it running,
and paint() to display it to the screen. You’ll learn about all of these in Week 2.
Now, compile the applet just as you did the application, using javac, the Java compiler.
javac [Link]
Again, just as for applications, you should now have a file called [Link] in your
HTML directory.
To include an applet in a Web page, you refer to that applet in the HTML code for that Web
page. Here, you create a very simple HTML file in the HTML directory (see Listing 1.3).
14
net
ing
r
Sams.
Learn
Cente
You refer to an applet in your HTML files with the <APPLET> tag. You’ll learn more about
Analysis <APPLET> later on, but here are two things to note:
■ Use the CODE attribute to indicate the name of the class that contains your applet.
1
■ Use the WIDTH and HEIGHT attributes to indicate the size of the applet. The browser uses
these values to know how big a chunk of space to leave for the applet on the page.
Here, a box 150 pixels wide and 25 pixels high is created.
Save the HTML file in your HTML directory, with a descriptive name (for example, you might
name your HTML file the same name as your applet—[Link]).
And now, you’re ready for the final test—actually viewing the result of your applet. To view the
applet, you need one of the following:
■ A browser that supports Java applets, such as Netscape 2.0.
■ The appletviewer application, which is part of the JDK. The appletviewer is not a
Web browser and won’t enable you to see the entire Web page, but it’s acceptable for
testing to see how an applet will look and behave if there is nothing else available.
Note: Do not use the alpha version of HotJava to view your applets; applets
developed with the beta JDK and onward cannot be viewed by the alpha HotJava.
If, by the time you read this, there is a more recent version of HotJava, you can use
that one instead.
If you’re using a Java-capable browser such as Netscape to view your applet files, you can use the
Open Local... item under the File menu to navigate to the HTML file containing the applet
(make sure you open the HTML file and not the class file). You don’t need to install anything
on a Web server yet; all this works on your local system.
If you don’t have a Web browser with Java capabilities built into it, you can use the appletviewer
program to view your Java applet. To run appletviewer, just indicate the path to the HTML file
on the command line:
appletviewer HTML/[Link]
Tip: Although you can start appletviewer from the same directory as your HTML
and class files, you may not be able to reload that applet without quitting
appletviewer first. If you start appletviewer from some other directory (as in the
previous command line), you can modify and recompile your Java applets and then
just use the Reload menu item to view the newer version.
15
M
T
W
R
DAY
Now, if you use the browser to view the applet, you see something similar to the image shown
in Figure 1.4. If you’re using appletviewer, you won’t see the text around the applet (My Java
applet says...), but you will see the Hello World itself.
Figure 1.4.
The Hello World applet.
Summary
Today, you got a basic introduction to the Java language and its goals and features. Java is a
programming language, similar to C or C++, in which you can develop a wide range of programs.
The most common use of Java at the moment is in creating applets for HotJava, an advanced
World Wide Web browser also written in Java. Applets are Java programs that are downloaded
and run as part of a Web page. Applets can create animations, games, interactive programs, and
other multimedia effects on Web pages.
Java’s strengths lie in its portability—both at the source and at the binary level, in its object-
oriented design—and in its simplicity. Each of these features help make applets possible, but
they also make Java an excellent language for writing more general-purpose programs that do
not require HotJava or other Java-capable browser to run. These general-purpose Java programs
are called applications. HotJava itself is a Java application.
To end this day, you experimented with an example applet and an example application, getting
a feel for the differences between the two and how to create, compile, and run Java programs—
or, in the case of applets, how to include them in Web pages. From here, you now have the
foundation to create more complex applications and applets.
Q&A
Q I’d like to use HotJava as my regular Web browser. You haven’t mentioned much
about HotJava today.
A The focus of this book is primarily on programming in Java and in the HotJava
classes, rather than on using HotJava itself. Documentation for using the HotJava
browser comes with the HotJava package.
Q I know a lot about HTML, but not much about computer programming. Can I
still write Java programs?
16
net
ing
r
Sams.
Learn
Cente
A If you have no programming experience whatsoever, you most likely will find pro-
gramming Java significantly more difficult. However, Java is an excellent language to
learn programming with, and if you patiently work through the examples and the 1
exercises in this book, you should be able to learn enough to get started with Java.
Q According to today’s lesson, Java applets are downloaded via HotJava and run on
the reader’s system. Isn’t that an enormous security hole? What stops someone
from writing an applet that compromises the security of my system—or worse,
that damages my system?
A Sun’s Java team has thought a great deal about the security of applets within Java-
capable browsers and has implemented several checks to make sure applets cannot do
nasty things:
■ Java applets cannot read or write to the disk on the local system.
■ Java applets cannot execute any programs on the local system.
■ Java applets cannot connect to any machines on the Web except for the server
from which they are originally downloaded.
In addition, the Java compiler and interpreter check both the Java source code and the
Java bytecodes to make sure that the Java programmer has not tried any sneaky tricks
(for example, overrunning buffers or stack frames).
These checks obviously cannot stop every potential security hole, but they can
significantly reduce the potential for hostile applets. You’ll learn more about security
issues later on in this book.
Q I followed all the directions you gave for creating a Java applet. I loaded it into
HotJava, but Hello World didn’t show up. What did I do wrong?
A I’ll bet you’re using the alpha version of HotJava to view the applet. Unfortunately,
between alpha and beta, significant changes were made as to how applets are written.
The result is that you can’t view beta applets (as this one was) in the alpha version of
HotJava, nor can you view alpha applets in browsers that expect beta applets. To view
the applet, either use a different browser, or use the appletviewer application that
comes with the JDK.
17
net
ing
r
Sams.
Learn
Cente
2 F
S
S WEEK
1
2
R
W
Object-Oriented
T
Programming
M and Java
by Laura Lemay
19
M
T
W
R
DAY
20
net
ing
r
Sams.
Learn
Cente
the interactions are between the components and can match the interactions, putting together
the overall system is easy.
What does this have to do with programming? Everything. Object-oriented programming
works in exactly this same way. Using object-oriented programming, your overall program is
made up of lots of different self-contained components (objects), each of which has a specific
role in the program and all of which can talk to each other in predefined ways.
2
Objects and Classes
Object-oriented programming is modeled on how, in the real world, objects are often made up
of many kinds of smaller objects. This capability of combining objects, however, is only one very
general aspect of object-oriented programming. Object-oriented programming provides several
other concepts and features to make creating and using objects easier and more flexible, and the
most important of these features is that of classes.
NEW☛ A class is a template for multiple objects with similar features. Classes embody all the
TERM features of a particular set of objects.
When you write a program in an object-oriented language, you don’t define actual objects. You
define classes of objects.
For example, you might have a Tree class that describes the features of all trees (has leaves and
roots, grows, creates chlorophyll). The Tree class serves as an abstract model for the concept of
a tree—to reach out and grab, or interact with, or cut down a tree you have to have a concrete
instance of that tree. Of course, once you have a tree class, you can create lots of different
instances of that tree, and each different tree instance can have different features (short, tall,
bushy, drops leaves in Autumn), while still behaving like and being immediately recognizable
as a tree (see Figure 2.1).
NEW☛ An instance of a class is another word for an actual object. If classes are an abstract
TERM representation of an object, an instance is its concrete representation.
So what, precisely, is the difference between an instance and an object? Nothing, really. Object
is the more general term, but both instances and objects are the concrete representation of a class.
In fact, the terms instance and object are often used interchangeably in OOP language. An
instance of a tree and a tree object are both the same thing.
In an example closer to the sort of things you might want to do in Java programming, you might
create a class for the user interface element called a button. The Button class defines the features
of a button (its label, its size, its appearance) and how it behaves (does it need a single click or
a double click to activate it, does it change color when it’s clicked, what does it do when it’s
activated?). Once you define the Button class, you can then easily create instances of that
button—that is, button objects—that all take on the basic features of the button as defined by
21
M
T
W
R
DAY
the class, but may have different appearances and behavior based on what you want that
particular button to do. By creating a Button class, you don’t have to keep rewriting the code
for each individual button you want to use in your program, and you can reuse the Button class
to create different kinds of buttons as you need them in this program and in other programs.
Figure 2.1.
The tree class and
tree instances.
Tree
Tree
Tree Class
(Abstract)
Tree
Tree
When you write a Java program, you design and construct a set of classes. Then, when your
program runs, instances of those classes are created and discarded as needed. Your task, as a Java
programmer, is to create the right set of classes to accomplish what your program needs to
accomplish.
22
net
ing
r
Sams.
Learn
Cente
Fortunately, you don’t have to start from the very beginning: the Java environment comes with
a library of classes that implement a lot of the basic behavior you need—not only for basic
programming tasks (classes to provide basic math functions, arrays, strings, and so on), but also
for graphics and networking behavior. In many cases, the Java class libraries may be enough so
that all you have to do in your Java program is create a single class that uses the standard class
libraries. For complicated Java programs, you may have to create a whole set of classes with
defined interactions between them.
NEW☛ A class library is a set of classes.
2
TERM
Attributes
Attributes are the individual things that differentiate one object from another and determine the
appearance, state, or other qualities of that object. Let’s create a theoretical class called
Motorcycle. The attributes of a motorcycle might include the following:
NEW☛ Instance variables define the attributes of an object. The class defines the kind of attribute,
TERM and each instance stores its own value for that attribute.
Each attribute, as the term is used here, has a single corresponding instance variable; changing
the value of a variable changes the attribute of that object. Instance variables may be set when
an object is created and stay constant throughout the life of the object, or they may be able to
change at will as the program runs.
23
M
T
W
R
DAY
In addition to instance variables, there are also class variables, which apply to the class itself and
to all its instances. Unlike instance variables, whose values are stored in the instance, class
variables’ values are stored in the class itself. You’ll learn about class variables later on this week;
you’ll learn more specifics about instance variables tomorrow.
Behavior
A class’s behavior determines what instances of that class do when their internal state changes
or when that instance is asked to do something by another class or object. Behavior is the way
objects can do anything to themselves or have anything done to them. For example, to go back
to the theoretical Motorcycle class, here are some behaviors that the Motorcycle class might have:
■ Start the engine
■ Stop the engine
■ Speed up
■ Change gear
■ Stall
To define an object’s behavior, you create methods, which look and behave just like functions
in other languages, but are defined inside a class. Java does not have functions defined outside
classes (as C++ does).
NEW☛ Methods are functions defined inside classes that operate on instances of those classes.
TERM
Methods don’t always affect only a single object; objects communicate with each other using
methods as well. A class or object can call methods in another class or object to communicate
changes in the environment or to ask that object to change its state.
Just as there are instance and class variables, there are also instance and class methods. Instance
methods (which are so common they’re usually just called methods) apply and operate on an
instance; class methods apply and operate on a class (or on other objects). You’ll learn more about
class methods later on this week.
Creating a Class
Up to this point, today’s lesson has been pretty theoretical. In this section, you’ll create a working
example of the Motorcycle class so that you can see how instance variables and methods are
defined in a class. You’ll also create a Java application that creates a new instance of the
Motorcycle class and shows its instance variables.
24
net
ing
r
Sams.
Learn
Cente
Note: I’m not going to go into a lot of detail about the actual syntax of this
example here. Don’t worry too much about it if you’re not really sure what’s going
on; it will become clear to you later on this week. All you really need to worry
about in this example is understanding the basic parts of this class definition.
Ready? Let’s start with a basic class definition. Open up that editor and enter the following: 2
class Motorcycle {
Congratulations! You’ve now created a class. Of course, it doesn’t do very much at the moment,
but that’s a Java class at its very simplest.
First, let’s create some instance variables for this class—three of them, to be specific. Just below
the first line, add the following three lines:
String make;
String color;
boolean engineState;
Here, you’ve created three instance variables: two, make and color, can contain String objects
(String is part of that standard class library mentioned earlier). The third, engineState, is a
boolean that refers to whether the engine is off or on.
Technical Note: boolean in Java is a real data type that can have the value true or
false. Unlike C, booleans are not numbers. You’ll hear about this again tomorrow
so you won’t forget.
Now let’s add some behavior (methods) to the class. There are all kinds of things a motorcycle
can do, but to keep things short, let’s add just one method—a method that starts the engine.
Add the following lines below the instance variables in your class definition:
void startEngine() {
if (engineState == true)
[Link](“The engine is already on.”);
else {
engineState = true;
[Link](“The engine is now on.”);
}
}
25
M
T
W
R
DAY
The startEngine method tests to see whether the engine is already running (in the line
engineState == true) and, if it is, merely prints a message to that effect. If the engine isn’t already
running, it changes the state of the engine to true and then prints a message.
With your methods and variables in place, save the program to a file called [Link]
(remember, you should always name your Java files the same names as the class they define).
Here’s what your program should look like so far:
class Motorcycle {
String make;
String color;
boolean engineState;
void startEngine() {
if (engineState == true)
[Link](“The engine is already on.”);
else {
engineState = true;
[Link](“The engine is now on.”);
}
}
}
Tip: The indentation of each part of the class isn’t important to the Java compiler.
Using some form of indentation, however, makes your class definition easier for
you and for other people to read. The indentation used here, with instance vari-
ables and methods indented from the class definition, is the style used throughout
this book. The Java class libraries use a similar indentation. You can choose any
indentation style that you like.
Before you compile this class, let’s add one more method. The showAtts method prints the
current values of the instance variables in an instance of your Motorcycle class. Here’s what it
looks like:
void showAtts() {
[Link](“This motorcycle is a “
+ color + “ “ + make);
if (engineState == true)
[Link](“The engine is on.”);
else [Link](“The engine is off.”);
}
The showAtts method prints two lines to the screen: the make and color of the motorcycle object,
and whether or not the engine is on or off.
26
net
ing
r
Sams.
Learn
Cente
Save that file again and compile it using javac:
javac [Link]
Note: After this point, I’m going to assume you know how to compile and run Java
programs. I won’t repeat this information after this.
2
What happens if you now use the Java interpreter to run this compiled class? Try it. Java assumes
that this class is an application and looks for a main method. This is just a class, however, so it
doesn’t have a main method. The Java interpreter (java) gives you an error like this one:
In class Motorcycle: void main(String argv[]) is not defined
To do something with the Motorcycle class—for example, to create instances of that class and
play with them—you’re going to need to create a Java application that uses this class or add a
main method to this one. For simplicity’s sake, let’s do the latter. Listing 2.1 shows the main()
method you’ll add to the Motorcycle class (you’ll go over what this does in a bit).
With the main() method, the Motorcycle class is now an application, and you can compile it
again and this time it’ll run. Here’s how the output should look:
Calling showAtts...
Output This motorcycle is a yellow Yamaha RZ350
The engine is off.
--------
27
M
T
W
R
DAY
Starting engine...
The engine is now on.
--------
Calling showAtts...
This motorcycle is a yellow Yamaha RZ350
The engine is on.
--------
Starting engine...
The engine is already on.
The contents of the main() method are all going to look very new to you, so let’s go through
Analysis it line by line so that you at least have a basic idea of what it does (you’ll get details about
the specifics of all of this tomorrow and the day after).
The first line declares the main() method. The main() method always looks like this; you’ll learn
the specifics of each part later this week.
Line 2, Motorcycle m = new Motorcycle(), creates a new instance of the Motorcycle class and
stores a reference to it in the variable m. Remember, you don’t usually operate directly on classes
in your Java programs; instead, you create objects from those classes and then modify and call
methods in those objects.
Lines 3 and 4 set the instance variables for this motorcycle object: the make is now a Yamaha RZ350
(a very pretty motorcycle from the mid-1980s), and the color is yellow.
Lines 5 and 6 call the showAtts() method, defined in your motorcycle object. (Actually, only
6 does; 5 just prints a message that you’re about to call this method.) The new motorcycle object
then prints out the values of its instance variables—the make and color as you set in the previous
lines—and shows that the engine is off.
Line 7 prints a divider line to the screen; this is just for prettier output.
Line 9 calls the startEngine() method in the motorcycle object to start the engine. The engine
should now be on.
Line 12 prints the values of the instance variables again. This time, the report should say the
engine is now on.
Line 15 tries to start the engine again, just for fun. Because the engine is already on, this should
print the error message.
28
net
ing
r
Sams.
Learn
Cente
Inheritance
Inheritance is one of the most crucial concepts in object-oriented programming, and it has a very
direct effect on how you design and write your Java classes. Inheritance is a powerful mechanism
that means when you write a class you only have to specify how that class is different from some
other class, while also giving you dynamic access to the information contained in those other
classes.
NEW☛ With inheritance, all classes—those you write, those from other class libraries that you use, 2
TERM and those from the standard utility classes as well—are arranged in a strict hierarchy (see
Figure 2.2).
Each class has a superclass (the class above it in the hierarchy), and each class can have one or
more subclasses (classes below that class in the hierarchy). Classes further down in the hierarchy
are said to inherit from classes further up in the hierarchy.
Figure 2.2.
A class hierarchy. Class A • Class A is the superclass of B
• Class B is a subclass of A
• Class B is the superclass
of C, D, and E
• Classes C, D, and E
are subclasses of B
Class B
Subclasses inherit all the methods and variables from their superclasses—that is, in any particular
class, if the superclass defines behavior that your class needs, you don’t have to redefine it or copy
that code from some other class. Your class automatically gets that behavior from its superclass,
that superclass gets behavior from its superclass, and so on all the way up the hierarchy. Your
class becomes a combination of all the features of the classes above it in the hierarchy.
At the top of the Java class hierarchy is the class Object; all classes inherit from this one superclass.
Object is the most general class in the hierarchy; it defines behavior specific to all objects in the
Java class hierarchy. Each class farther down in the hierarchy adds more information and
becomes more tailored to a specific purpose. In this way, you can think of a class hierarchy as
29
M
T
W
R
DAY
defining very abstract concepts at the top of the hierarchy and those ideas becoming more
concrete the farther down the chain of superclasses you go.
Most of the time when you write new Java classes, you’ll want to create a class that has all the
information some other class has, plus some extra information. For example, you may want a
version of a Button with its own built-in label. To get all the Button information, all you have
to do is define your class to inherit from Button. Your class will automatically get all the behavior
defined in Button (and in Button’s superclasses), so all you have to worry about are the things
that make your class different from Button itself. This mechanism for defining new classes as the
differences between them and their superclasses is called subclassing.
NEW☛ Subclassing involves creating a new class that inherits from some other class in the class
TERM hierarchy. Using subclassing, you only need to define the differences between your class
and its parent; the additional behavior is all available to your class through inheritance.
What if your class defines entirely new behavior, and isn’t really a subclass of another class? Your
class can also inherit directly from Object, which still allows it to fit neatly into the Java class
hierarchy. In fact, if you create a class definition that doesn’t indicate its superclass in the first
line, Java automatically assumes you’re inheriting from Object. The Motorcycle class you created
in the previous section inherited from Object.
net
ing
r
Sams.
Learn
Cente
A far better plan is to factor out the common information for Car and Motorcycle into a more
general class hierarchy. This may be a lot of work just for the classes Motorcycle and Car, but once
you add Bicycle, Scooter, Truck, and so on, having common behavior in a reuseable superclass
significantly reduces the amount of work you have to do overall.
Let’s design a class hierarchy that might serve this purpose. Starting at the top is the class Object,
which is the root of all Java classes. The most general class to which motorcycle and car both
belong might be called Vehicle. A vehicle, generally, is defined as a thing that propels someone
from one place to another. In the Vehicle class, you define only the behavior that enables
2
someone to be propelled from point a to point b, and nothing more.
Below Vehicle? How about two classes: PersonPoweredVehicle and EnginePoweredVehicle?
EnginePoweredVehicle is different from Vehicle because is has an engine, and the behaviors
might include stopping and starting the engine, having certain amounts of gasoline and oil, and
perhaps the speed or gear in which the engine is running. Person-powered vehicles have some
kind of mechanism for translating people motion into vehicle motion—pedals, for example.
Figure 2.3 shows what you have so far.
Figure 2.3.
The basic vehicle hierarchy. Object
Vehicle
PersonPoweredVehicle EnginePoweredVehicle
Now, let’s become even more specific. With EnginePoweredVehicle, you might have several
classes: Motorcycle, Car, Truck, and so on. Or you can factor out still more behavior and have
intermediate classes for TwoWheeled and FourWheeled vehicles, with different behaviors for each
(see Figure 2.4).
Finally, with a subclass for the two-wheeled engine-powered vehicles you can finally have a class
for motorcycles. Alternatively, you could additionally define scooters and mopeds, both of
which are two-wheeled engine-powered vehicles but have different qualities from motorcycles.
Where do qualities such as make or color come in? Wherever you want them to go—or, more
usually, where they fit most naturally in the class hierarchy. You can define the make and color
31
M
T
W
R
DAY
on Vehicle, and all the subclasses will have those variables as well. The point to remember is that
you have to define a feature or a behavior only once in the hierarchy; it’s automatically reused
by each subclass.
Figure 2.4.
EnginePoweredVehicle
Two-wheeled and four-
wheeled vehicles.
TwoWheeled FourWheeled
EnginePoweredVehicle EnginePoweredVehicle
32
net
ing
r
Sams.
Learn
Cente
Figure 2.5. Method
definition
How methods are located.
Class
Class Class 2
Object Object
NEW☛ Overriding a method is creating a method in a subclass that has the same signature (name,
TERM number and type of arguments) as a method in a superclass. That new method then hides
the superclass’s method (see Figure 2.6).
Figure 2.6.
Class
Overriding methods.
Method is overridden
by this definition
Initial method
definition Class
Object Object
33
M
T
W
R
DAY
34
net
ing
r
Sams.
Learn
Cente
You’ll learn all about packages, including how to create and use them, in Week 3. For now, there
are only a few things you need to know:
■ The class libraries in the Java Developer’s Kit are contained in a package called java.
The classes in the java package are guaranteed to be available in any Java implementa-
tion, and are the only classes guaranteed to be available across different implementa-
tions. The java package itself contains other packages for classes that define the
language itself, the input and output classes, some basic networking, and the window
toolkit functions. Classes in other packages (for example, classes in the sun or netscape 2
packages) may be available only in specific implementations.
■ By default, your Java classes have access to only the classes in [Link] (the base
language package inside the java package). To use classes from any other package, you
have to either refer to them explicitly by package name or import them in your source
file.
■ To refer to a class within a package, list all the packages that class is contained in and
the class name, all separated by periods (.). For example, take the Color class, which is
contained in the awt package (awt stands for Abstract Windowing Toolkit). The awt
package, in turn, is inside the java package. To refer to the Color class in your pro-
gram, you use the notation [Link].
Creating a Subclass
To finish up today, let’s create a class that is a subclass of another class and override some
methods. You’ll also get a basic feel for how packages work in this example.
Probably the most typical instance of creating a subclass, at least when you first start
programming in Java, is in creating an applet. All applets are subclasses of the class Applet (which
is part of the [Link] package). By creating a subclass of Applet, you automatically get all
the behavior from the window toolkit and the layout classes that enables your applet to be drawn
in the right place on the page and to interact with system operations, such as keypresses and
mouse clicks.
In this example, you’ll create an applet similar to the Hello World applet from yesterday, but
one that draws the Hello string in a larger font and a different color. To start this example, let’s
first construct the class definition itself. Remember the HTML and classes directories you
created yesterday? Let’s go back to those, go back to your text editor, and enter the following class
definition:
public class HelloAgainApplet extends [Link] {
}
Here, you’re creating a class called HelloAgainApplet. Note the part that says extends
[Link]—that’s the part that says your applet class is a subclass of the Applet class.
35
M
T
W
R
DAY
Note that because the Applet class is contained in the [Link] package, you don’t have
automatic access to that class, and you have to refer to it explicitly by package and class name.
The other part of this class definition is the public keyword. Public means that your class is
available to the Java system at large once it is loaded. Most of the time you need to make a class
public only if you want it to be visible to all the other classes in your Java program; but applets,
in particular, must be declared to be public. (You’ll learn more about public classes in Week 3.)
A class definition with nothing in it doesn’t really have much of a point; without adding or
overriding any of its superclasses’ variables or methods, there’s no point to creating a subclass
at all. Let’s add some information to this class to make it different from its superclass.
First, add an instance variable to contain a Font object:
Font f = new Font(“TimesRoman”,[Link],36);
The f instance variable now contains a new instance of the class Font, part of the [Link]
package. This particular font object is a Times Roman font, boldface, 36 points high. In the
previous Hello World applet, the font used for the text was the default font: 12 point Times
Roman. Using a font object, you can change the font of the text you draw in your applet.
By creating an instance variable to hold this font object, you make it available to all the methods
in your class. Now let’s create a method that uses it.
When you write applets, there are several “standard” methods defined in the applet superclasses
that you will commonly override in your applet class. These include methods to initialize the
applet, to start it running, to handle operations such as mouse movements or mouse clicks, or
to clean up when the applet stops running. One of those standard methods is the paint()
method, which actually displays your applet on screen. The default definition of paint() doesn’t
do anything—it’s an empty method. By overriding paint(), you tell the applet just what to draw
on the screen. Here’s a definition of paint():
public void paint(Graphics g) {
[Link](f);
[Link]([Link]);
[Link](“Hello again!”, 5, 25);
}
There are two things to know about the paint() method. First, note that this method is declared
public, just as the applet itself was. The paint() method is actually public for a different
reason—because the method it’s overriding is also public. If you try to override a method in your
own class that’s public in a superclass, you get a compiler error, so the public is required.
Secondly, note that the paint() method takes a single argument: an instance of the Graphics
class. The Graphics class provides platform-independent behavior for rendering fonts, colors,
and basic drawing operations. You’ll learn a lot more about the Graphics class in Week 2, when
you create more extensive applets.
36
net
ing
r
Sams.
Learn
Cente
Inside your paint() method, you’ve done three things:
■ You’ve told the graphics object that the default drawing font will be the one contained
in the instance variable f.
■ You’ve told the graphics object that the default color is an instance of the Color class
for the color red.
■ Finally, you’ve drawn your “Hello Again!” string onto the screen itself, at the x and y
positions of 5 and 25. The string will be rendered in the default font and color. 2
For an applet this simple, this is all you need to do. Here’s what the applet looks like so far:
public class HelloAgainApplet extends [Link] {
If you’ve been paying attention, you’ll notice something is wrong with this example up to this
point. If you don’t know what it is, try saving this file (remember, save it to the same name as
the class: [Link]) and compiling it using the Java compiler. You should get a
bunch of errors similar to this one:
[Link][Link] Class Graphics not found in type declaration.
Why are you getting these errors? Because the classes you’re referring to are part of a package.
Remember that the only package you have access to automatically is [Link]. You referred to
the Applet class in the first line of the class definition by referring to its full package name
([Link]). Further on in the program, however, you referred to all kinds of other
classes as if they were already available.
There are two ways to solve this problem: refer to all external classes by full package name or
import the appropriate class or package at the beginning of your class file. Which one you choose
to do is mostly a matter of choice, although if you find yourself referring to a class in another
package lots of times, you may want to import it to cut down on the amount of typing.
In this example, you’ll import the classes you need. There are three of them: Graphics, Font, and
Color. All three are part of the [Link] package. Here are the lines to import these classes. These
lines go at the top of your program, before the actual class definition:
import [Link];
import [Link];
import [Link];
37
M
T
W
R
DAY
Tip: You also can import an entire package of (public) classes by using an asterisk
(*) in place of a specific class name. For example, to import all the classes in the awt
package, you can use this line:
import [Link].*;
Now, with the proper classes imported into your program, HelloAgainApplet should compile
cleanly to a class file. To test it, create an HTML file with the <APPLET> tag as you did yesterday.
Here’s an HTML file to use:
<HTML>
<HEAD>
<TITLE>Another Applet</TITLE>
</HEAD>
<BODY>
<P>My second Java applet says:
<APPLET CODE=”[Link]” WIDTH=200 HEIGHT=50>
</APPLET>
</BODY>
</HTML>
For this HTML example, your Java class file is in the same directory as this HTML file. Save
the file to [Link] and fire up your Java-aware browser or the Java applet viewer.
Figure 2.7 shows the result you should be getting (the Hello Again string is red).
Figure 2.7.
The Hello Again applet.
Summary
If this is your first encounter with object-oriented programming, a lot of the information in this
chapter is going to seem really theoretical and overwhelming. Fear not—the further along in this
book you get, and the more Java applications you create, the easier it is to understand.
One of the biggest hurdles of object-oriented programming is not necessarily the concepts, it’s
their names. OOP has lots of jargon surrounding it. To summarize today’s material, here’s a
glossary of terms and concepts you learned today:
38
net
ing
r
Sams.
Learn
Cente
Class: A template for an object, which contains variables and methods representing
behavior and attributes. Classes can inherit variables and methods from other classes.
Object: A concrete instance of some class. Multiple objects that are instances of the
same class have access to the same methods, but often have different values for their
instance variables.
Instance: The same thing as an object; each object is an instance of some class.
Superclass: A class further up in the inheritance hierarchy than its child, the subclass. 2
Subclass: A class lower in the inheritance hierarchy than its parent, the superclass.
When you create a new class, that’s often called subclassing.
Instance method: A method defined in a class, which operates on an instance of that
class. Instance methods are usually called just methods.
Class method: A method defined in a class, which can operate on the class itself or on
any object.
Instance variable: A variable that is owned by an individual instance and whose value is
stored in the instance.
Class variable: A variable that is owned by the class and all its instances as a whole, and
is stored in the class.
Interface: A collection of abstract behavior specifications that individual classes can
then implement.
Package: A collection of classes and interfaces. Classes from packages other than
[Link] must be explicitly imported or referred to by full package name.
Q&A
Q Methods are effectively functions that are defined inside classes. If they look like
functions and act like functions, why aren’t they called functions?
A Some object-oriented programming languages do call them functions (C++ calls them
member functions). Other object-oriented languages differentiate between functions
inside and outside a body of a class or object, where having separate terms is impor-
tant to understanding how each works. Because the difference is relevant in other
languages, and because the term method is now in such common use in object-
oriented technology, Java uses the word as well.
Q I understand instance variables and methods, but not class variables and
methods.
A Most everything you do in a Java program will be with objects. Some behaviors and
attributes, however, make more sense if they are stored in the class itself rather than in
the object. For example, to create a new instance of a class, you need a method that is
39
M
T
W
R
DAY
defined for the class itself, not for an object. (Otherwise, how can you create an
instance of class? You need an object to call the new method in, but you don’t have an
object yet.) Class variables, on the other hand, are often used when you have an
attribute whose value you want to share with the instances of a class.
Most of the time, you’ll use instance variables and methods. You’ll learn more about
class variables and methods later on this week.
40
net
ing
r
Sams.
Learn
Cente
3 F
S
S WEEK
1
3
R
JavaWBasics
T
M by Laura Lemay
41
M
T
W
R
DAY
3 Java Basics
On Days 1 and 2, you learned about Java programming in very broad terms—what a Java
program and an executable look like, and how to create simple classes. For the remainder of this
week, you’re going to get down to details and deal with the specifics of what the Java language
looks like.
Today, you won’t define any classes or objects or worry about how any of them communicate
inside a Java program. Rather, you’ll draw closer and examine simple Java statements—the basic
things you can do in Java within a method definition such as main().
Today you’ll learn about the following:
■ Java statements and expressions
■ Variables and data types
■ Comments
■ Literals
■ Arithmetic
■ Comparisons
■ Logical operators
Technical Note: Java looks a lot like C++, and—by extension—like C. Much of
the syntax will be very familiar to you if you are used to working in these languages.
If you are an experienced C or C++ programmer, you may want to pay special
attention to the Technical Notes (such as this one), because they will provide
information about the specific differences between these and other traditional
languages and Java.
Statements sometimes return values—for example, when you add two numbers together or test
to see whether one value is equal to another. These kind of statements are called expressions.
We’ll discuss these later on today.
42
net
ing
r
Sams.
Learn
Cente
The most important thing to remember about Java statements is that each one ends with a
semicolon. Forget the semicolon and your Java program won’t compile.
Java also has compound statements, or blocks, which can be placed wherever a single statement
can. Block statements are surrounded by braces ({}). You’ll learn more about blocks in Chapter
5, “Arrays, Conditionals, and Loops.”
Note: Unlike other languages, Java does not have global variables—that is, vari-
ables that are global to all parts of a program. Instance and class variables can be
used to communicate global information between and among objects. Remember,
Java is an object-oriented language, so you should think in terms of objects and
how they interact, rather than in terms of programs.
Declaring Variables
To use any variable in a Java program, you must first declare it. Variable declarations consist of
a type and a variable name:
43
M
T
W
R
DAY
3 Java Basics
int myAge;
String myName;
boolean isTired;
Variable definitions can go anywhere in a method definition (that is, anywhere a regular Java
statement can go), although they are most commonly declared at the beginning of the definition
before they are used:
public static void main (String args÷]) {
int count;
String title;
boolean isAsleep;
...
}
You can string together variable names with the same type:
int x, y, z;
String firstName, LastName;
You can also give each variable an initial value when you declare it:
int myAge, mySize, numShoes = 28;
String myName = “Laura”;
boolean isTired = true;
int a = 4, b = 5, c = 6;
If there are multiple variables on the same line with only one initializer (as in the first of the
previous examples), the initial value applies to only the last variable in a declaration. You can also
group individual variables and initializers on the same line using commas, as with the last
example, above.
Local variables must be given values before they can be used (your Java program will not compile
if you try to use an unassigned local variable). For this reason, it’s a good idea always to give local
variables initial values. Instance and class variable definitions do not have this restriction (their
initial value depends on the type of the variable: null for instances of classes, 0 for numeric
variables, ‘\0’ for characters, and false for booleans).
44
net
ing
r
Sams.
Learn
Cente
use accented characters and other glyphs as legal characters in variable names, as long as they have
a Unicode character number above 00C0.
Finally, note that the Java language is case-sensitive, which means that uppercase letters are
different from lowercase letters. This means that the variable X is different from the variable x,
and a rose is not a Rose is not a ROSE. Keep this in mind as you write your own Java programs 3
and as you read Java code other people have written.
By convention, Java variables have meaningful names, often made up of several words
combined. The first word is lowercase, but all following words have an initial uppercase letter:
Button theButton;
long reallyBigNumber;
boolean currentWeatherStateOfPlanetXShortVersion;
Variable Types
In addition to the variable name, each variable declaration must have a type, which defines what
values that variable can hold. The variable type can be one of three things:
■ One of the eight basic primitive data types
■ The name of a class
■ An array
You’ll learn about how to declare and use array variables in Chapter 5.
The eight primitive data types handle common types for integers, floating-point numbers,
characters, and boolean values (true or false). They’re called primitive because they’re built into
the system and are not actual objects, which makes them more efficient to use. Note that these
data types are machine-independent, which means that you can rely on their sizes and
characteristics to be consistent across your Java programs.
There are four Java integer types, each with different ranges of values (as listed in Table 3.1). All
are signed, which means they can hold either positive or negative numbers. Which type you
choose for your variables depends on the range of values you expect that variable to hold; if a
value becomes too big for the variable type, it is truncated.
45
M
T
W
R
DAY
3 Java Basics
Floating-point numbers are used for numbers with a decimal part. Java floating-point numbers
are compliant with IEEE 754 (an international standard for defining floating-point numbers
and arithmetic). There are two floating-point types: float (32 bits, single-precision) and double
(64 bits, double-precision).
The char type is used for individual characters. Because Java uses the Unicode character set, the
char type has 16 bits of precision, unsigned.
Finally, the boolean type can have one of two values, true or false. Note that unlike in other
C-like languages, boolean is not a number, nor can it be treated as one. All tests of boolean
variables should test for true or false.
In addition to the eight basic data types, variables in Java can also be declared to hold an instance
of a particular class:
String LastName;
Font basicFont;
OvalShape myOval;
Each of these variables can then hold only instances of the given class. As you create new classes,
you can declare variables to hold instances of those classes (and their subclasses) as well.
Technical Note: Java does not have a typedef statement (as in C and C++). To
declare new types in Java, you declare a new class; then variables can be declared to
be of that class’s type.
46
net
ing
r
Sams.
Learn
Cente
Comments
Java has three kinds of comments. /* and */ surround multiline comments, as in C or C++. All
text between the two delimiters is ignored:
/* I don’t know how I wrote this next part; I was working
really late one night and it just sort of appeared. I
suspect the code elves did it for me. It might be wise
not to try and change it.
*/
Comments cannot be nested; that is, you cannot have a comment inside a comment.
Double-slashes (//) can be used for a single line of comment. All the text up to the end of the
line is ignored:
int vices = 7; // are there really only 7 vices? 3
The final type of comment begins with /** and ends with */. These are special comments that
are used for the javadoc system. Javadoc is used to generate API documentation from the code.
You won’t learn about javadoc in this book; you can find out more information from the
documentation that came with Sun’s Java Developer’s Kit or from Sun’s Java home page (http:/
/[Link]).
Literals
Literals are used to indicate simple values in your Java programs.
NEW☛ Literal is a programming language term, which essentially means that what you type is
TERM what you get. For example, if you type 4 in a Java program, you automatically get an integer
with the value 4. If you type ‘a’, you get a character with the value a.
Literals may seem intuitive most of the time, but there are some special cases of literals in Java
for different kinds of numbers, characters, strings, and boolean values.
Number Literals
There are several integer literals. 4, for example, is a decimal integer literal of type int (although
you can assign it to a variable of type byte or short because it’s small enough to fit into those
types). A decimal integer literal larger than an int is automatically of type long. You also can force
a smaller number to a long by appending an L or l to that number (for example, 4L is a long
integer of value 4). Negative integers are preceded by a minus sign—for example, -45.
Integers can also be expressed as octal or hexadecimal: a leading 0 indicates that a number is
octal—for example, 0777 or 0004. A leading 0x (or 0X) means that it is in hex (0xFF, 0XAF45).
47
M
T
W
R
DAY
3 Java Basics
Hexadecimal numbers can contain regular digits (0–9) or upper- or lowercase hex digits (a–f or
A–F).
Floating-point literals usually have two parts: the integer part and the decimal part—for
example, 5.677777. Floating-point literals result in a floating-point number of type double,
regardless of the precision of that number. You can force the number to the type float by
appending the letter f (or F) to that number—for example, 2.56F.
You can use exponents in floating-point literals using the letter e or E followed by the exponent
(which can be a negative number): 10e45 or .36E-2.
Boolean Literals
Boolean literals consist of the keywords true and false. These keywords can be used anywhere
you need a test or as the only possible values for boolean variables.
Character Literals
Character literals are expressed by a single character surrounded by single quotes: ’a’, ’#’, ’3’,
and so on. Characters are stored as 16-bit Unicode characters. Table 3.2 lists the special codes
that can represent nonprintable characters, as well as characters from the Unicode character set.
The letter d in the octal, hex, and Unicode escapes represents a number or a hexadecimal digit
(a–f or A–F).
48
net
ing
r
Sams.
Learn
Cente
Technical Note: C and C++ programmers should note that Java does not include
character codes for \a (bell) or \v (vertical tab).
String Literals
A combination of characters is a string. Strings in Java are instances of the class String. Strings
are not simple arrays of characters as they are in C or C++, although they do have many array-
like characteristics (for example, you can test their length and add and delete individual
characters as if they were arrays). Because string objects are real objects in Java, they have
methods that enable you to combine, test, and modify strings very easily.
String literals consist of a series of characters inside double quotes:
3
“Hi, I’m a string literal.”
“” //an empty string
Strings can contain character constants such as newline, tab, and Unicode characters:
“A string with a \t tab in it”
“Nested strings are \”strings inside of\” other strings”
“This string brought to you by Java\u2122”
In the last example, the Unicode code sequence for \u2122 produces a trademark symbol (™).
Note: Just because you can represent a character using a Unicode escape does not
mean your computer can display that character—the computer or operating system
you are running may not support Unicode, or the font you’re using may not have a
glyph (picture) for that character. All that Unicode escapes in Java provide is a way
to encode special characters for systems that support Unicode.
When you use a string literal in your Java program, Java automatically creates an instance of the
class String for you with the value you give it. Strings are unusual in this respect; the other literals
do not behave in this way (none of the primitive base types are actual objects), and usually
creating a new object involves explicitly creating a new instance of a class. You’ll learn more about
strings, the String class, and the things you can do with strings later today and tomorrow.
49
M
T
W
R
DAY
3 Java Basics
Arithmetic
Java has five operators for basic arithmetic (see Table 3.3).
– Subtraction 5 – 7
* Multiplication 5 * 5
÷ Division 14 ÷ 7
% Modulus 20 % 7
Each operator takes two operands, one on either side of the operator. The subtraction operator
(–) can also be used to negate a single operand.
Integer division results in an integer. Because integers don’t have decimal fractions, any
remainder is ignored. The expression 31 ÷ 9, for example, results in 3 (9 goes into 31 only 3
times).
Modulus (%) gives the remainder once the operands have been evenly divided. For example, 31
% 9 results in 4 because 9 goes into 31 three times, with 4 left over.
Note that, for integers, the result type of most operations is an int or a long, regardless of the
original type of the operands. Large results are of type long; all others are int. Arithmetic wherein
one operand is an integer and another is a floating point results in a floating-point result. (If
you’re interested in the details of how Java promotes and converts numeric types from one type
50
net
ing
r
Sams.
Learn
Cente
to another, you may want to check out the Java Language Specification; that’s more detail than
I want to cover here.)
Listing 3.1 is an example of simple arithmetic.
x is 6, y is 4
Output x
x
+ y = 10
- y = 2
x / y = 1
x % y = 2
a is 12.5, b is 7
a / b = 1.78571
In this simple Java application (note the main() method), you initially define four variables
Analysis in lines 3 through 6: x and y, which are integers (type int), and a and b, which are floating-
point numbers (type float). Keep in mind that the default type for floating-point literals
(such as 12.5) is double, so to make sure these are numbers of type float, you have to use an f
after each one (lines 5 and 6).
The remainder of the program merely does some math with integers and floating point numbers
and prints out the results.
There is one other thing to mention about this program: the method [Link]().
You’ve seen this method on previous days, but you haven’t really learned exactly what it does.
The [Link]() method merely prints a message to the standard output of your
system—to the screen, to a special window, or maybe just to a special log file, depending on your
system and the development environment you’re running (Sun’s JDK prints it to the screen).
The [Link]() method takes a single argument—a string—but you can use + to
concatenate values into a string, as you’ll learn later today.
51
M
T
W
R
DAY
3 Java Basics
net
ing
r
Sams.
Learn
Cente
Take, for example, the following two expressions:
y = x++;
y = ++x;
These two expressions give very different results because of the difference between prefix and
postfix. When you use postfix operators (x++ or x––), y gets the value of x before before x is
incremented; using prefix, the value of x is assigned to y after the increment has occurred. Listing
3.2 is a Java example of how all this works.
M
T
W
R
DAY
3 Java Basics
In the first part of this example, you increment x alone using both prefix and postfix
Analysis increment operators. In each, x is incremented by 1 each time. In this simple form, using
either prefix or postfix works the same way.
In the second part of this example, you use the expression y = x++, in which the postfix
increment operator is used. In this result, the value of x is incremented after that value is assigned
to y. Hence the result: y is assigned the original value of x (0), and then x is incremented by 1.
In the third part, you use the prefix expression y = ++x. Here, the reverse occurs: x is incremented
before its value is assigned to y. Because x is 1 from the previous step, its value is incremented
(to 2), and then that value is assigned to y. Both x and y end up being 2.
Technical Note: Technically, this description is not entirely correct. In reality, Java
always completely evaluates all expressions on the right of an expression before
assigning that value to a variable, so the concept of “assigning x to y before x is
incremented” isn’t precisely right. Instead, Java takes the value of x and “remem-
bers” it, evaluates (increments) x, and then assigns the original value of x to y.
Although in most simple cases this distinction may not be important, for more
complex expressions with side effects it may change the behavior of the expression
overall. See the Language Specification for many more details about the details of
expression evaluation in Java.
Comparisons
Java has several expressions for testing equality and magnitude. All of these expressions return
a boolean value (that is, true or false). Table 3.5 shows the comparison operators:
!= Not equal x != 3
54
net
ing
r
Sams.
Learn
Cente
Logical Operators
Expressions that result in boolean values (for example, the comparison operators) can be
combined by using logical operators that represent the logical combinations AND, OR, XOR, and
logical NOT.
For AND combinations, use either the & or &&. The expression will be true only if both operands
tests are also true; if either expression is false, the entire expression is false. The difference between
the two operators is in expression evaluation. Using &, both sides of the expression are evaluated
regardless of the outcome. Using &&, if the left side of the expression is false, the entire expression
returns false, and the right side of the expression is never evaluated.
For OR expressions, use either | or ||. OR expressions result in true if either or both of the operands
is also true; if both operands are false, the expression is false. As with & and &&, the single |
evaluates both sides of the expression regardless of the outcome; with ||, if the left expression 3
is true, the expression returns true and the right side is never evaluated.
In addition, there is the XOR operator ^, which returns true only if its operands are different (one
true and one false, or vice versa) and false otherwise (even if both are true).
In general, only the && and || are commonly used as actual logical combinations. &, |, and ^ are
more commonly used for bitwise logical operations.
For NOT, use the ! operator with a single expression argument. The value of the NOT expression
is the negation of the expression; if x is true, !x is false.
Bitwise Operators
Finally, here’s a short summary of the bitwise operators in Java. These are all inherited from C
and C++ and are used to perform operations on individual bits in integers. This book does not
go into bitwise operations; it’s an advanced topic covered better in books on C or C++. Table
3.6 summarizes the bitwise operators.
M
T
W
R
DAY
3 Java Basics
x|=y OR assignment (x + x | y)
Operator Precedence
Operator precedence determines the order in which expressions are evaluated. This, in some
cases, can determine the overall value of the expression. For example, take the following
expression:
y = 6 + 4 / 2
Depending on whether the 6 + 4 expression or the 4 ÷ 2 expression is evaluated first, the value
of y can end up being 5 or 8. Operator precedence determines the order in which expressions
are evaluated, so you can predict the outcome of an expression. In general, increment and
decrement are evaluated before arithmetic, arithmetic expressions are evaluated before compari-
sons, and comparisons are evaluated before logical expressions. Assignment expressions are
evaluated last.
Table 3.8 shows the specific precedence of the various operators in Java. Operators further up
in the table are evaluated first; operators on the same line have the same precedence and are
evaluated left to right based on how they appear in the expression itself. For example, give that
same expression y = 6 + 4 ÷ 2, you now know, according to this table, that division is evaluated
before addition, so the value of y will be 8.
net
ing
r
Sams.
Learn
Cente
Operator Notes
new (type)expression The new operator is used for creating new instances of classes; ()
in this case is for casting a value to another type (you’ll learn
about both of these tomorrow)
* ÷ % Multiplication, division, modulus
+ – Addition, subtraction
<< >> >>> Bitwise left and right shift
< > ≤ ≥ Relational comparison tests
== != Equality
& AND
^ XOR 3
| OR
You can always change the order in which expressions are evaluated by using parentheses around
the expressions you want to evaluate first. You can nest parentheses to make sure expressions
evaluate in the order you want them to (the innermost parenthetical expression is evaluated
first). The following expression results in a value of 5, because the 6 + 4 expression is evaluated
first, and then the result of that expression (10) is divided by 2:
y = (6 + 4) / 2
Parentheses also can be useful in cases where the precedence of an expression isn’t immediately
clear—in other words, they can make your code easier to read. Adding parentheses doesn’t hurt,
so if they help you figure out how expressions are evaluated, go ahead and use them.
String Arithmetic
One special expression in Java is the use of the addition operator (+) to create and concatenate
strings. In most of the previous examples shown today and in earlier lessons, you’ve seen lots of
lines that looked something like this:
[Link](name + “ is a “ + color “ beetle”);
The output of that line (to the standard output) is a single string, with the values of the variables
(here, name and color), inserted in the appropriate spots in the string. So what’s going on here? 57
M
T
W
R
DAY
3 Java Basics
The + operator, when used with strings and other objects, creates a single string that contains
the concatenation of all its operands. If any of the operands in string concatenation is not a string,
it is automatically converted to a string, making it easy to create these sorts of output lines.
String concatenation makes lines such as the previous one especially easy to construct. To create
a string, just add all the parts together—the descriptions plus the variables—and output it to the
standard output, to the screen, to an applet, or anywhere.
The += operator, which you learned about earlier, also works for strings. For example, take the
following expression:
myName += “ Jr.”;
just as it would be for numbers. In this case, it changes the value of myName (which might be
something like John Smith to have a Jr. at the end (John Smith Jr.).
Summary
As you learned in the last two lessons, a Java program is made up primarily of classes and objects.
Classes and objects, in turn, are made up of methods and variables, and methods are made up
of statements and expressions. It is those last two things that you’ve learned about today; the
basic building blocks that enable you to create classes and methods and build them up to a full-
fledged Java program.
Today, you learned about variables, how to declare them and assign values to them; literals for
easily creating numbers, characters, and strings; and operators for arithmetic, tests, and other
simple operations. With this basic syntax, you can move on tomorrow to learning about working
with objects and building simple useful Java programs.
To finish up this summary, Table 3.8 is a list of all the operators you learned about today so that
you can refer back to them.
58
net
ing
r
Sams.
Learn
Cente
Table 3.8. Operator summary.
Operator Meaning
+ Addition
– Subtraction
* Multiplication
÷ Division
% Modulus
< Less than
> Greater than
≤ Less than or equal to
≥ Greater than or equal to 3
== Equal
!= Not equal
&& Logical AND
|| Logical OR
! Logical NOT
& AND
| OR
^ XOR
continues
59
M
T
W
R
DAY
3 Java Basics
Q&A
Q I didn’t see any way to define constants.
A You can’t create local constants in Java; you can create only constant instance and class
variables. You’ll learn how to do this tomorrow.
Q What happens if you declare a variable to be some integer type and then give it a
number outside the range of values that variable can hold?
A Logically, you would think that the variable is just converted to the next larger type,
but this isn’t what happens. What does happen is called overflow. This means that if a
number becomes too big for its variable, that number wraps around to the smallest
possible negative number for that type and starts counting upward toward zero again.
Because this can result in some very confusing (and wrong) results, make sure that you
declare the right integer type for all your numbers. If there’s a chance a number will
overflow its type, use the next larger type instead.
Q How can you find out the type of a given variable?
A If you’re using the base types (int, float, boolean), and so on, you can’t. If you care
about the type, you can convert the value to some other type by using casting (you’ll
learn about this tomorrow).
If you’re using class types, you can use the instanceof operator, which you’ll learn
more about tomorrow.
Q Why does Java have all these shorthand operators for arithmetic and assignment?
It’s really hard to read that way.
A The syntax of Java is based on C++, and therefore on C. One of C’s implicit goals is
the capability of doing very powerful things with a minimum of typing. Because of
this, shorthand operators, such as the wide array of assignments, are common.
There’s no rule that says you have to use these operators in your own programs,
however. If you find your code to be more readable using the long form, no one will
come to your house and make you change it.
60
net
ing
r
Sams.
Learn
Cente
4 F
S
S WEEK
1
4
R
W with
Working
T
Objects
M
by Laura Lemay
61
M
T
W
R
DAY
Let’s start today’s lesson with an obvious statement: because Java is an object-oriented language,
you’re going to be dealing with a lot of objects. You’ll create them, modify them, move them
around, change their variables, call their methods, combine them with other objects—and, of
course, develop classes and use your own objects in the mix.
Today, therefore, you’ll learn all about the Java object in its natural habitat. Today’s topics
include:
■ Creating instances of classes
■ Testing and modifying class and instance variables in your new instance
■ Calling methods in that object
■ Casting (converting) objects and other data types from one class to another
■ Other odds and ends about working with objects
■ An overview of the Java class libraries
Note: What about the literals for numbers and characters? Don’t they create
objects, too? Actually, they don’t. The primitive data types for numbers and
characters create numbers and characters, but for efficiency, they aren’t actually
objects. You can put object-wrappers around them if you need to treat them like
objects (you’ll learn how to do this later).
62
net
ing
r
Sams.
Learn
Cente
Using new
To create a new object, you use new with the name of the class you want to create an instance
of, then parentheses after that:
String str = new String();
The parentheses are important; don’t leave them off. The parentheses can be empty, in which
case the most simple, basic object is created, or the parentheses can contain arguments that
determine the initial values of instance variables or other initial qualities of that object. The
number and type of arguments you can use with new are defined by the class itself by using a
special method called a constructor; you’ll learn about how to create constructors in your own
classes later on this week.
! Caution: Some classes may not enable you to create instances without any argu-
ments. Check the class to make sure. 4
For example, take the Date class, which creates date objects. Listing 4.1 is a Java program that
shows three different ways of creating a Date object using new:
63
M
T
W
R
DAY
In this example, three different dates are created by using different arguments to new. The
Analysis first instance (line 8) uses new with no arguments, which creates a Date object for today’s
date (as the first line of the output shows).
The second Date object you create in this example has five integer arguments. The arguments
represent a date: year, month, day, hours, and seconds. And, as the output shows, this creates
a Date object for that particular date: Sunday, August first, 1971, at 7:30 AM.
The third version of Date takes one argument, a string, representing the date as a text string.
When the Date object is created, that string is parsed, and a Date object with that date and time
is created (see the third line of output). The date string can take many different formats; see the
API documentation for the Date class (part of the [Link] package) for information about
what strings you can use.
NEW☛ Constructors are special methods for creating and initializing new instances of classes.
TERM Constructors initialize the new object and its variables, create any other objects that object
needs, and generally perform any other operations the object needs to run.
Multiple constructor definitions in a class can each have a different number or type of
arguments—then, when you use new, you can specify different arguments in the argument list,
and the right constructor for those arguments will be called. That’s how each of those different
versions of new that were listed previously can create different things.
When you create your own classes, you can define as many constructors as you need to
implement that class’s behavior. You’ll learn how to create constructors on Day 7.
64
net
ing
r
Sams.
Learn
Cente
and reclaims the memory that those objects are using. You don’t have to do any explicit freeing
of memory; you just have to make sure you’re not still holding onto an object you want to get
rid of. You’ll learn more specific details about the Java garbage collector and how it works on
Day 21.
Getting Values
To get at the value to an instance variable, you use dot notation.
NEW☛ With dot notation, an instance or class variable name has two parts: the object on the left 4
TERM side of the dot, and the variable on the right side of the dot.
For example, if you have an object assigned to the variable myObject, and that object has a variable
called var, you refer to that variable’s value like this:
[Link];
This form for accessing variables is an expression (it returns a value), and both sides of the dot
are also expressions. This means that you can nest instance variable access. If that var instance
variable itself holds an object, and that object has its own instance variable called state, you can
refer to it like this:
[Link];
Dot expressions are evaluated left to right, so you start with myObject’s variable var, which points
to another object with the variable state. You end up with the value of that state variable.
Changing Values
Assigning a value to that variable is equally easy—just tack an assignment operator on the right
side of the expression:
[Link] = true;
65
M
T
W
R
DAY
Listing 4.2 is an example of a program that tests and modifies the instance variables in a Point
object. Point is part of the [Link] package and refers to a coordinate point with an x and a y
value.
X is 10
Output Y is 10
Setting X to 5.
Setting y to 15.
X is 5
Y is 15
In this example, you first create an instance of Point where X and Y are both 10 (line 6). Lines
Analysis 8 and 9 print out those individual values, and you can see dot notation at work there. Lines
11 through 14 change the values of those variables to 5 and 15, respectively. Finally, lines
16 and 17 print out the values of X and Y again to show how they’ve changed.
Class Variables
Class variables, as you learned before, are variables that are defined and stored in the class itself.
Their values, therefore, apply to the class and to all its instances.
With instance variables, each new instance of the class gets a new copy of the instance variables
that class defines. Each instance can then change the values of those instance variables without
affecting any other instances. With class variables, there is only one copy of that variable. Every
instance of the class has access to that variable, but there is only one value. Changing the value
of that variable changes it for all the instances of that class.
66
net
ing
r
Sams.
Learn
Cente
You define class variables by including the static keyword before the variable itself. You’ll learn
more about this on Day 6. For example, take the following partial class definition:
class FamilyMember {
static String surname = “Johnson”;
String name;
int age;
...
}
Instances of the class FamilyMember each have their own values for name and age. But the class
variable surname has only one value for all family members. Change surname, and all the instances
of FamilyMember are affected.
To access class variables, you use the same dot notation as you do with instance variables. To
get or change the value of the class variable, you can use either the instance or the name of the
class on the left side of the dot. Both the lines of output in this example print the same value):
FamilyMember dad = new FamilyMember()
[Link](“Family’s surname is: “ + [Link]);
[Link](“Family’s surname is: “ + [Link]);
Because you can use an instance to change the value of a class variable, it’s easy to become
confused about class variables and where their values are coming from (remember, the value of 4
a class variable affects all the instances). For this reason, it’s a good idea to use the name of the
class when you refer to a class variable—it makes your code easier to read and strange results
easier to debug.
Calling Methods
Calling a method in objects is similar to referring to its instance variables: method calls also use
dot notation. The object whose method you’re calling is on the left side of the dot; the name
of the method and its arguments is on the right side of the dot:
[Link](arg1, arg2, arg3);
Note that all methods must have parentheses after them, even if that method takes no arguments:
[Link]();
If the method you’ve called results in an object that itself has methods, you can nest methods
as you would variables:
[Link]().getName();
You can combine nested method calls and instance variable references as well:
[Link](arg1, arg2);
67
M
T
W
R
DAY
[Link](), the method you’ve been using all through the book this far, is a great
example of nesting variables and methods. The System class (part of the [Link] package)
describes system-specific behavior. [Link] is a class variable that contains an instance of the
class PrintStream that points to the standard output of the system. PrintStream instances have
a println() method that prints a string to that output stream.
Listing 4.3 shows an example of calling some methods defined in the String class. Strings
include methods for string tests and modification, similar to what you would expect in a string
library in other languages.
In line 4, you create a new instance of String by using a string literal (it’s easier that way
Analysis than using new and then putting the characters in individually). The remainder of the
program simply calls different string methods to do different operations on that string:
■ Line 6 prints the value of the string we created in line 4: “Now is the winter of our
discontent”.
68
net
ing
r
Sams.
Learn
Cente
■ Line 7 calls the length() method in the new String object. This string has 35 charac-
ters.
■ Line 9 calls the charAt() method, which returns the character at the given position in
the string. Note that string positions start at 0, so the character at position 5 is s.
■ Line 11 calls the substring() method, which takes two integers indicating a range and
returns the substring at those starting and ending points. The substring() method
can also be called with only one argument, which returns the substring from that
position to the end of the string.
■ Line 13 calls the indexOf() method, which returns the position of the first instance of
the given character (here, ‘d’).
■ Line 15 shows a different use of the indexOf() method, which takes a string argument
and returns the index of the beginning of that string.
■ Finally, line 18 uses the toUpperCase() method to return a copy of the string in all
uppercase.
Class Methods 4
Class methods, like class variables, apply to the class as a whole and not to its instances. Class
methods are commonly used for general utility methods that may not operate directly on an
instance of that class, but fit with that class conceptually. For example, the String class contains
a class method called valueOf(), which can take one of many different types of arguments
(integers, booleans, other objects, and so on). The valueOf() method then returns a new
instance of String containing the string value of the argument it was given. This method doesn’t
operate directly on an existing instance of String, but getting a string from another object or data
type is definitely a String-like operation, and it makes sense to define it in the String class.
Class methods can also be useful for gathering general methods together in one place (the class).
For example, the Math class, defined in the [Link] package, contains a large set of
mathematical operations as class methods—there are no instances of the class Math, but you can
still use its methods with numeric or boolean arguments.
To call a class method, use dot notation as you do with instance methods. As with class variables,
you can use either an instance of the class or the class itself on the left site of the dot. However,
for the same reasons noted in the discussion on class variables, using the name of the class for
class variables makes your code easier to read. The last two lines in this example produce the same
result:
String s, s2;
s = “foo”;
s2 = [Link](5);
s2 = [Link](5);
69
M
T
W
R
DAY
References to Objects
As you work with objects, one important thing going on behind the scenes is the use of references
to those objects. When you assign objects to variables, or pass objects as arguments to methods,
you are passing references to those objects, not the objects themselves or copies of those objects.
An example should make this clearer. Examine the following snippet of code:
import [Link];
class ReferencesTest {
pt1.x = 200;
pt1.y = 200;
[Link](“Point1: “ + pt1.x + “, “ + pt1.y);
[Link](“Point2: “ + pt2.x + “, “ + pt2.y);
}
}
In this program, you declare two variables of type Point, and assign a new Point object to pt1.
Then you assign the value of pt1 to pt2.
Now, here’s the challenge. After changing pt1’s x and y instance variables, what will pt2 look
like?
Here’s the output of that program:
As you can see, pt2 was also changed. When you assign the value of pt1 to pt2, you actually
Analysis create a reference from p2 to the same object to which pt1 refers. Change the object that
pt2 refers to, and you also change the object that pt1 points to, because both are references
to the same object.
The fact that Java uses references becomes particularly important when you pass arguments to
methods. You’ll learn more about this later on today, but keep these references in mind.
70
net
ing
r
Sams.
Learn
Cente
Technical Note: There are no explicit pointers or pointer arithmetic in Java—just
references. However, because of Java references, you have most of the capabilities
that you have with pointers without the confusion and lurking bugs that explicit
pointers can create.
NEW☛ Casting is a mechanism of converting the value of an object or primitive type into another
TERM type. The result of a cast is a new object or value; casting does not affect the original object 4
or value.
Although the concept of casting is a simple one, the rules for what types in Java can be converted
to what other types are complicated by the fact that Java has both primitive types (int, float,
boolean), and object types (String, Point, Window, and so on). Because of these three types, there
are three forms of casts and conversions to talk about in this section:
■ Casting between primitive types: int to float to boolean
■ Casting between object types: an instance of a class to an instance of another class
■ Converting primitive types to objects and then extracting primitive values back out of
those objects
71
M
T
W
R
DAY
To convert a large value to smaller type, you must use an explicit cast, because converting that
value may result in a loss of precision. Explicit casts look like this:
(typename) value
In this form, typename is the name of the type you’re converting to (for example: short, int,
float, boolean), and value is an expression that results in the value you want to convert. This
expression divides the values of x by the value of y and casts the result to an int:
(int) (x / y);
Note that because the precedence of casting is higher than that of arithmetic, you have to use
parentheses so that the result of the division is what gets cast to an int.
Casting Objects
Instances of classes can also be cast to instances of other classes, with one restriction: the class
of the object you’re casting and the class you’re casting it to must be related by inheritance; that
is, you can cast an object only to an instance of its class’s sub- or superclass—not to any random
class.
Analogous to converting a primitive value to a larger type, some objects may not need to be cast
explicitly. In particular, because instances’ subclasses usually contain all the information that
instances’ superclasses do, you can use an instance of a subclass anywhere a superclass is expected.
Suppose you have a method that takes two arguments: one of type Object, and one of type
Number. You don’t have to pass instances of those particular classes to that method. For the Object
argument, you can pass any subclass of Object (any object, in other words), and for the Number
argument you can pass in any instance of any subclass of Number (Integer, Boolean, Float, and
so on).
Casting an object to an instance of one of that object’s superclasses loses the information the
original subclass provided and requires a specific cast. To cast an object to another class, you use
the same casting operation that you used for base types:
(classname) object
In this case, classname is the name of the class you want to cast the object to, and object is a
reference to the object you’re casting. Note that casting creates a new instance of the new class
with all the information that the old object contained; the old object still continues to exist as
it did before.
Here’s a (fictitious) example of a cast of an instance of the class GreenApple to an instance of the
class Apple (where GreenApple is theoretically a subclass of Apple):
GreenApple a;
Apple a2;
72
net
ing
r
Sams.
Learn
Cente
a = new GreenApple();
a2 = (Apple) a;
In addition to casting objects to classes, you can also cast objects to interfaces—but only if that
object’s class or one of its superclasses actually implements that interface. Casting an object to
an interface then enables you to call one of that interface’s methods even if that object’s class does
not directly implement that interface. You’ll learn more about interfaces in Week 3.
Using class methods defined in these classes, you can create an object-equivalent for all the 4
primitive types using new. The following line of code creates an instance of the Integer class with
the value 35:
Integer intObject = new Integer(35);
Once you have actual objects, you can treat those values as objects. Then, when you want the
primitive values back again, there are methods for that as well—for example, the intValue()
method extracts an int primitive value from an Integer object:
int theInt = [Link](); // returns 35
See the Java API documentation for these special classes for specifics on the methods for
converting primitives to and from objects.
73
M
T
W
R
DAY
Comparing Objects
Yesterday, you learned about operators for comparing values: equals, not equals, less than, and
so on. Most of these operators work only on primitive types, not on objects. If you try to use other
values as operands, the Java compiler produces errors.
The exception to this rule is with the operators for equality: == (equal) and != (not equal). These
operators, when used with objects, tests whether the two operands refer to exactly the same
object.
What should you do if you want to be able to compare instances of your class and have
meaningful results? You have to implement special methods in your class, and you have to call
those methods using those method names.
Technical Note: Java does not have the concept of operator overloading—that is,
the capability of defining the behavior of the built-in operators by defining meth-
ods in your own classes. The built-in operators remain defined only for numbers.
A good example of this is the String class. It is possible to have two strings, two independent
objects in memory with the same values—that is, the same characters in the same order.
According to the == operator, however, those two String objects will not be equal, because,
although their contents are the same, they are not the same object.
The String class, therefore, defines a method called equals() that tests each character in the
string and returns true if the two strings have the same values. Listing 4.4 illustrates this.
net
ing
r
Sams.
Learn
Cente
String1: she sells sea shells by the sea shore.
Output String2: she sells
Same object? true
sea shells by the sea shore.
The first part of this program (lines 4 through 6) declares two variables, str1 and str2,
Analysis assigns the literal she sells sea shells by the sea shore. to str1, and then assigns that
value to str2. As you know from object references, now str1 and str2 point to the same
object, and the test at line 10 proves that.
In the second part, you create a new string object with the value of str1. Now you have two
different string objects with the same value. Testing them to see whether they’re the same object
by using the == operator (line 16) returns the expected answer, as does testing them using the
equals method (line 17) to compare their values.
Technical Note: Why can’t you just use another literal when you change str2,
rather than using new? String literals are optimized in Java—if you create a string
using a literal, and then use another literal with the same characters, Java knows
4
enough merely to give you the first String object back. Both strings are the same
objects—to create two separate objects you have to go out of your way.
Copying Objects
Recall from the section on object references that assigning variables and passing objects as
arguments to methods affect only the object’s reference and doesn’t create copies of those
objects. How do you create copies of objects? There are two ways: the copy() method and the
clone() method.
The copy() method (defined in Object, and so available to all objects), takes a single argument—
another instance of the same class—and copies the values of all the argument’s instance variables
into the instance variables of the current object (the one in which you’re calling the method).
Note that if those instance variables in turn hold references to objects, only the references are
copied, not the objects.
Point pt1, pt2, pt3;
pt1 = new Point(0,0);
pt2 = new Point(100,100);
[Link](pt1); // pt1’s values are copied into pt2; both now are (0,0).
75
M
T
W
R
DAY
The clone() method is similar to copy(), except that clone() takes no arguments. The clone()
method creates a new instance of the same class as the source object and then copies the values
of the instance variables (either primitive types or references to other objects). clone() returns
an instance of the class Object; to use it as an instance of the original class you have to cast it.
Here’s an example that clones the Point object in pt2 and stores the result in pt3:
pt3 = (Point) [Link]();
What does this do? The getClass() method is defined in the Object class, and as such is available
for all objects. The result of that method is a Class object (where Class is itself a class), which
has a method called getName(). getName() returns a string representing the name of the class.
Another test that might be useful to you is the instanceof operator. instanceof has two
operands: an object on the left, and the name of a class on the right. The expression returns true
or false based on whether the object is an instance of the named class or any of that class’s
superclasses:
“foo” instanceof String // true
Point pt = new Point(10,10);
pt instanceof String // false
The instanceof operator can also be used for interfaces; if an object implements an interface,
the instanceof operator with an interface name on the right side returns true. You’ll learn all
about interfaces in Week 3.
76
net
ing
r
Sams.
Learn
Cente
and their methods and instance variables is a great way to figure out what Java can and cannot
do, as well as a starting point for your own development.
Here are the class packages that are part of the Java class libraries:
■ [Link]: Classes that apply to the language itself, which includes the Object class,
the String class, and the System class. It also contains the special classes for the
primitive types (Integer, Character, Float, and so on).
■ [Link]: Utility classes, such as Date, as well as simple collection classes, such as
Vector and Hashtable.
■ [Link]: Input and output classes for writing to and reading from streams (such as
standard input and output) and for handling files.
■ [Link]: Classes for networking support, including Socket and URL (a class to
represent references to documents on the World Wide Web).
■ [Link]: (the Abstract Window Toolkit): Classes to implement a graphical user
interface, including classes for Window, Menu, Button, Font, CheckBox, and so on. This
package also includes classes for processing images (the [Link] package).
■ [Link]: Classes to implement Java applets, including the Applet class itself, as
4
well as the AudioClip class.
In addition to the Java classes, your development environment may also include additional
classes that provide other utilities or functionality. Although these classes may be useful, because
they are not part of the standard Java library, they won’t be available to other people trying to
run your Java program. This is particularly important for applets, because applets are expected
to be able to run on any platform, using any Java-aware browser. Only classes inside the java
package are guaranteed to be available on all browsers and Java environments.
Summary
Objects, objects everywhere. Today, you learned all about how to deal with objects: how to
create them, how to find out and change the values of their variables, and how to call their
methods. You also learned how to copy and compare them, and how to convert them into other
objects. Finally, you learned a bit about the Java class libraries—which give you a whole slew of
classes to play with in your own programs.
You now have the fundamentals of how to deal with most simple things in the Java language.
All you have left are arrays, conditionals, and loops, which you’ll learn about tomorrow. Then
you’ll learn how to define and use classes in Java applications on Day 6, and launch directly into
applets next week. With just about everything you do in your Java programs, you’ll always come
back to objects.
77
M
T
W
R
DAY
Q&A
Q I’m confused about the differences between objects and the primitive data types,
such as int and boolean.
A The primitive types in the language (byte, short, int, long, float, double, and char)
represent the smallest things in the language. They are not objects, although in many
ways they can be handled like objects—they can be assigned to variables and passed in
and out of methods. Most of the operations that work exclusively on objects, however,
will not.
Objects usually represent instances of classes and as such, are much more complex
data types than simple numbers and characters, often containing numbers and
characters as instance or class variables.
Q In the section on calling methods, you had examples of calling a method with a
different number of arguments each time—and it gave a different kind of result.
How is that possible?
A That’s called method overloading. Overloading enables the same function name to have
different behavior based on the arguments it’s called with—and the number and type
of arguments can vary. When you define methods in your own classes, you define
separate method signatures with different sets or arguments and different definitions.
When that method is called, Java figures out which definition to execute based on the
number and type of arguments with which you called it.
You’ll learn all about this on Day 6.
Q No operator overloading in Java? Why not? I thought Java was based on C++,
and C++ has operator overloading.
A Java was indeed based on C++, but it was also designed to be simple, so many of
C++’s features have been removed. The argument against operator overloading is that
because the operator can be defined to mean anything, it makes it very difficult to
figure out what any given operator is doing at any one time. This can result in entirely
unreadable code. Given the potential for abuse, the designers of Java felt it was one of
the C++ features that was best left out.
78
net
ing
r
Sams.
Learn
Cente
5 F
S
S WEEK
1
R 5
W
Arrays,
T
Conditionals,
M and Loops
by Laura Lemay
79
M
T
W
R
DAY
Although you could write Java programs using what you’ve learned so far, those programs would
be pretty dull. Much of the good stuff in Java or in any programming language results when you
have arrays to store values in and control-flow constructs (loops and conditionals) to execute
different bits of a program based on tests. Today, you’ll find out about the following:
■ Arrays, one of the most useful objects in Java, which enable you to collect objects into
an easy-to-manage list
■ Block statements, for grouping together related statements
■ if and switch, for conditional tests
■ for and while loops, for iteration or repeating a statement or statements multiple
times
Arrays
Arrays in Java are different than they are in other languages. Arrays in Java are actual objects that
can be passed around and treated just like other objects.
NEW☛ Arrays are a way to store a list of items. Each element of the array holds an individual item,
TERM and you can place items into and remove items from those slots as you need to.
Arrays can contain any type of value (base types or objects), but you can’t store different types
in a single array. You can have an array of integers, or an array of strings, or an array of arrays,
but you can’t have an array that contains, for example, both strings and integers.
To create an array in Java, you use three steps:
1. Declare a variable to hold the array.
2. Create a new array object and assign it to the array variable.
3. Store things in that array.
Point hits[];
int temps[];
80
net
ing
r
Sams.
Learn
Cente
An alternate method of defining an array variable is to put the brackets after the type instead of
after the variable. They are equivalent, but this latter form is often much more readable. So, for
example, these three declarations could be written like this:
String[] difficultWords;
Point[] hits;
int[] temps;
That line creates a new array of Strings with ten slots, or elements. When you create the new array
object using new, you must indicate how many elements that array will hold.
Array objects can contain primitive types such as integers or booleans, just as they can contain
objects:
5
int[] temps = new int[99];
When you create an array object using new, all its elements are initialized for you (0 for numeric
arrays, false for boolean, ‘\0’ for character arrays, and null for everything else). You can also
create and initialize an array at the same time. Instead of using new to create the new array object,
enclose the elements of the array inside braces, separated by commas:
String[] chiles = { “jalapeno”, “anaheim”, “serrano,”
“habanero,” “thai” };
Each of the elements inside the braces must be of the same type and must be the same type as
the variable that holds that array. An array the size of the number of elements you’ve included
will be automatically created for you. This example creates an array of String objects named
chiles that contains five elements.
M
T
W
R
DAY
The myArray part of this expression is a variable holding an array object, although it can also be
an expression that results in an array). The subscript is the slot within the array to access, which
can also be an expression. Array subscripts start with 0, as they do in C and C++. So, an array
with ten elements has array values from subscript 0 to 9.
Note that all array subscripts are checked to make sure that they are inside the boundaries of the
array (greater than 0 but less than the array’s length) either when your Java program is compiled
or when it is run. It is impossible in Java to access or assign a value to an array element outside
of the boundaries of the array. Note the following two statements, for example:
String arr[] = new String[10];
arr[10] = “eggplant”;
A program with that last statement in it produces a compiler error at that line when you try to
compile it. The array stored in arr has only ten elements numbered from 0, the element at
subscript 10 doesn’t exist, and the Java compiler will check for that.
If the array subscript is calculated at run-time (for example, as part of a loop) and ends up outside
the boundaries of the array, the Java interpreter also produces an error (actually, to be technically
correct, it throws an exception). You’ll learn more about exceptions later on next week and on
Day 18.
How can you keep from overrunning the end of an array accidentally in your own programs?
You can test for the length of the array in your programs using the length instance variable—
it’s available for all array objects, regardless of type:
int len = [Link] // returns 10
An important thing to note is that an array of objects in Java is an array of references to those
objects (similar in some ways to an array of pointers in C or C++). When you assign a value to
a slot in an array, you’re creating a reference to that object, just as you do for a plain variable.
When you move values around inside arrays (as in that last line), you just reassign the reference;
you don’t copy the value from one slot to another. Arrays of primitive types such as ints or floats
do copy the values from one slot to another.
Arrays of references to objects, as opposed to the objects themselves, are particularly useful
because it means you can have multiple references to the same objects both inside and outside
arrays—for example, you can assign an object contained in an array to a variable and refer to that
same object by using either the variable or the array position.
82
net
ing
r
Sams.
Learn
Cente
Multidimensional Arrays
Java does not support multidimensional arrays. However, you can declare and create an array
of arrays (and those arrays can contain arrays, and so on, for however many dimensions you
need), and access them as you would C-style multidimensional arrays:
int coords[][] = new int[12][12];
coords[0][0] = 1;
coords[0][1] = 2;
Block Statements
A block statement is a group of other statements surrounded by braces ({}). You can use a block
anywhere a single statement would go, and the new block creates a new local scope for the
statements inside it. This means that you can declare and use local variables inside a block, and
those variables will cease to exist after the block is finished executing. For example, here’s a block
inside a method definition that declares a new variable y. You cannot use y outside the block in
which it’s declared:
void testblock() {
int x = 10;
{ // start of block
int y = 50;
[Link](“inside the block:”);
[Link](“x:” + x);
[Link](“y:” + y);
} // end of block
} 5
Blocks are not usually used in this way—alone in a method definition. You’ve mostly seen blocks
up to this point surrounding class and method definitions, but another very common use of
block statements is in the control flow constructs you’ll learn about in the remainder of today’s
lesson.
if Conditionals
The if conditional, which enables you to execute different bits of code based on a simple test
in Java, is nearly identical to if statements in C. if conditionals contain the keyword if,
followed by a boolean test, followed by a statement (often a block statement) to execute if the
test is true:
if (x < y)
[Link](“x is smaller than y”);
An optional else keyword provides the statement to execute if the test is false:
if (x < y)
[Link](“x is smaller than y”);
else [Link](“y is bigger.”);
83
M
T
W
R
DAY
if (engineState == true )
[Link](“Engine is already on.”);
else {
[Link](“Now starting Engine”);
if (gasLevel >= 1)
engineState = true;
else [Link](“Low on gas! Can’t start engine.”);
}
This example uses the test (engineState == false). For boolean tests of this type, a common
shortcut is merely to include the first part of the expression, rather than explicitly testing its value
against true or false:
if (engineState)
[Link](“Engine is on.”);
else [Link](“Engine is off”);
The test is an expression that returns true or false, just like the test in the if statement. If the
test is true, the conditional operator returns the value of trueresult; if it’s false, it returns the
value of falseresult. For example, the following conditional tests the values of x and y, returns
the smaller of the two, and assigns that value to the variable smaller:
int smaller = x < y ? x : y;
The conditional operator has a very low precedence; that is, it’s usually evaluated only after all
its subexpressions are evaluated. The only operators lower in precedence are the assignment
operators. See the precedence chart in Day 3’s lesson for a refresher on precedence of all the
operators.
84
net
ing
r
Sams.
Learn
Cente
switch Conditionals
A common practice in programming in any language is to test a variable against some value, and
if it doesn’t match that value, to test it again against a different value, and if it doesn’t match that
one to make yet another test, and so on. Using only if statements, this can become unwieldy,
depending on how it’s formatted and how many different options you have to test. For example,
you might end up with a set of if statements something like this or longer:
if (oper == ‘+’)
addargs(arg1,arg2);
else if (oper == ‘=’)
subargs(arg1,arg2);
else if (oper == ‘*’)
multargs(arg1,arg2);
else if (oper == ‘/’)
divargs(arg1,arg2);
This form of if statement is called a nested if, because each else statement in turn contains yet
another if, and so on, until all possible tests have been made.
A common shorthand mechanism for nested ifs that you can use in some cases allows you tests
and actions together in a single statement. This is the switch or case statement; in Java it’s switch
and behaves as it does in C:
switch (test) {
case valueOne:
resultOne;
break;
case valueTwo: 5
resultTwo;
break;
case valueThree:
resultThree;
break;
...
default: defaultresult;
}
In the switch statement, the test (a primitive type of byte, char, short, or int) is compared with
each of the case values in turn. If a match is found, the statement, or statements after the test
is executed. If no match is found, the default statement is executed. The default is optional,
so if there isn’t a match in any of the cases and default doesn’t exist, the switch statement
completes without doing anything.
Note that the significant limitation of the switch in Java is that the tests and values can be only
simple primitive types (and then only primitive types that are castable to int). You cannot use
larger primitive types (long, float) or objects within a switch, nor can you test for any
relationship other than equality. This limits the usefulness of switch to all but the simplest cases;
nested ifs can work for any kind of test on any type.
85
M
T
W
R
DAY
Here’s a simple example of a switch statement similar to the nested if shown earlier:
switch (oper) {
case ‘+’:
addargs(arg1,arg2);
break;
case ‘*’:
subargs(arg1,arg2);
break;
case ‘-’:
multargs(arg1,arg2);
break;
case ‘/’:
divargs(arg1,arg2);
break;
}
Note the break statement included in every line. Without the explicit break, once a match is
made, the statements for that match and also all the statements further down in the switch are
executed until a break or the end of the switch is found (and then execution continues after the
end of the switch). In some cases, this may be exactly what you want to do, but in most cases,
you’ll want to make sure to include the break so that only the statements you want to be executed
are executed.
One handy use of falling through occurs when you want multiple values to execute the same
statements. In this instance, you can use multiple case lines with no result, and the switch will
execute the first statements it finds. For example, in the following switch statement, the string
“x is an even number.” is printed if x has values of 2, 4, 6, or 8. All other values of x print the
string “x is an odd number.”
switch (x) {
case 2:
case 4:
case 6:
case 8:
[Link](“x is an even number.”);
break;
default: [Link](“x is an odd number.”);
}
for Loops
The for loop, as in C, repeats a statement or block of statements some number of times until
a condition is matched. for loops are frequently used for simple iteration in which you repeat
a block of statements a certain number of times and then stop, but you can use for loops for just
about any kind of loop.
The for loop in Java looks roughly like this:
for (initialization; test; increment) {
86
net
ing
r
Sams.
Learn
Cente
statements;
}
The statement part of the for loop is the statement that is executed each time the loop iterates.
Just as with if, you can include either a single statement here or a block; the previous example
used a block because that is more common. Here’s an example of a for loop that initializes all
the values of a String array to null strings:
String strArray[] = new String[10];
int i; // loop index
Any of the parts of the for loop can be empty statements, that is, you can simply include a 5
semicolon with no expression or statement, and that part of the for loop will be ignored. Note
that if you do use a null statement in your for loop, you may have to initialize or increment any
loop variables or loop indices yourself elsewhere in the program.
You can also have an empty statement for the body of your for loop, if everything you want to
do is in the first line of that loop. For example, here’s one that finds the first prime number higher
than 4000:
for (i = 4001; notPrime(i); i += 2)
;
Note that a common mistake in C that also occurs in Java is accidentally to put a semicolon after
the first line of the for loop:
for (i = 0; i < 10; i++);
[Link](“Loop!”);
Because the first semicolon ends the loop with an empty statement, the loop doesn’t actually do
anything. The println function will be printed only once, because it’s actually outside the for
loop entirely. Be careful not to make this mistake in your own Java programs.
87
M
T
W
R
DAY
while and do loops, like for, are exactly the same as those same constructions in C and C++.
while Loops
The while loop is used to repeat a statement or block of statements as long as a particular
condition is true. while loops look like this:
while (condition) {
bodyOfLoop;
}
The condition is a boolean expression. If it returns true, the while loop executes the statements
in bodyOfLoop and then tests the condition again, repeating until the condition is false. I’ve
shown the while loop here with a block statement, because it’s most commonly used, although
you can use a single statement in place of the block.
Here’s an example of a while loop that copies the elements of an array of integers (in array1)
to an array of floats (in array2), casting each element to a float as it goes. The one catch is that
if any of the elements in the first array is 0, the loop will immediately exit at that point. To cover
both the cases wherein all the elements have been copied and an element is 0, you can use a
compound test with the && operator:
while ((ch != ‘ ‘) && (ch != ‘\t’) && (ch != ‘\n’) && (ch != ‘\r’)) {
addChar(ch, theName);
ch = [Link]();
}
Note that if the condition is initially false the first time it is tested (for example, if the first element
in that first array is 0), the body of the while loop will never be executed. If you need to execute
the loop at least once, you can do one of two things:
■ Duplicate the body of the loop outside the while loop.
■ Use a do loop (described below).
The do loop is considered the better solution of the two.
88
net
ing
r
Sams.
Learn
Cente
do...while Loops
The do loop is just like a while loop, except that do executes a given statement or block until a
condition is false. The main difference is that while loops test the condition before looping,
making it possible that the body of the loop will never execute if the condition is false the first
time it’s tested. do loops run the body of the loop at least once before testing the condition. do
loops look like this:
do {
bodyOfLoop;
} while (condition);
Here, the bodyOfLoop part is the statements that are executed with each iteration. It’s shown here
with a block statement because it’s most commonly used that way, but you can substitute the
braces for a single statement as you can with the other control-flow constructs. The condition
is a boolean test. If it returns true, the loop is run again. If it returns false, the loop exits. Keep
in mind that with do loops, the body of the loop executes at least once.
Here’s a simple example of a do loop that prints a message each time the loop iterates:
int x = 1;
do {
[Link](“Looping, round “ + x);
x++;
} while (x <= 10);
89
M
T
W
R
DAY
You’ve already seen break as part of the switch statement; it stops execution of the switch, and
the program continues. The break keyword, when used with a loop, does the same thing—it
immediately halts execution of the current loop. If you’ve nested loops within loops, execution
picks up in the next outer loop; otherwise, the program merely continues executing the next
statement after the loop.
For example, suppose you have a while loop that copies elements from one array into another.
Each element in the array should be copied until the end of the array is reached or if an element
contains 0. You can test for that latter case inside the body of the while and then use a break to
exit the loop:
while (count < [Link]) {
if (array1[count] == 0) {
break;
}
array2[count] = array1[count];
count++;
}
}
continue is similar to break except that instead of halting execution of the loop entirely, the loop
starts over at the next iteration. For do and while loops, this means the execution of the clock
starts over again; for for loops, the increment expression is evaluated and then block is executed.
continue is useful when you want to special-case elements within a loop. With the previous
example of copying one array to another, you can test for whether the current element is 0 and
restart the loop if you find it so that the resulting array will never contain zero. Note that because
you’re skipping elements in the first array, you now have to keep track of two different array
counters:
while (count < [Link]) {
if (array1[count] == 0)
continue;
array2[count2++] = (float)array1[count++];
}
Labeled Loops