Download Complete Java the UML way integrating object oriented design and programming Else Lervik PDF for All Chapters
Download Complete Java the UML way integrating object oriented design and programming Else Lervik PDF for All Chapters
https://ebookultra.com/download/object-oriented-design-with-uml-and-
java-1st-edition-kenneth-barclay/
https://ebookultra.com/download/object-oriented-software-engineering-
using-uml-patterns-and-java-2nd-edition-bernd-bruegge/
https://ebookultra.com/download/applying-uml-and-patterns-an-
introduction-to-object-oriented-programming-2ed-edition-larmen/
https://ebookultra.com/download/scientific-software-design-the-object-
oriented-way-1st-edition-damian-rouson/
Java Methods Object Oriented Programming and Data
Structures Third AP 3rd AP Edition Maria Litvin
https://ebookultra.com/download/java-methods-object-oriented-
programming-and-data-structures-third-ap-3rd-ap-edition-maria-litvin/
https://ebookultra.com/download/beginning-c-object-oriented-
programming-2nd-edition-dan-clark/
https://ebookultra.com/download/object-oriented-programming-in-c-4th-
edition-e-balagurusamy/
https://ebookultra.com/download/object-oriented-software-development-
using-java-principles-patterns-and-frameworks-2nd-edition-xiaoping-
jia/
Java the UML way integrating object oriented design and
programming Else Lervik Digital Instant Download
Author(s): Else Lervik, Vegard B. Havdal
ISBN(s): 9780470854884, 047085488X
Edition: English language ed
File Details: PDF, 58.13 MB
Year: 2002
Language: english
This page intentionally left blank
Java the UML Way
Integrating Object-Oriented Design and Programming
All Rights Reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by
any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except under the terms of the Copyright,
Designs and Patents Act 1988 or under the terms of a licence issued by the Copyright Licensing Agency Ltd, 90 Tottenham Court
Road, London, UK W1P OLP, without the permission in writing of the Publisher with the exception of any material supplied
specifically for the purpose of being entered and executed on a computer system for exclusive use by the purchaser of the
publication.
Neither the authors nor John Wiley & Sons, Ltd accept any responsibility or liability for loss or damage occasioned to any person
or property through using the material, instructions, methods or ideas contained herein, or acting or refraining from acting as a
result of such use. The authors and publisher expressly disclaim all implied warranties, including merchantability or fitness for
any particular purpose. There will be no duty on the authors or publisher to correct any errors or defects in the software.
Designations used by companies to distinguish their products are often claimed as trademarks. In all instances where John Wiley
& Sons, Ltd is aware of a claim, the product names appear in capital or all capital letters. Readers, however, should contact the
appropriate companies for more complete information regarding trademarks and registration.
A catalogue record for this book is available from the British Library
1 Introduction 1
1.1 Preliminaries for Reading This Book 2
1.2 Contemplating a Computer 3
1.3 Java Applications and Java Applets 5
1.4 JavaScript and JSP 6
1.5 How This Book is Structured 7
1.6 A Small Example Program 9
1.7 Examples of Applets 15
1.8 New Concepts in This Chapter 17
1.9 Review Problems 19
1.10 Programming Problems 20
2 Variables, Data Types, and Expressions 21
2.1 Example 22
2.2 Data and Variables 22
2.3 Algorithms, Programming Errors, and Test Data 26
2.4 Statements, Blocks, and Names 28
2.5 Variables and Constants 30
2.6 Data Types 34
2.7 Assignments and Arithmetical Expressions 40
2.8 Type Conversion 43
2.9 Calculations for Our Renovation Project 45
2.10 New Concepts in This Chapter 47
2.11 Review Problems 49
2.12 Programming Problems 49
3 Using Ready-Made Classes 51
3.1 Objects as Models of Reality 52
3.2 Using Ready-Made Classes 55
3.3 The Random Class 60
3.4 The String Class 63
3.5 Organizing Classes in Packages 70
3.6 Class Methods and Class Constants in the Java Library 71
3.7 Reading Data from the User 73
3.8 New Concepts in This Chapter 77
3.9 Review Problems 79
3.10 Programming Problems 79
4 Constructing Your Own Classes 81
4.1 Creating Classes 82
4.2 Programming a Class 85
4.3 Access Modifiers - Private and Public 91
Contents
16 Threads 499
16.1 Threads in Processes 500
16.2 Dividing Time Between Threads 502
16.3 Example of Threads in Use 503
16.4 Thread States 507
16.5 Communication Between Threads 508
16.6 Locks and Synchronization 510
16.7 More Control: wait(), notify(), and notifyAll() 515
16.8 Peeking at the Threads with JDB 519
16.9 New Concepts in This Chapter 521
16.10 Review Problems 522
16.11 Programming Problem 522
Appendices
A Using Java SDK and WinEdit 699
A.1 SDK 699
A.2 Running Applets 703
A.3 WinEdit 703
B Keywords 705
C Number Systems 707
D The Unicode Character Set 711
E HTML and Applets 713
F Exceptions to the Code Standard 717
References 719
Index 721
This textbook was designed for higher education in technological fields where Java
and object-orientation form the basis of programming education. This book covers
both basic and more advanced programming.
The book assumes a general familiarity with computers, operating systems, and
the most common tools (such as, for example, word processors and browsers).
Readers should be familiar with concepts like "file" and "directory" and know the
difference between internal memory (RAM) and storage (for example, the hard
disk).
A foundation in object-orientation
When using Java as an educational language, it makes sense for readers to deal with
object-oriented ways of thinking as soon as possible. To a large extent, modern
programming consists of using ready-made components and classes. It's possible
to make a Java program that draws geometric figures, displays images, and plays
sound files without using anything more complicated than sequential control
structure. We believe that graphics and graphical user interfaces will motivate
further study into both object-orientation and programming in general, more so
than difficult control structures and textual user interfaces.
Readers will be introduced to the Java API for the first time in chapter 3. We'll
introduce the standard JOptionPane class which makes it possible to create
programs with primitive graphical user interfaces. We'll also use the Random and
String classes. This will teach readers to use ready-made classes and at the same
time provide a general introduction to object-oriented ways of thinking.
Once readers have used ready-made classes, we believe they will want to find out
what these classes look like inside. We devote quite a bit of space to creating our
own classes, a broad and comprehensive topic. In chapter 4, the readers will get to
create their own applets with simple geometrical figures where they can control the
shape, colors, and fonts themselves.
With this as a foundation, more classes follow to demonstrate the need for
selection and loop control structures.
Preface
Software
The software necessary for writing Java programs can be downloaded free from the
Internet. This book builds on the Java 2 SDK. The SDK is available on Sun's Web
pages (http://java.sun.com/). This book explains how the package is used. In
addition, you'll need a good editor. Alternatively, you can use an integrated
development environment, for example JBuilder Foundation, which you can get
from Borland's pages on the Internet (http://www.borland.com/jbuilder/).
To develop dynamic Web pages with JavaServer Pages (chapter 21), the reader
needs a web server. The book gives instructions on installation and use of a free
web server, LiteWebServer from http://www.gefionsoftware.com/.
Teaching aids
The book includes several teaching aids: every chapter starts with the chapter's
learning goals and ends with a list of the new concepts introduced, review
problems, and more involved programming problems. In addition, most
subchapters end with shorter problems, where the reader is encouraged to actively
work with the material that was just covered.
The book's Internet page (see above) includes a set of overheads that go with
each chapter. The overheads are based primarily on the book, but also contain
some examples and figures not found in the book.
Preface
Intermediate topics
This part of the book will prepare readers to make comprehensive programs with
graphical user interfaces. This requires extensive use of the Java API and a thorough
understanding of the concepts in an object-oriented system (such as associations
and generalizations, for example).
Arrays of reference types are essentially different in their structure and behavior
from arrays of primitive data types. Therefore, we've chosen to treat these in a
separate chapter along with the ArrayList class, which is a class that hides
reference arrays with dynamic lengths. For many practical purposes, this class is
better suited than an ordinary array of reference type. Chapter 10 also covers classes
with prepared sort-and-search methods including classes that make it possible to
take a country's character sets into consideration.
Chapter 10 introduces further relationships between objects in the form of
associations. We emphasize a demonstration of the transition from class diagram
to program code.
Chapter 11 deals with communication between programs and data files. The
chapter covers both text and binary transfers as well as direct access to a file.
Serialization is a simple, but very useful technique that we'll cover here.
Chapter 12 deals with some of the more important topics in object-orientation,
namely inheritance and polymorphism. Modeling is important here. Readers will
learn the difference between association and generalization. It's important to
thoroughly understand the conceptual apparatus to program inheritance correctly.
With a solid foundation in object-oriented programming, readers should now
be in a position to understand the event model used to program graphical user
interfaces in Java. Chapters 13–15 cover this topic. The most common graphical
components are covered and emphasis is placed on distinguishing the classes that
describe the problem to be solved from the classes that describe the user interface.
Readers will create both applets and applications.
comments. Engineer Simon Thoresen wrote answers for well over 30 programming
problems. The solutions for many of the most complicated problems present
material that supplements the contents of the book.
We would especially like to thank the three lecturers who dared to believe that
this would become instructional material that they could use during the 1999/2000
school year: Assistent Professor Bjorn Klefstad, Associate Professor Jan H. Nilsen,
and Lecturer Grethe Sandstrak. Along with approximately 100 students, they
worked with preliminary and unfinished course materials—their experiences were
very helpful to us.
The chapter on JavaServer Pages is not a part of the Norwegian edition, and
Assistant Professor Tomas Holt has contributed to this chapter with tips and
comments in an indispensable way.
Translator Tara F. Chace did an excellent job in translating all the text from
Norwegian into English during a very short period. Thanks to her!
Else Lervik
and
Vegard B. Havdal
reduction
• Compile and run a small program you have entered into the computer
The sun was probably shining in San Francisco on the 23rd of May 1995, when the
head of research at Sun Microsystems, John Gage, and perhaps the Internet1
world's biggest celebrity, Netscape founder Marc Andreessen, officially presented
the programming language Java and associated technology.
It was no wonder that Gage was one of the two men on the stage, as the language
in question first saw the light of day during a research project at Sun named Green.
Andreessen had been part of the small group of students who made the first
graphical browser for the WWW (Web), Mosaic. This program, and its successor
Netscape, had revolutionized the computing world during the early 1990s. The
new cooperation between Netscape and Sun would let small programs written in
Java make Web pages interactive and more alive. These plans received a lot of
attention, and there were plenty of ideas about programming toasters over the
Web, and more.
Even today, Java is strongly associated with the Internet, and many people think
the language is exclusively for use on the Web. This is absolutely wrong. Java is a
complete programming language, with its own distinctive features, and more and
less typical fields of use.
1. If these words are new to you, there is a glossary of terms in section 1.8 of this chapter.
1 Introduction
Java is a young programming language. Six or seven years is not long. As a result,
computing professionals or students need to keep up with the continuing
evolution of Java and its associated programs. Writing computer programs in a
language that's undergoing constant refinement may seem like an impossible task,
but in the case of Java, it is not. This is thanks to the language's design and
philosophy. In this book, we hope to give you a basis for understanding this.
2. Keep in mind that Windows Explorer is often configured to hide the suffix of registered file types,
displaying a graphical icon instead. You can check this by looking at View, Options: Hide extensions
for known file types. We recommend not hiding the file extensions, to give you better control and
avoid confusion when several files have the same prefix.
1.2 Contemplating a Computer
we will start working with Java through a console window, you will have to learn
basic textual navigation. We will try to make this easy as we go along. If you need
to read more about this, do a Web search for "MS-DOS commands" or an
equivalent phrase. Or look at the book's Web pages on http://www.tisip.no/Java-
ThellmlWay/, where we have links to some primers.
When it comes to the physical construction of the computer, we have already
mentioned that there is usually a hard disk inside where files are arranged in
directories. Furthermore, it is good to know that there is a central "brain" called the
microprocessor and that the computer has internal memory that is often called RAM,
Random Access Memory. Another name for the microprocessor is CPU, Central
Processing Unit. It would be hard to avoid these terms in a book on programming.
The hard disk is an example of secondary memory. Even if we turn the computer
off, our data and programs will still be intact on the hard disk. All the contents of
the aforementioned internal memory disappear when the power is turned off. The
internal memory is used by the microprocessor to store the running programs, and
their data.
We have published additional information and numbered examples on the
Web. Hence we are assuming that the reader is familiar with using the Internet, at
least browsing a page on the Web and changing the basic configuration of the Web
browser. Try to go to http://www. tisip. no/JavaTheUmlWay/ and see if you can find
your way around.
layer and a window system. The program that implements the console layer in MS-
DOS is called command.com. When we type the command dir in MS-DOS, we
imagine a number of operations being executed in the kernel.
is done, it is run, and it is allowed to communicate actively with the user of the
browser. Instead of retrieving a "dead" HTML file, we now have a small computer
program, and it is the responsibility of the browser in our own living room to
arrange for this program to start and run. Web and applets are good examples of
distributed systems. In a computer network context, with several computers
interconnected, we always try to distribute the amount of work in a reasonable way
between the different computers. When a Web page has 1000 hits in a short period
of time and this page contains some applets, all 1000 clients will all fetch the
applets, and start to run them. This is work that the Web servers would have to do
otherwise, and it could easily have become much too big a task to keep track of all
the information for all the browsers. But this server serves Java applets to the
browsers, saying, "You can do this work yourselves, here is the program."
The other main type of programs are what we call applications. This is
something more traditional; an application consists of program files that altogether
make up a computer program. It is not linked to the Web. In this case, the entire
program is run on the computer we are working on. There are no necessary network
implications. We may also bring the program files home from the office with us
and run the program there. But there are important differences between Java
applications and traditional programs in the form of exe-files. For example, Java
program files are not named archive.exe and cannot be run by typing their name or
double-clicking on them. They have suffix class and require a separate program to
be run. But we will look into this later.
Another very important attribute of programs written in Java is that they are not
tied to a particular brand of computer. We say that the language is architecture neu-
tral or platform independent. This means that you can write a program on your
Windows NT Workstation at work and run it. Then you can bring it home to your
Macintosh or Linux PC and run the same program. If we think back to applets, we
see that this is clearly a prerequisite for applets to work as they were intended. There
are several types of computers used to navigate the Web and if they are all going to
be able to use the applets, which is more or less the situation today, the applet
cannot be written in a way that is usable for only one type of computer. For
example: if a language allows the programmer to write something that is particular
to one specific computer's internal memory layout, that language is not
architecture neutral.
So what does this have to do with Java? The answer is almost nothing, except for
the name. At times, the program code in JavaScript is reminiscent of Java, but it is
something completely different. You will be introduced to JavaScript in Chapter 21.
JSP, or Java Server Pages, is another Java-related technology for advanced Web
applications. You will learn more about that in Chapter 21 also.
Java Core
When we wish to describe parts of the ready-to-use program libraries included with
Java, the API, we do that in a box marked API Reference. Here is an example:
API Reference
Type faces
We have used different type faces for various parts of the text The aim of this is to
make it easy to read. The text in the book is printed in Giovanni. If we include
words of program code inside a paragraph, like int age = 0;, we use a typewriter
face, Courier. We do the same when including examples of program-user
interaction in the console, for instance how to compile and run a program:
When we refer to file names in the text, like autoexec.bat or javac.exe, we use italics.
References
Instead of including them verbatim in the text several times, we have collected our
references to literature and Web pages in a list in Appendix G. A reference to a Web
page in this list from the text itself looks like this: [URL Java book] and a reference
to a book looks like this: [Larman 2000]. The exact addresses and details are
included in the list of references.
Coding standards
When we write computer programs, the appearance of the program code adheres to
a particular style. This has to do with indentations, upper and lower case letters, etc.
The point of this is keeping the code tidy and easy to read. Sun has published a
standard for this, which we use to a large extent. You can find it on [URL Coding
standard] . We recommend sticking to this standard for the appearance of your code
and most of the code in this book does. There are a few things we do differently to
enhance readability. These exceptions of ours are summarized in Appendix F.
Figures
In the book you will learn about a standard for modeling program systems called
UML, Unified Modeling Language. This refers to various types of diagrams used
mainly in the design phase of a program system. Figures that are UML are marked
as such in the captions.
Program Listing 1 .1
r
* PrintText.java VBH 200–08–28
* Prints text several times
*
V
class PrintText {
public static void main(String[] args) {
System.out.println("Our first program...");
for (int i = 0 ; i<10 ; i++) System.out.println(" About to leam Java!");
Program listing 1.1 details a small Java program, or if you like, a (very) small
application. Let's look at the first lines. There is text in English there, and you might
guess that this is for humans, not computers. The lines between / * and * / are com-
ments. Comments are essential in all programming. The point is to explain and
elaborate on aspects of the program. This is for another person who has to read the
program at a later stage, make corrections, or put it to use. But it can also be useful
to you if you need to change something in a program you wrote several years ago.
It is universally regarded as very important to write comments for difficult and
complicated pieces of the code, but it is not uncommon to fail to do so, especially
in an educational context. We think this is because the usefulness of comments is
not apparent in the short term.
Comments make computer programs useful in the long run as well, for instance
when other developers have to work with them. It is important to acquire the habit
of commenting your code well.
The first comment line in the example shows the name of the file where we have
stored this program, PrintText.java. In other words, we imagine that we have typed
this into a text file with Notepad, for instance, and saved it as PrintText.java. The files
do not contain images or headers, and are by no means similar, for example, to a
doc file that Word uses. Text files are widely used, but tend to be less familiar to
Windows users. The ini configuration files in Windows are text files. E-mail and the
majority of all services on the Internet are also based on the same type of text
coding. In all programming languages, the program code itself is also stored in
plain text. A text file is a text file, computer type (almost) notwithstanding, and this
has been the case for a few years. But in Windows 95/98 and MS-DOS there are
complications, since ASCII (a common character set, see the new concepts in
section 1.8) with certain modifications is often being used here.
We mentioned that one may write, save and edit these files using Notepad in
Windows, but this is very far from being a satisfactory tool. We want more
1.6 A Small Example Program
functionality, like having several files open for editing at the same time. One might
use Word and always save as plain text, but this is needlessly cumbersome. So we
suggest using a program named WinEdit. It is a handy text editing tool, or editor, a
short introduction to which is given in Appendix A.
Back to the example program. We had stated that the file in which the program
is stored is called PrintText.java. It is not a coincidence that the first actual code line
in the program is class PrintText. In this case, class denotes the start of
our program. It is true that a program is always a class in Java, but the reverse is not
true. A class can be other things besides a program. Notice the brackets, { and }.
They are used in Java to mark blocks. Blocks are groups of code lines that belong
together and that we need to delimit. If you look closely at the example, there are
two such blocks here, one inside the other. The outer block is the class
PrintText, where we see class PrintText and its block. The next block is
the method main. It is named by public static void main (String []
args) and the brackets. To summarize, you are looking at one class with one
method. In other programming languages, methods are called subroutines or
functions.
So what does this program actually do? A computer program is a way for a
computer to solve a problem. In this example, this solution is what is inside the
main () method. This is always where a Java application starts. The program prints
the following text in the console window:
This is done with something called a loop, which we will come back to later. We
print "Our first program..." once and "About to learn Java!" ten times. We won't
describe in detail what causes this to happen right now, but we will mention that
the words System. out. print In handle the printing of one sentence.
How we run a program
Our little program has been saved in the file PrintText.java. The computer can't run
this directly from the Java source code. We need to translate it into a type of code
that the computer understands. This is the process referred to as compilation, even
1 Introduction
though the actual details differ a bit from language to language. The compiler is the
program that handles this translation.
It has been most common for PCs that the compiler translates from source code
into machine code. The machine code is the language the microprocessor uses. It is
practically unreadable to humans and that is certainly one of the reasons we have
programming languages like Java. Compiling into machine code can be illustrated
as in Figure 1.2. In this example, a file written in the language Pascal, with file name
HelloWorld.pas, is to be compiled.
We have indicated the machine code with the digits 0 and 1. Data made up of only
these digits is called binary data and this is how the microprocessor "thinks". But we
don't. The finished machine code is stored in the file HelloWorid.com and it can be
started by double clicking on it. Today, an exe file is more common than com, but
an exe file is not necessarily machine code.
In Java it is a slightly different story. Instead of creating a completely self-
contained file of machine code, the compiler produces byte code, stored in a class
file. This class file can't run by itself. Another program, known as the interpreter, is
required to run it. We have illustrated this in Figure 1.3.
In Figure 1.3 we have illustrated the contents of the class file with random
characters. It is not legible to us either.
The outcome of all this is that we need two programs to run a Java program we have
written: a compiler to create the class file, and an interpreter to run it. Sometimes,
the interpreter is also called a compiler, because in the process of running the
program it translates it into machine code internally. A Just-In-Time Compiler is an
interpreter. But in this book, "Java compiler" means the program that translates
from source code into byte code, unless we say otherwise.
Note that the file with the source code has the suffix .Java and the file with the byte
code (which we call the class file) always has the suffix .class. This is mandatory.
But why this middle stage in the form of the class files? The most important answer
lies in what we said earlier about architecture neutral languages. A class file can be
used on all types of computers that support Java, i.e. all types of computers for
which a Java interpreter is available. Only when the interpreter starts to run the class
file will machine-specific issues start to play a role at all. Anything pertaining to a
type of computer (say a Macintosh) is the concern of the interpreter alone. Ideally,
the class files will work everywhere. If you have a class file program and an
interpreter, you are ready to run that program. This is where the slogan "Write once,
run everywhere" comes from.
The interpreter is also refered to as JVM, Java Virtual Machine. This is an abstract,
theoretical model for a computer that will run Java and the interpreter program
implements this model.
Another attribute of the class files is their small size: they are usually significantly
smaller that the file with the source code. This makes them quicker to transmit
through a network, like applets on the Web.
In this book, we are working with the compiler and interpreter that are included
in Sun's freely distributed package Java Development Kit, or JDK. Newer JDK
releases are called SDK (Software Development Kit). Short and sweet, the Java
compiler is called javac, Java Compile, and the interpreter is called Java. The
installation and use of these programs are outlined in Appendix A. Henceforth we
assume you have installed SDK, and we will now show a brief example of typing,
compiling and running a program on a PC.
1. First, type the code in Program Listing 1.1 in your favourite text editor, for
instance WinEdit.
2. Then save the file in the directory on your hard drive you wish to store Java files
on: let's use c:\javaprograms. The file may, but is not required to, be saved as
PrintText.java, because PrintText is the name of the class containing the
method main ( ) .3
3. If you are using Notepad, you need to make sure the file wasn't named PrintText.java.txt. Notepad
insists on naming all text files .txt, which is completely wrong. You might quote the file name when
saving.
1 Introduction
3. Then you start an MS-DOS window and go to the program directory with the
following command:
c:\windows> cd c:\javaprograms
c: \ javaprograms>
4. Then compile by typing the following text. If it works out fine, you will get the
prompt back and it will look as if nothing happened.
c:\j avaprograms> javac PrintText.Java
c:\javaprograms>
If, on the other hand, you get an error message, you have to recheck the source
code for typos. Another common mistake is to spell the name of the file wrong.
5. If you didn't get any errors, you can start the program this way and look at its
output:
c:\javaprograms> java PrintText
Our first program...
About to learn Java!
About to learn Java!
About to learn Java!
About to learn Java!
About to learn Java!
About to learn Java!
About to learn Java!
About to learn Java!
About to learn Java!
About to learn Java!
c : \javaprograms>
Notice that it is incorrect to type
c : \javaprograms> Java PrintText. class (Mistake!)
even though it is the class file that is to be started.
The example showed a rather optimistic course of events. It is far more common
to get some sort of error message from the compiler, indicating a mistake in the
source code. After some corrections and new mistakes in the source code, you will
eventually get it right, but errors may also arise during the execution of the
program. This is all in a day's work for a computer programmer, and you have to
get used to a certain amount of hassle getting things to work. Fortunately, there are
techniques and tools to simplify things as much as possible.
Other tools for working with Java
We use SDK from Sun. This is the most official development tool for Java. We have
seen that it consists of simple programs which we basically need to start by hand by
giving textual commands. Many people prefer to work in this way, but many others
1.7 Examples of Applets
will prefer menus and buttons for compiling and running. Luckily there are
products that provide this.
With text editing tools like WinEdit, we can compile and run programs from
menus, in addition to editing text. These menu choices automatically run javac and
Java for us, making WinEdit into a sort of shell around the SDK. Every now and
then, problems arise in the communication between the editing tool and SDK, for
instance with particular types of Java programs. It will then be very useful to go to
a console window (like the MS-DOS prompt) and do the compiling by hand. So we
recommend learning to use the SDK from the console as an auxiliary solution.
Another category are tools specializing in keeping track of the programmer's
files graphically, creating graphical user interfaces with powerful tools, and of
course compiling and running. Examples of such products are Borland JBuilder
and IBM VisualAge. In our opinion it is still always useful to know how to use the
console tools. That gives the programmer full control over the development
process and all the associated file types.
In the tool Microsoft Visual J++, changes to the language itself have been added,
but not in conformance with Sun's official Java standards. This has been very
controversial and we will not cover these extensions in this book.
The address reveals that it is an HTML document. Applets must lie within HTML
files, or to be precise, the reference to the applet's class file must lie within a HTML
file. So where there is an applet, there is always an accompanying HTML document.
When you load this address, you will get a small document, and the applet runs
inside a rectangular area on the page. This applet is very simple: it only prints a text
with a circle around it. Figure 1.4 shows a piece of the browser, where the applet is
running.
So what is so interesting here? The text and the circle you see are created by the
little applet running in your browser. It is not a part of the static document you
fetched from www.tisip.no. This is the reason why you probably need to wait a while
for something to happen with the applet, compared to the rest of the document. A
small program has to run. In this example, there is certainly no need for an applet.
We could have included the text and the circle in the HTML document, because it
is static. But the applet could have moved and received input from you, the user
Our second example does just that: [URL Color Applet]. Here you are presented
with the option of choosing the applet's background color from a menu. It is in fact
a tiny graphical user interface. This applet is active: it communicates with you by
itself, after being completely downloaded from the Web server. Figure 1.5 shows
how this might look in your browser, although we cannot show the colors.
The applet in Figure 1.5 could not have been made in HTML, as it is not static. Small
and graphical, it could have been written in JavaScript, but that would have given
us serious limitations if we wanted to expand its functionality, and speed decreases
significantly as the size of the little "system" increases.
1.8 New Concepts in This Chapter
• Your browser does not support Java applets. This means that the browser
program hasn't been provided with this functionality. Netscape 4.0 and Internet
Explorer 3.0 and newer should support certain versions of Java. Your solution is
to download a newer browser.
• Your browser has the Java applet functionality disabled. In your configuration
menu (Options, Preferences or the like) you may switch off running applets
encountered on the Web. The solution to this problem is obvious: enable applet
support in the browser.
• Your browser does not support applets written in the version of Java this applet
is written in. This usually implies that you are using an older browser. Published
applets tend to be written in the newest version of Java commonly supported at
that time. The solution is to get a newer browser and perhaps an additional
module for Java support.
You may run across other problems, but these three are very common.
API Application Programming Interface. A standard program library that comes with the
Java software. See also chapter 8.
applet A Java program that's executed inside a Web browser. It is part of a Web document.
application A standalone program meant to run by itself, not needing a browser, for example.
architecture neutral A key element in Java. Nothing in the language ties a program to a particular type
of computer.
ASCII American Standard Code for Information Interchange. A commonly used character
set. See also text file.
browser A program for viewing pages ("surfing") on the Web. Examples: Internet Explorer and
Netscape Navigator.
1 Introduction
client A program or a computer that asks for services from a server, usually over a network.
compiler A program that accepts source code as input and produces, for example, machine code
or byte code.
compiling The process of translating source code into machine code or byte code.
directory The files on a computer are arranged in directories. The directories are organized like a
tree, with directories under others.
distributed system Consists of several programs running on several computers and communicating with
each other.
file An amount of information that serves a purpose to the computer. Often stored on a
hard disk.
HTML Hypertext Markup Language. The formatting language for Web documents.
interactive A situation where a continuous dialogue takes place between human and computer.
JVM Java Virtual Machine. The theoretical model for a computer, which the Java interpreter
realizes.
method A named part of the source code which we use whenever needed. See also chapters 3
and 4.
object orientation (OO) A way to design computer programs. An example of a principle is: Everything that has
to do with a certain thing in the program is gathered in a certain module. An object
oriented language is a language in which this principle is a key point
operating system (OS) The program that administers the hardware so that the user can use it easily. Also
keeps track of the different programs running on the computer. The most widely used
operating systems today are Windows 98 and NT.
process A more general term for a program running on a computer. We often start several
processes when we start a program by double-clicking on it. See also chapter 16.
programming language A set of rules for instructions to a computer. A programming language is a whole lot
more exactly defined than German, for example.
The text which constitutes a program. The source code is to be found on one or more
text files.
text file File containing only plain text. The standard for plain text in Europe is ISO 8859-1, or
latin-1. 8 bits per character are used. The Unicode character system, which lava uses, is
larger, with 16 bits per character. The characters in ISO 8859-1 match Unicode. ASCII
is an older character set with regional variants. The standard part of ASCII is part of
ISO 8859-1.
Unicode A newer and larger character system than ASCII. See also text file.
UNIX Common name for a large class of operating systems. It is widely used for large,
heavy applications.
URL Uniform Resource Locator. An address on the Web, like http://www.tisip.no/ eller/tp://
ftp.gnu.org/.
user interface The part of a program visible to the user. The user interface may be graphical. In that
case, the user will use buttons and windows. If it's textual, the user communicates
with the computer using written commands.
Web (WWW, World A service on the Internet where different documents are presented. They usually
Wide Web) contain links to other documents, that can be navigated between using a mouse.
Windows Explorer The program in Windows that we use to explore disks, diskettes and more. It allows us
to move and copy files, etc.
• Assignment, casting
• Write programs that perform mathematical calculations and print the results to
the console
This chapter will cover a number of fundamental language elements in Java. There
are equivalent language elements in just about every programming language.
We'll start by introducing an example that we will work with as we proceed
through the book, a program that calculates what it will cost to fix up a
condominium.
In order for the computer to be able to perform these calculations, it needs quite
a bit of information about the condominium. We will look at how to input this
information into a program. We will also look at how to write the program so that
it does the calculations for us and displays the results on the screen.
2 Variables, Data Types, and Expressions
2.1 Example
You just bought an old condominium that you're going to renovate. You've
decided that the bathroom, kitchen, and the electrical installations are fine.
However, you want to replace the flooring in a couple of the rooms and paint and
wallpaper some of them.
You need to perform a number of calculations:
• How many square meters of parquet flooring, or other flooring, will you need
for a floor?
• What will the renovation cost for each individual wall, each individual room,
and the entire renovation project?
We will work quite a bit with this example over the course of this book. We'll
start with a very simple program that calculates the area of a wall, and we'll end up
with a program with a graphical user interface that will be a useful tool in planning
a renovation (see Figure 15.8). Between these two extremes, we will write smaller
programs that can be used to calculate, for example, how many rolls of wallpaper
we need to cover a wall.
This book is about object-oriented programming. That means that we always
start by finding the objects that are going to be modeled. These can be walls, floors,
wallpaper, etc. The purpose of the program will be to perform certain tasks using
these objects—for example, estimating the number of liters of paint we will need for
a wall.
In this chapter, we'll look at how to solve minor, individual problems without
thinking so much about the objects.
2. What data needs to be input in order for the program to be able to calculate these
results? This is data that the program's user will use the keyboard to input. The
program reads this data. We call it input data.
Answer: The formula for the area of a rectangle is the length times the height.
Thus the input data is the length and height, measured in meters.
3. What happens between the data being input and the results printing out?
Answer: The program calculates the area based on the formula provided.
The program that solves this little problem will communicate with the user via
the screen and keyboard. When we put this into a larger context, we will be able to
say instead that the surface object performs services for a so-called client object,
which in turn communicates with a user interface object. In an object-oriented
program we will have to ask ourselves these three questions for every single object:
What do we expect the object to tell us, and what does it need to know about itself
to be able to tell us this? What formulas and problem-solving methods does the
object need to know? These questions show that an object in a program has very
different characteristics from an object in reality. More about this in chapter 3.
The following sketch of a textual user interface in the console window is
sufficient for our simple problem:
What the user types is indicated in italic. The user can calculate the area of
several walls by running the program several times.
Actually, it's very difficult to do something as basic as inputting two numbers
into Java. Therefore we start by inputting the length and height directly into the
program (see Program Listing 2.1). Now the user interface is even simpler than
shown above. Only the result prints out. Look at the end of the program listing.
You'll find "Example Run". By enclosing this in / * and */, the compiler regards this
as a comment. Most of the program listings in this book that contain complete
programs with a textual user interface show example program runs at the end.
If the user wants to calculate the area of several walls, she has to open the
program in an editor and edit the length and height each time. Then she has to
compile and run it again.
class WallCalculations {
public static void main(String args) {
double length = 5.0;
double height = 2.3;
double area = length * height;
System.out.println("The area of the wall is " + area + " square meters.');
/* Example Run:
The area of the wall is 11.5 square meters.
V
Get the program from [URL Java book], compile it, and run it.
The lines of code are performed in the order they are listed. This is called
sequential execution.
We remember from section 1.6 that the program does what is in the main ( )
method. The program sets aside room for data in the computer's internal memory.
For example:
double length = 5.0;
Storage spaces like this are called variables. Each variable can contain only one data
value. The program fills the variables with reasonable contents immediately after
they're formed. Here, the variable length receives the value 5.0.
All the variables in the program are outlined in Figure 2.1.
Once length and height are created and have each received their values, the
area is calculated. The result of the multiplication is placed in the variable named
area:
double area = length * height;
Finally, the results of the calculations are printed:
System.out.println(The area of the wall is " + area + " square meters.");
We're familiar with Systern. out .print In () from chapter 1. Inside the
parentheses we indicate what will be printed on the screen. If we are going to print
out several things, we use + to link them together. Text that is going to be printed
exactly as it is is placed in double quotes. Text without double quotes can be the
name of a variable, such as area. That means that the program will get the
contents of the variable and print that on the screen. In this example, the printout
looks like this:
Figure 2.1 The variables in the program that calculate the area of a wall
2.2 Data and Variables
/* Example Run:
Length: 5.8 m
Height: 2.4 m
The area of the wall is 13.92 square meters.
V
2 Variables, Data Types, and Expressions
• By using /* and */. All text between /* and */ is ignored by the compiler.
There can easily be several lines of text between / * and * /.
smaller, and there's rarely a need for algorithms on multiple levels. An algorithm's
rules are "ordered" by definition. That means that they have to be carried out in a
specific order. Usage instructions and cake recipes are familiar examples of
algorithms. The program in the previous example builds on the following
algorithm:
1. Read the length and height.
2. Calculate the area using the stated formula.
3. Output the area.
We say that a program that goes through the compiler without error messages
has no syntax errors. The program's syntax is correct. That means that we have
combined words and punctuation in the program in such a way that the compiler
can translate it to a series of byte code instructions.
Errors can arise when you run the program. There may be errors that stop the
program from running, or it may be that the program doesn't solve the problem
that it was intended to solve. The reason for this might be that the algorithm is
programmed wrong, or that the algorithm is wrong. Errors of this type are called
logical errors (the expression semantic errors is also used, "semantic" meaning "of or
relating to meaning"). The compiler doesn't help us find logical errors. We can find
logical errors by running a carefully thought-out set of test data through the
program.
A test data set is a set of input and output data values whose purpose is to detect
logical errors in the program. Test data of course has to be realistic data, but it's also
important to choose data that will test the program's outer limits. A program for
organizing books in a library has to work for zero books and for 200,000 books (or
whatever the upper limit is). In this case, realistic data will be somewhere between
these two outer limits.
We set up the test data for our program as shown in Table 2.1.
Table 2.1 Test data set for a program that calculates the area of a wall
Data Set No. Length Height Expected
Results
1 0.0 0.0 0.0 no wall
2 100 10 1000 a large wall
3 2.3 4.5 10.35 a "normal"
wall
-2.5 3 error message
2 Variables, Data Types, and Expressions
If we run the program with data set number 4, it will calculate that the area is -7.5.
We don't get any message that negative length is meaningless. That's because the
program doesn't check that the input data is correct before the calculations are
performed. Program Listing 2.3 demonstrates how we can do this. We use the
language elements if and else: if a condition is satisfied (here: both height and
length are greater than zero), then we will calculate the area; if not, then we will send
a message to the user. This is covered thoroughly in chapter 5. Until then, we'll get
by without checking the input data.
We've seen the need for test data. There are also other ways to find logical errors
in a program. Inspections are used a great deal. Briefly, this is when other people
formally go through the code. The benefit to this, over testing, is that this type of
debugging can take place early on in the development process. The earlier an error
is detected, the cheaper it will be to fix.
/* Example Run:
The length and/or the height has a non-positive value.
V
Problem
Test the program above with the test data set in table 2.1.
III
LA PLANÈTE HOMICIDE
IV
DANS LA TERRE PROFONDE
C’était après le crépuscule. Les constellations avivaient leurs
flammes fines. L’oasis, taciturne, cachait sa détresse et ses douleurs.
Et Targ promenait une âme fiévreuse près de l’enceinte.
L’heure était affreuse pour les Derniers Hommes.
Successivement, les planétaires avaient annoncé d’immenses
désastres. La Dévastation était détruite; aux Deux-Équatoriales, à la
Grande-Combe, aux Sables-Bleus, les eaux avaient disparu; elles
décroissaient aux Hautes-Sources; l’Oasis-Claire et le Val-de-Soufre
annonçaient ou des secousses ruineuses ou des fuites rapides du
liquide.
L’Humanité entière subissait le désastre.
La lune fut claire; elle étalait son disque de nacre et d’argent sur
les collines occidentales. Hypnotisé, Targ se dirigeait vers elle. Il vint
dans un terroir de roches. La trace du désastre y restait; plusieurs
s’étaient renversées, d’autres fendues; partout, la terre siliceuse
montrait des crevasses.
—On dirait, murmurait le jeune homme, que la secousse a atteint
ici sa plus grande violence... Pourquoi?
Son rêve s’éloignait un peu, l’ambiance excitait sa curiosité.
—Pourquoi? se redemanda-t-il... Oui, pourquoi?
Il s’arrêtait à chaque moment pour considérer les rocs et aussi
par prudence; ce sol convulsé devait être plein de pièges. Une
exaltation étrange le saisit. Il songea que, si une route existait vers
l’Eau, il y avait bien des chances pour qu’elle se décelât dans cet
endroit si profondément remanié. Ayant allumé la «radiatrice» qu’il
ne quittait jamais en voyage, il s’engagea dans des fissures ou des
corridors: tous se rétrécissaient rapidement ou se terminaient en cul-
de-sac.
V
AU FOND DES ABIMES
VI
LES FERROMAGNÉTAUX
VII
L’EAU, MÈRE DE LA VIE
VIII
ET SEULES SURVIVENT LES TERRES-ROUGES
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookultra.com