0% found this document useful (0 votes)
11 views10 pages

Javanote 11

Uploaded by

praveenkumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views10 pages

Javanote 11

Uploaded by

praveenkumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

x CONTENTS

11.1.5 The Scanner Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544


11.1.6 Serialized Object I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
11.2 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
11.2.1 Reading and Writing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
11.2.2 Files and Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
11.2.3 File Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
11.3 Programming With Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
11.3.1 Copying a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
11.3.2 Persistent Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
11.3.3 Files in GUI Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
11.3.4 Storing Objects in Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
11.4 Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
11.4.1 URLs and URLConnections . . . . . . . . . . . . . . . . . . . . . . . . . . 569
11.4.2 TCP/IP and Client/Server . . . . . . . . . . . . . . . . . . . . . . . . . . 571
11.4.3 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
11.4.4 A Trivial Client/Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
11.4.5 A Simple Network Chat . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
11.5 Network Programming and Threads . . . . . . . . . . . . . . . . . . . . . . . . . 581
11.5.1 A Threaded GUI Chat Program. . . . . . . . . . . . . . . . . . . . . . . . 582
11.5.2 A Multithreaded Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
11.5.3 Distributed Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
11.6 A Brief Introduction to XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
11.6.1 Basic XML Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
11.6.2 XMLEncoder and XMLDecoder . . . . . . . . . . . . . . . . . . . . . . . 598
11.6.3 Working With the DOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
Exercises for Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
Quiz on Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609

12 Advanced GUI Programming 611


12.1 Images and Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
12.1.1 Images and BufferedImages . . . . . . . . . . . . . . . . . . . . . . . . . . 611
12.1.2 Working With Pixels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
12.1.3 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
12.1.4 Cursors and Icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
12.1.5 Image File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
12.2 Fancier Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
12.2.1 Measuring Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
12.2.2 Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
12.2.3 Antialiasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
12.2.4 Strokes and Paints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
12.2.5 Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
12.3 Actions and Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
12.3.1 Action and AbstractAction . . . . . . . . . . . . . . . . . . . . . . . . . . 636
12.3.2 Icons on Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
12.3.3 Radio Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
12.3.4 Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
12.3.5 Keyboard Accelerators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
CONTENTS xi

12.3.6 HTML on Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645


12.4 Complex Components and MVC . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
12.4.1 Model-View-Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
12.4.2 Lists and ListModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
12.4.3 Tables and TableModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
12.4.4 Documents and Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654
12.4.5 Custom Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
12.5 Finishing Touches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
12.5.1 The Mandelbrot Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
12.5.2 Design of the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662
12.5.3 Internationalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
12.5.4 Events, Events, Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666
12.5.5 Custom Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
12.5.6 Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
Exercises for Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
Quiz on Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673

Appendix: Source Files 675


xii CONTENTS
Preface

Introduction to Programming Using Java is a free introductory computer programming


textbook that uses Java as the language of instruction. It is suitable for use in an introductory
programming course and for people who are trying to learn programming on their own. There
are no prerequisites beyond a general familiarity with the ideas of computers and programs.
There is enough material for a full year of college-level programming. Chapters 1 through 7
can be used as a textbook in a one-semester college-level course or in a year-long high school
course.
This version of the book covers “Java 5.0”, and many of the examples use features that were
not present in earlier versions of Java. (Sometimes, you will see this version of Java referred
to as Java 1.5 instead of Java 5.0.) Note that Java applets appear throughout the pages of the
on-line version of this book. Many of those applets will be non-functional in Web browsers that
do not support Java 5.0.
The home web site for this book is http://math.hws.edu/javanotes/. The page at that
address contains links for downloading a copy of the web site and for downloading a PDF
version of the book.
∗ ∗ ∗
In style, this is a textbook rather than a tutorial. That is, it concentrates on explaining
concepts rather than giving step-by-step how-to-do-it guides. I have tried to use a conversational
writing style that might be closer to classroom lecture than to a typical textbook. You’ll
find programming exercises at the end of most chapters, and you will find a detailed solution
for each exercise, with the sort of discussion that I would give if I presented the solution in
class. (Solutions to the exercises can be found in the on-line version only.) I strongly advise
that you read the exercise solutions if you want to get the most out of this book. This is
certainly not a Java reference book, and it is not even close to a comprehensive survey of all
the features of Java. It is not written as a quick introduction to Java for people who already
know another programming language. Instead, it is directed mainly towards people who are
learning programming for the first time, and it is as much about general programming concepts
as it is about Java in particular. I believe that Introduction to Programming using Java is
fully competitive with the conventionally published, printed programming textbooks that are
available on the market. (Well, all right, I’ll confess that I think it’s better.)
There are several approaches to teaching Java. One approach uses graphical user interface
programming from the very beginning. Some people believe that object oriented programming
should also be emphasized from the very beginning. This is not the approach that I take. The
approach that I favor starts with the more basic building blocks of programming and builds
from there. After an introductory chapter, I cover procedural programming in Chapters 2, 3,
and 4. Object-oriented programming is introduced in Chapter 5. Chapters 6 covers the closely
related topic of event-oriented programming and graphical user interfaces. Arrays are covered in
Chapter 7. Chapter 8 marks a turning point in the book, moving beyond the fundamental ideas

xiii
xiv Preface

of programming to cover more advanced topics. Chapter 8 is mostly about writing robust and
correct programs, but it also has a section on parallel processing and threads. Chapters 9 and
10 cover recursion and data structures, including the Java Collection Framework. Chapter 11 is
about files and networking. Finally, Chapter 12 returns to the topic of graphical user interface
programming to cover some of Java’s more advanced capabilities.
∗ ∗ ∗
Major changes have been made in the fifth edition. Perhaps the most significant change is
the use of parameterized types in the chapter on generic programming. Parameterized types—
Java’s version of templates—were the most eagerly anticipated new feature in Java 5.0.
Other new features in Java 5.0 are also covered. Enumerated types are introduced, although
they are not covered in their full complexity. The “for-each” loop is covered and is used
extensively. Formatted output is also used extensively, and the Scanner class is covered (though
not until Chapter 11). Static import is covered briefly, as are variable arity methods.
The non-standard TextIO class that I use for input in the first half of the book has been
rewritten to support formatted output. I have also added some file I/O capabilities to this class
to make it possible to cover some examples that use files early in the book.
Javadoc comments are covered for the first time in this edition. Almost all code examples
have been revised to use Javadoc-style comments.
The coverage of graphical user interface programming has been reorganized, much of it has
been rewritten, and new material has been added. In previous editions, I emphasized applets.
Stand-alone GUI applications were covered at the end, almost as an afterthought. In the fifth
edition, the emphasis on applets is gone, and almost all examples are presented as stand-alone
applications. However, applet versions of each example are still presented on the web pages of
the on-line version of the book. The chapter on advanced GUI programming has been moved
to the end, and a significant amount of new material has been added, including coverage of
some of the features of Graphics2D.
Aside from the changes in content, the appearance of the book has been improved, especially
the appearance of the PDF version. For the first time, the quality of the PDF approaches that
of conventional textbooks.
∗ ∗ ∗
The latest complete edition of Introduction to Programming using Java is always available
on line at http://math.hws.edu/javanotes/. The first version of the book was written in 1996,
and there have been several editions since then. All editions are archived at the following Web
addresses:
• First edition: http://math.hws.edu/eck/cs124/javanotes1/ (Covers Java 1.0.)
• Second edition: http://math.hws.edu/eck/cs124/javanotes2/ (Covers Java 1.1.)
• Third edition: http://math.hws.edu/eck/cs124/javanotes3/ (Covers Java 1.1.)
• Fourth edition: http://math.hws.edu/eck/cs124/javanotes4/ (Covers Java 1.4.)
• Fifth edition: http://math.hws.edu/eck/cs124/javanotes5/ (Covers Java 5.0.)
Introduction to Programming using Java is free, but it is not in the public domain. As
of Version 5.0, it is published under the terms of the Creative Commons Attribution-Share
Alike 2.5 License. To view a copy of this license, visit http://creativecommons.org/licenses/by-
sa/2.5/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco,
California, 94105, USA. This license allows redistribution and modification under certain terms.
For example, you can:
Preface xv

• Post an unmodified copy of the on-line version on your own Web site (including the parts
that list the author and state the license under which it is distributed!).
• Give away or sell printed, unmodified copies of this book, as long as they meet the re-
quirements of the license.
• Make modified copies of the complete book or parts of it and post them on the web or
otherwise distribute them, provided that attribution to the author is given, the modifica-
tions are clearly noted, and the modified copies are distributed under the same license as
the original. This includes translations to other languages.
While it is not actually required by the license, I do appreciate hearing from people who
are using or distributing my work.
∗ ∗ ∗
A technical note on production: The on-line and PDF versions of this book are created
from a single source, which is written largely in XML. To produce the PDF version, the XML
is processed into a form that can be used by the TeX typesetting program. In addition to XML
files, the source includes DTDs, XSLT transformations, Java source code files, image files, a
TeX macro file, and a couple of scripts that are used in processing. I have not made the source
materials available for download, since they are not in a clean enough form to be publishable,
and because it would require a fair amount of expertise to make any use of them. However,
they are not meant to be secret, and I am willing to make them available on request.
∗ ∗ ∗
Professor David J. Eck
Department of Mathematics and Computer Science
Hobart and William Smith Colleges
Geneva, New York 14456, USA
Email: [email protected]
WWW: http://math.hws.edu/eck/
xvi Preface
Chapter 1

Overview: The Mental Landscape

When you begin a journey, it’s a good idea to have a mental map of the terrain you’ll
be passing through. The same is true for an intellectual journey, such as learning to write
computer programs. In this case, you’ll need to know the basics of what computers are and
how they work. You’ll want to have some idea of what a computer program is and how one is
created. Since you will be writing programs in the Java programming language, you’ll want to
know something about that language in particular and about the modern, networked computing
environment for which Java is designed.
As you read this chapter, don’t worry if you can’t understand everything in detail. (In fact,
it would be impossible for you to learn all the details from the brief expositions in this chapter.)
Concentrate on learning enough about the big ideas to orient yourself, in preparation for the
rest of the book. Most of what is covered in this chapter will be covered in much greater detail
later in the book.

1.1 The Fetch and Execute Cycle: Machine Language


A computer is a complex system consisting of many different components. But at the
heart—or the brain, if you want—of the computer is a single component that does the actual
computing. This is the Central Processing Unit, or CPU. In a modern desktop computer,
the CPU is a single “chip” on the order of one square inch in size. The job of the CPU is to
execute programs.
A program is simply a list of unambiguous instructions meant to be followed mechanically
by a computer. A computer is built to carry out instructions that are written in a very simple
type of language called machine language. Each type of computer has its own machine
language, and the computer can directly execute a program only if the program is expressed in
that language. (It can execute programs written in other languages if they are first translated
into machine language.)
When the CPU executes a program, that program is stored in the computer’s main mem-
ory (also called the RAM or random access memory). In addition to the program, memory
can also hold data that is being used or processed by the program. Main memory consists of a
sequence of locations. These locations are numbered, and the sequence number of a location
is called its address. An address provides a way of picking out one particular piece of informa-
tion from among the millions stored in memory. When the CPU needs to access the program
instruction or data in a particular location, it sends the address of that information as a sig-
nal to the memory; the memory responds by sending back the data contained in the specified

1
2 CHAPTER 1. THE MENTAL LANDSCAPE

location. The CPU can also store information in memory by specifying the information to be
stored and the address of the location where it is to be stored.
On the level of machine language, the operation of the CPU is fairly straightforward (al-
though it is very complicated in detail). The CPU executes a program that is stored as a
sequence of machine language instructions in main memory. It does this by repeatedly reading,
or fetching , an instruction from memory and then carrying out, or executing , that instruc-
tion. This process—fetch an instruction, execute it, fetch another instruction, execute it, and so
on forever—is called the fetch-and-execute cycle. With one exception, which will be covered
in the next section, this is all that the CPU ever does.
The details of the fetch-and-execute cycle are not terribly important, but there are a few
basic things you should know. The CPU contains a few internal registers, which are small
memory units capable of holding a single number or machine language instruction. The CPU
uses one of these registers—the program counter , or PC—to keep track of where it is in the
program it is executing. The PC stores the address of the next instruction that the CPU should
execute. At the beginning of each fetch-and-execute cycle, the CPU checks the PC to see which
instruction it should fetch. During the course of the fetch-and-execute cycle, the number in the
PC is updated to indicate the instruction that is to be executed in the next cycle. (Usually,
but not always, this is just the instruction that sequentially follows the current instruction in
the program.)
∗ ∗ ∗

A computer executes machine language programs mechanically—that is without under-


standing them or thinking about them—simply because of the way it is physically put together.
This is not an easy concept. A computer is a machine built of millions of tiny switches called
transistors, which have the property that they can be wired together in such a way that an
output from one switch can turn another switch on or off. As a computer computes, these
switches turn each other on or off in a pattern determined both by the way they are wired
together and by the program that the computer is executing.
Machine language instructions are expressed as binary numbers. A binary number is made
up of just two possible digits, zero and one. So, a machine language instruction is just a sequence
of zeros and ones. Each particular sequence encodes some particular instruction. The data that
the computer manipulates is also encoded as binary numbers. A computer can work directly
with binary numbers because switches can readily represent such numbers: Turn the switch on
to represent a one; turn it off to represent a zero. Machine language instructions are stored
in memory as patterns of switches turned on or off. When a machine language instruction
is loaded into the CPU, all that happens is that certain switches are turned on or off in the
pattern that encodes that particular instruction. The CPU is built to respond to this pattern
by executing the instruction it encodes; it does this simply because of the way all the other
switches in the CPU are wired together.
So, you should understand this much about how computers work: Main memory holds
machine language programs and data. These are encoded as binary numbers. The CPU fetches
machine language instructions from memory one after another and executes them. It does
this mechanically, without thinking about or understanding what it does—and therefore the
program it executes must be perfect, complete in all details, and unambiguous because the CPU
can do nothing but execute it exactly as written. Here is a schematic view of this first-stage
understanding of the computer:
1.2. ASYNCHRONOUS EVENTS 3

Memory
00101110 (Location 0)
11010011 (Location 1)
Data to memory 01010011 (Location 2)
00010000 (Location 3)
CPU 10111111
Data from memory 10100110
11101001
Program 00000111
counter: 10100110
Address for
1011100001 reading/writing 00010001
data 00111110 (Location 10)

1.2 Asynchronous Events: Polling Loops and Interrupts


The CPU spends almost all of its time fetching instructions from memory and executing
them. However, the CPU and main memory are only two out of many components in a real
computer system. A complete system contains other devices such as:
• A hard disk for storing programs and data files. (Note that main memory holds only a
comparatively small amount of information, and holds it only as long as the power is turned
on. A hard disk is necessary for permanent storage of larger amounts of information, but
programs have to be loaded from disk into main memory before they can actually be
executed.)
• A keyboard and mouse for user input.
• A monitor and printer which can be used to display the computer’s output.
• A modem that allows the computer to communicate with other computers over telephone
lines.
• A network interface that allows the computer to communicate with other computers
that are connected to it on a network.
• A scanner that converts images into coded binary numbers that can be stored and
manipulated on the computer.
The list of devices is entirely open ended, and computer systems are built so that they can
easily be expanded by adding new devices. Somehow the CPU has to communicate with and
control all these devices. The CPU can only do this by executing machine language instructions
(which is all it can do, period). The way this works is that for each device in a system, there
is a device driver , which consists of software that the CPU executes when it has to deal
with the device. Installing a new device on a system generally has two steps: plugging the
device physically into the computer, and installing the device driver software. Without the
device driver, the actual physical device would be useless, since the CPU would not be able to
communicate with it.

You might also like