100% found this document useful (3 votes)
28 views

Download Complete Java the UML way integrating object oriented design and programming Else Lervik PDF for All Chapters

The document provides information about the book 'Java the UML Way: Integrating Object-Oriented Design and Programming' by Else Lervik and Vegard B. Havdal, including details on its content, structure, and download links. It also lists several other related ebooks available for download on ebookultra.com. The book covers various topics in Java programming and object-oriented design.

Uploaded by

alysekhale49
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
28 views

Download Complete Java the UML way integrating object oriented design and programming Else Lervik PDF for All Chapters

The document provides information about the book 'Java the UML Way: Integrating Object-Oriented Design and Programming' by Else Lervik and Vegard B. Havdal, including details on its content, structure, and download links. It also lists several other related ebooks available for download on ebookultra.com. The book covers various topics in Java programming and object-oriented design.

Uploaded by

alysekhale49
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Visit https://ebookultra.

com to download the full version and


explore more ebooks

Java the UML way integrating object oriented


design and programming Else Lervik

_____ Click the link below to download _____


https://ebookultra.com/download/java-the-uml-way-
integrating-object-oriented-design-and-programming-
else-lervik/

Explore and download more ebooks at ebookultra.com


Here are some suggested products you might be interested in.
Click the link to download

Object Oriented Design with UML and Java 1st Edition


Kenneth Barclay

https://ebookultra.com/download/object-oriented-design-with-uml-and-
java-1st-edition-kenneth-barclay/

Object Oriented Software Engineering Using UML Patterns


and Java 2nd Edition Bernd Bruegge

https://ebookultra.com/download/object-oriented-software-engineering-
using-uml-patterns-and-java-2nd-edition-bernd-bruegge/

Applying UML and Patterns An Introduction To Object


Oriented Programming 2Ed Edition Larmen

https://ebookultra.com/download/applying-uml-and-patterns-an-
introduction-to-object-oriented-programming-2ed-edition-larmen/

Scientific Software Design The Object Oriented Way 1st


Edition Damian Rouson

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/

Introduction to Programming with Greenfoot Object Oriented


Programming in Java with Games and Simulations 1st Edition
Michael Kolling
https://ebookultra.com/download/introduction-to-programming-with-
greenfoot-object-oriented-programming-in-java-with-games-and-
simulations-1st-edition-michael-kolling/

Beginning C Object Oriented Programming 2nd Edition Dan


Clark

https://ebookultra.com/download/beginning-c-object-oriented-
programming-2nd-edition-dan-clark/

Object Oriented Programming in C 4th Edition E.


Balagurusamy

https://ebookultra.com/download/object-oriented-programming-in-c-4th-
edition-e-balagurusamy/

Object oriented software development using Java principles


patterns and frameworks 2nd Edition Xiaoping Jia.

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

Else Lervik and Vegard B. Havdal


S0r Trondelag University College, Trondheim, Norway

Translated and sponsored by tisip

JOHN WILEY & SONS, LTD


V: tlSlD
'
First published in the Norwegian language as Programmering i Java, © 2000 Else Lervik and Vegard B. Havdal,
The TISIP Foundation, and Gyldendal Akademisk

English language edition


Copyright © 2002 by John Wiley & Sons Ltd,
Baffins Lane, Chichester,
West Sussex PO 19 1UD, England

National 01243 779777


International (+44) 1243 779777
e-mail (for orders and customer service enquiries): [email protected]
Visit our Home Pag on http://www.wileyeurope.com

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.

Library of Congress Cataloguing in Publishing Data (applied for)

British Library Cataloguing in Publication Data

A catalogue record for this book is available from the British Library

ISBN 0 470 84386 1

Typeset by Cybertechnics Ltd, Sheffield


Printed and bound in Great Britain by Biddies Ltd, Guildford and King's Lynn
This book is printed on acid-free paper responsibly manufactured from sustainable forestry,
in which at least two trees are planted for each one used for paper production.
Contents
Preface xi

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

4.4 Contents of a Class 92


4.5 One More Class and Some New Operators 101
4.6 Introduction to Applets 106
4.7 Introduction to Graphics 111
4.8 New Concepts in This Chapter 118
4.9 Review Problems 120
4.10 Programming Problems 121
Selection as a Control Structure 123
5.1 A Simple Calculator 124
5.2 A Selection is a Control Structure 126
5.3 Blocks inside Methods 131
5.4 The if Statement 133
5.5 Nested if and Multiple-Choice Statements 137
5.6 Boolean Expressions 144
5.7 The Multiple-Choice Statement switch 150
5.8 Comparing Computed Decimal Numerals 153
5.9 The Conditional Operator ?: 153
5.10 New Concepts in This Chapter 154
5.11 Review Problems 155
5.12 Programming Problems 156
Loops as a Control Structure 159
6. 1 Counter-Controlled Loops 160
6.2 A Loop with a General Condition 163
6.3 A Graphics Example 166
6.4 The for Statement 168
6.5 Nested Control Structures 169
6.6 The do-while Statement 171
6.7 Choosing the Right Loop Statement 173
6.8 Controlling Input Data 174
6.9 New Concepts in This Chapter 177
6.10 Review Problems 178
6.11 Programming Problems 178

Collaboration Between Objects 181


7. 1 Examples of Collaboration Between Objects 182
7.2 A Menu-Driven Program 190
7.3 Several References to the Same Object 197
7.4 Summary: Argument Passing 202
7.5 New Concepts in This Chapter 205
7.6 Review Problems 205
7.7 Programming Problems 205

8 Java Libraries and Exception Handling 207


8. 1 The Online API Documentation 208
8.2 Making Your Own Libraries 211
8.3 Localization 214
8.4 Sound and Images 218
Contents

8.5 Introduction to Exception Handling 220


8.6 Exception Handling in Detail 226
8.7 New Concepts in This Chapter 236
8.8 Review Problems 236
8.9 Programming Problems 237
9 Arrays of Primitive Data Types 239
9.1 What is an Array? 240
9.2 Copying Arrays 244
9.3 The Month Class for Precipitation Data 247
9.4 Sorting 251
9.5 Searching 255
9.6 The java.util.Arrays Class 256
9.7 Two-Dimensional Arrays 258
9.8 More Than Two Dimensions 265
9.9 Multidimensional Arrays and Object-Oriented Programming 266
9.10 New Concepts in This Chapter 267
9.11 Review Problems 268
9.12 Programming Problems 268
10 Arrays of Reference Types and Array Lists 271
10.1 An Array of Reference Type 272
10.2 Array Lists 275
10.3 Wrapper Classes - Integer, Double, etc. 278
10.4 The Methods - equals() and toStringQ 281
10.5 Associations 283
10.6 A Bigger Example 285
10.7 The Comparable and Comparator Interfaces 296
10.8 Sorting Arrays and Array Lists 298
10.9 New Concepts in This Chapter 304
10.10 Review Problems 305
10.11 Programming Problems 305
11 Using Data Files and Streams 307
11.1 Data Files and Streams 308
11.2 An Example of a Data File 309
11.3 Reading Text from a File 311
11.4 Writing Text to a File 315
11.5 Data Files: Summary and Class Descriptions 316
11.6 Reading Numbers from a Data File 320
11.7 Communication with the Console 323
11.8 Binary Transfer of Data 323
11.9 Random Access to the Contents of a File 325
11.10 Serialization 329
11.11 New Concepts in This Chapter 335
11.12 Review Problems 355
11.13 Programming Problems 336
Contents

12 Inheritance and Polymorphism 339


12.1 Generalization and Specialization 340
12.2 Inheritance 342
12.3 The Material Class with Subclasses 345
12.4 Handling Instances of Subclasses as a Whole 351
12.5 The Renovation Case with Many Surfaces and Many Materials 354
12.6 What if Polymorphism Didn' t Exist? 357
12.7 The Protected Access Modifier 360
12.8 Two Levels of Inheritance 364
12.9 Rules and Syntax 369
12.10 Interface 372
12.11 New Concepts in This Chapter 376
12.12 Review Problems 377
12.13 Programming Problems 378

13 GUI Programming and Events 383


13.1 GUI Components 384
13.2 Pushing a Button 388
13.3 Inner Classes 395
13.4 Managing the Layout 402
13.5 New Concepts in This Chapter 412
13.6 Review Problems 413
13.7 Programming Problems 413

14 Text, Choices, and Windows 415


14. 1 Text Components and Focus Listeners 416
14.2 Giving the User a Choice Between Alternatives 423
14.3 Choices Using Check Boxes 425
14.4 Choices Using Radio Buttons 428
14.5 Choices Using Lists 431
14.6 Windows 439
14.7 Making a Window 441
14.8 Differences Between Applets and Applications 446
14.9 Other Ways to Program Listeners 448
14. 10 New Concepts in This Chapter 450
14.11 Review Problems 451
14.12 Programming Problems 451

15 Creating User Interfaces 453


15.1 Menus 453
15.2 Toolbars 458
15.3 Dialog Windows 461
15.4 GridBagLayout as Layout Manager 476
15.5 The Table GUI Component (the JTable Class) 481
15.6 GUI for the Renovation Project 484
15.7 New Concepts in This Chapter 495
15.8 Review Problems 495
15.9 Programming Problems 496
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

17 Data Structures and Algorithms 523


17.1 Graphs 524
17.2 Lists 526
17.3 The Solution: Collection, List, and Linked List 534
17.4 Queues and Stacks 538
17.5 Recursion 540
17.6 Trees 542
17.7 Trees in the API 550
17.8 Hashtables 553
17.9 New Concepts in This Chapter 558
17.10 Review Problems 559
17.11 Programming Problems 559

18 More about Applets 561


18.1 What Applets Do on the Web 561
18.2 Security 562
18.3 Programming an Applet 565
18.4 Security in Practice 570
18.5 Communication Between Applet and Browser 572
18.6 New Concepts in This Chapter 575
18.7 Review Problems 576
18.8 Programming Problems 576

19 Distributed Systems with Socket Programming and RMI 579


19.1 Sockets 580
19.2 Objects That Collaborate over a Network 586
19.3 How Does Communication Between the Objects Occur? 594
19.4 RMI and Applets 600
19.5 Deployment Diagram 600
19.6 A Distributed System with Callback 603
19.7 New Concepts in This Chapter 614
19.8 Review Problems 615
19.9 Programming Problems 615
Contents

20 Programming with Databases 619


20.1 Database Drivers 620
20.2 Establishing Contact with a Database 621
20.3 A Bigger Example 628
20.4 A Database Application 634
20.5 The Three-Layer Architecture 640
20.6 Transactions and Compiled SQL Statements 641
20.7 New Concepts in This Chapter 645
20.8 Review Problems 645
20.9 Programming Problems 646

21 Web Programming with JavaServer Pages 649


21.1 Different Ways of Programming for the Web 650
21.2 Installing Software 651
21.3 Servlets 652
21.4 JavaServer Pages (JSP) 657
21.5 What Does JSP Consist of? 658
21.6 Inputting Data from the User 662
21.7 Client-Side Validation with JavaScript 671
21.8 Databases 672
21.9 Storing State Information 680
21.10 New Concepts in This Chapter 695
21.11 Review Problems 696
21.12 Programming Problems 697

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

Object-oriented thinking and modeling go hand in hand with programming


throughout this whole book. Nevertheless, for beginners to be able to run Java
programs, their first read-through of the book will probably focus on programming
details. Later perusals will contribute more to readers lifting their gazes up beyond
the details of the code.
Using ready-made classes is part of developing the ability to think abstractly and
understand encapsulation. We've chosen to make do with this in the first half of
the book. We consider event handling, which is required to write programs with
"real" graphical user interfaces, to be so complicated that the time for it comes only
after most of the pieces of the Java language and object-orientation in general are
in place. If it is included too early on, we believe that the degree of "mystery"
behind it remains too high.

This book is not just for beginners


Because of an early, and therefore very thorough focus on object-orientation, we
believe that this book is suited to professional programmers with backgrounds in
non-object-oriented solution methods and programming languages. These readers
will be able to sail through many of the programming details in the earlier chapters
and concentrate instead on the object-orientation aspect, as illustrated with simple
code examples.
Readers with backgrounds from another object-oriented programming
language, C++ for example, will recognize quite a bit in the first part of the book.
They should, however, peruse this material quickly, primarily because there are a
number of essential differences between Java and C++, but also because the
conceptual apparatus differs somewhat between the two languages. Examples of
where Java differs from C++: in Java, arrays are objects with built-in knowledge of
their own length, exceptions are thrown if you try to refer to an array element with
an invalid index, space has to be allocated for all objects using the new operator
(you cannot put objects on the stack), objects that no longer have references are
removed automatically, it's not possible to program true multiple inheritance,
there's no operator-overloading, it's not possible to manipulate pointers, etc.
Java's rich Application Programming Interface (API) will be of particular interest
to readers with backgrounds in other languages. The Swing library makes it
possible to create platform-independent graphical user interfaces. The classes for
managing strings and arrays of dynamic length are easy to use. Familiar data
structures such as linked lists, trees, and hashtables are built in as part of the Java
API. Remote Method Invocation (RMI) makes it easy to create distributed systems
in the form of objects that cooperate over the network. Java Database Connectivity
(JDBC) is a collection of classes that can communicate via database drivers with
just about any database system. JavaServer Pages (JSP) is a technique for
programming dynamic Web pages. The programs run on the web server and
generate customized Web pages.
Unified Modeling Language (UML) as a modeling language
One of the most welcome events in recentyears in the field of object-oriented analysis
and design was when three gentlemen, Booch, Jacobson, and Rumbaugh, joined
forces and created a single common modeling language, Unified Modeling Language
(UML). This language is a standard accepted by the Object Management Group
(OMG), and we will gradually introduce elements of the language as we proceed.
We start with a class diagram that illustrates a single class in chapter 3, and gradually
add more classes using associations and generalizations. We use an activity diagram
to illustrate control structures, threads, and other parallel processes. Sequence
diagrams are very convenient for showing how objects send messages to each other.
In the last few chapters of the book, we use deployment diagrams to show how the
different parts of a distributed system depend on each other and run on physically
different machines.

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/.

Resource page on the Internet


This book has its own Internet page, http://www.tisip.no/JavaTheUmlWay/, where
you'll find all the examples, as well as answers to all the shorter problems and
many of the programming problems. The page also includes a number of relevant
links.

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

The book's structure


The basics
The first nine chapters provide the requisite foundation in programming.
The first chapter introduces the topics of programming and Java and lays out the
prerequisites we're assuming the readers have. This chapter also covers the various
typographical elements used in the book.
Chapter 2 provides a necessary introduction into the topics of variables, data
types, and expressions. Chapters 3 and 4 focus on object-orientation and the goal
of the chapters is for the readers to learn to use ready-made classes and to make
their own classes. Readers will become familiar with important object-oriented
concepts like servers, clients, attributes, messages, and operations. They will
understand that there's a difference between objects in reality and objects in
programs. Readers will create their own first applets with simple geometrical figures
in chapter 4.
Chapters 5 and 6 cover the control structures of selection and loops.
Object-orientation is again the focus in chapter 7, where we'll look at message
exchanges between objects. This requires a thorough understanding of how
arguments are passed between objects, and we'll go through a number of
programming details, some of them difficult.
We now believe the reader is ready to use the online documentation that comes
with the SDK. Chapter 8 offers a brief introduction to this. Using the ready-made
classes that come with the SDK requires familiarity with exception handling in Java.
Therefore, this is also covered in chapter 8.
Chapter 9 covers arrays of primitive data types. Simple sorting and searching are
discussed. The chapter also covers the use of ready-made methods for this purpose.

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.

Introduction to advanced topics


Chapter 16 covers thread programming. Threads make it possible to multitask
internally within a single program. The Java interpreter makes extensive internal
use of threads—for example, in conjunction with graphical user interfaces.
Chapter 17 shows how the Java API can be used to create and handle the
traditional data structures—linked lists, queues, stacks, trees, and hashtables.
Recursion is also covered in this context.
Chapter 18 covers applets in a larger context. We look at the purpose for applets
and security in connection with them. The chapter also goes through
communication between applets and the browser.
Chapter 19 deals with programming distributed systems. There's a brief
introduction to socket programming, but the primary topic of the chapter is RMI.
We will create relatively complex distributed systems with callbacks.
The topic of chapter 20 is programming with databases. The chapter shows how
to use JDBC to get a Java program to communicate with a relational database using
SQL statements.
Chapter 21 is an introduction to server programming for the Internet. We'll see
how to use JSP to create systems for the Internet where users see customized Web
pages and where communication with databases is central.
We would like to thank...
Many people have made the work on this book possible: first and foremost, TISIP,
whose economic support has made it possible to carry out this project. We'd also
like to thank the Norwegian Technical Literary Fund [Det Faglitteraere Fond] for its
financial support.
A number of people have contributed opinions, ideas, and materials for the
book. We would especially like to express our gratitude to the following: Assistent
Professor Mildrid Ljosland and Associate Professor Tore Berg Hansen read carefully
through the entire manuscript and contributed extremely useful technical
Preface

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

Learning goals for this chapter


After reading this chapter, you should understand:

• The relationship between Java and the Internet

• The concept of a computer program

• The basics of compilation

After reading this chapter you should be able to:

• 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.

1.1 Preliminaries for Reading This Book


Everyone starts their computing career as the user of one or more available
program(s). The term end user is also common. For instance, you might be using a
word processing program to write letters or school reports, or an invoicing program
at the store where you work. In addition, you are also a user of the computer's
operating system. The operating system keeps track of the programs we are
running, and lets us use hard disks, floppy drives and the rest of the hardware.
In this book, you will learn how such programs are created. What is taken for
granted is that you have been using a PC for a while. You should be familiar with
the terms file, directory and sub-directory. This means that when you are clicking
your way through the Windows Explorer, you know that you're dealing with a
structure of files in directories on a hard disk.
Programs in Windows are files with the suffix exe. If you double-click on one of
these files, you start that program. We call them program files. If you double-click a
doc file, the program Word will usually start. Try these things in Explorer yourself,
if you wish.2 It is important to note that this does not mean that the doc file is a
program. It is just how Windows keeps track of the fact that these files are meant
for the program Word, which must be started first. A doc file is data for the program
Word.
There is also an important distinction between text-based and graphical
programs. The vast majority of Windows programs have a graphical user interface.
The user interface is how we communicate with the computer. This might be done
using written commands entered on the keyboard, or we may point and click on
menus and buttons using a mouse. Occasionally in Windows we use the former, a
textual user interface. Then the textual dialogue takes place at the MS-DOS prompt,
or the console as we call it in this book. In Windows NT there is no MS DOS. There
it is called a command prompt. It is nevertheless depicted with an MS DOS symbol,
because MS DOS programs can be run. In the MS DOS console we navigate through
the directories with the command cd, change directory. When we feel like it, we can
run a program that is located in our current directory by typing its name. Some
people are familiar with using a computer this way, whereas many are not. Because

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.

1.2 Contemplating a Computer


It's no easy task to describe the workings of a computer to a beginner. When you
click on Windows Explorer there are several things taking place between you and
the chip on the motherboard inside the computer, the microprocessor. Dividing
the computer system into layers, see Figure 1.1, can help us see the bigger picture
here. Each layer is one or more running program (processes is more widely used in
this context), which makes up part of the operating system.
You start in the center, where there's a small program known as the kernel. This
program uses a small number of commands to perform operations in the hardware
of the computer. This is where it all starts.
Outside the kernel is the next layer, for instance the MS DOS text-based console.
Here the user can work with the computer using a number of textual commands
and run different programs. For each thing the user does in the console, several
operations will be executed in the kernel.
Outside the textual console interface, we usually find a graphical user interface.
This is familiar to most; using a mouse or another mechanical device we operate
the computer by pointing and clicking to start programs, move files, etc.
In Figure 1.1, we put a computer in the center to symbolize computer hardware
like disk drives, memory, screen and keyboard. The operating system kernel hides
this hardware so that the outside layers don't have to know details about the
hardware covered by the kernel. Outside the kernel, we can see a textual console
1 Introduction

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.

Graphical widows System

Figure 1.1 Layers in a computer system


How well defined the boundaries between layers are, varies from system to system,
system being for instance Macintosh, Windows, Linux, In some systems you can
use different combinations of the various layers depending on your needs. For
instance, you might choose the graphical window system you like best. In other
systems you are tied to one window system because the layers are not dearly
separated.
For the person who is about to program these computers, this division into
layers is a great advantage: we only need to deal with the level we are working on.
It's possible that we are working on the graphical window system directly. In that
case, programming consists of specifying when and where to open a window with
the buttons OK and Cancel, and some text or specifying a pull-down menu with
some selections. Microsoft Visual Basic is an example of a tool for this type of
programming. On the other hand, we might program with the textual console
interface as the base. Communication with the program will be through textual
messages, but it is also common to create graphical user interfaces in this type of
programming. It is just that in that case, it doesn't all begin with the graphics. This
is how we set out to write Java programs in this book. We start by using text for the
user interface, then move on to writing graphical user interfaces when we consider
it necessary.
1.3 Java Applications and Java Applets

The goal of a programming language is for a programmer to describe the


solution to a problem to the computer, solutions which are helpful for a number
of users who will use the program or refine it further. It's the computer's job to
execute this solution. The problems we're discussing are usually the kind that are
too difficult or time consuming for human beings to solve. That's about all there is
to say about programming languages in general, because the ways these problems
are solved are incredibly diverse. There are numerous traditions and styles of
programming in terms of how the programmer works, how the programs are
written and how the user utilizes them. In lava, a technique called object
orientation or OO is the key issue. Among other things, this is a means of
organizing the computer program that is going to solve a given problem. We solve
a problem by creating a model of objects that exist in the real world. This method
is commonly linked to Java's relative in the world of computer languages, C++, but
other languages, like Smalltalk, are also based on OO. The invention of this
technique is commonly attributed to two Norwegians, Kristen Nygaard and Ole-
Johan Dahl. They designed the first object oriented language, SIMULA, at the
Norwegian Computing Centre in the mid-1960s.

1.3 Java Applications and Java Applets


As mentioned earlier, the language Java has received a good deal of publicity
because of its connection to the Web and the Internet. There are two main
important types of Java programs in use today: standalone Java programs, or appli-
cations, and Java applets. (We might also consider servlets as a third type.) Applets are
what we see on the Web and they're what made Java unique at the time of its birth.
Most computer users are familiar with browsing the Web using Netscape,
Internet Explorer or some other browser. We know that we come across pages with
text and pictures, all of them placed on a Web server for us to fetch and view. The
browser, or maybe the machine we run the browser on, is an example of a client.
There are lots of clients all over the place fetching information from a single server.
One would expect the server to be big and the clients small. That is often the case.
The computer running the server is a powerful machine, while the client machine
is a common desktop computer. The programs running on the server and client
machines are related the other way around; a Web browser is a much more
complicated program than a Web server.
The pages we find on the Web have been formatted in the language HTML
(Hypertext Markup Language), which will give us header texts with different
appearances and links to other documents. In addition, we see pictures and tables.
Every now and then we run across a sound clip or maybe a small movie and then
we might need an extra program module in our browser. Common to all these
things we fetch from the Web to look at is that they are passive. We only deal with
static information files, stored on some server somewhere in the world for us to
retrieve and look at. Not so with Java applets. When we fetch one of those from the
Web, it is a Java program that we load from the Web into our browser. When that
1 Introduction

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.

1.4 JavaScript and JSP


There is also a programming language called JavaScript. But unlike Java, which can
be used to write large, standalone applications, JavaScript is a language used solely
in Web pages and browsers. JavaScript was created by Netscape. It is used in small
bits of program code inside HTML documents to allow more advanced navigation
using the mouse, more flexible use of graphics, etc. Hence, pages containing
JavaScripts are not totally passive.
1.5 How This Book is Structured

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.

1.5 How This Book is Structured


At the beginning of this text we concentrate on Java applications and then later on
we cover applets. Furthermore, we will start by using textual communication with
the user. This means that we start out with the most minimal type of Java
programming. By doing this, we provide a basis for understanding the whole
workings of both applets and graphical user interfaces. We do this by gradually
explaining the mechanisms of the language, before taking on graphics and applets.
Small graphical user interfaces are still used quite early, for the sake of simplicity.
New students of programming languages often start by writing the world's
smallest program. It is commonly referred to as "Hello world!", because its only
task is printing that greeting to the user. The program only has to print one line of
text on the screen. We will also do this, but there is a certain antagonism between
writing tiny programs and studying Java's fundamental construction, object
orientation. Tiny Java programs don't make much sense in an OO context. Only
when the programs become larger will the power of OO begin to show. The
conclusion is this: things that seem odd to begin with become important in a larger
context. Don't pay too much attention to things looking strange in a small
program.
Vocabulary
The use of terms in computer science is not trivial. Different aspects of computer
science put different meanings into the same term. In this book, we stick to the
terms used by Java's main developers, Gosling, Joy and Steele, in their language
specification [Gosling, Joy, Steele 1996]. We also use the vocabulary of the main
designers of UML, our modeling language [Rumbaugh, Jacobson, Booch 1999]. In
the event that these two sources differ in their terminologies, we will choose those
of the Java designers.
Language references
The language Java can be said to be minimal. That means that there is a small
number of constructs and keywords in the language, but a large amount of ready-
to-use code for all sorts of functions. You need to learn to use this code and find
your way around it as well. In this book we will provide references to the core of
the language and ready-to-use functionality in two types of boxes in the text. This
is our way of trying to systematize this. An example of a reference box relating to
the language core follows here. What's inside it is only included as an example.
1 Introduction

Java Core

Example of language core reference: class


The reserved word class is used at the beginning of the definition of all classes in
Java, class is followed by a start-bracket, {, next is the member variables and
methods of the class, and finally the class definiton is closed by a closing bracket
}. Example:
class Patient {
/* Contents */

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

Example of API reference: the class java.lang.String


Methods:
public int lengthQ
The method returns the length of this String object.

Pay particular attention to the Note boxes.

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:

c:\javaprograms\> javac MyProgram.class


c: \ javaprograms\> Java MyProgram
Hello, you lot!
1.6 A Small Example Program

As you see, the user input is in italics.


Often, we need to include larger amounts of Java code in a paragraph. We have
chosen to use a more space-conserving type face for that.
public class BouncingBall {
public static void main(String[] args) {
Dimension windowDim = new Dimension(500,500);
BouncingBallWindow myWindow
= new BouncingBallWindow(windowDim.width, windowDim. height);
myWindow.setVisible(true);

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.

1.6 A Small Example Program


Now it's high time to introduce our first Java program. We do not intend to explain
all of its aspects, but wish to give the reader an idea of what a Java program is. We
have already used the term program code for what you can see in program listing
1.1, and it is also called source code.
1 Introduction

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:

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!

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.

Figure 1.2 Compiling to machine code

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.

Figure 1.3 Compiling to byte code


1.6 A Small Example Program

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.

1.7 Examples of Applets


With an Internet connection, you can look at a simple example applet we have
written. Many readers may have seen applets on the Web before. Our example is
found at http://www.tisip.no/JavaTheUmlWay/examples/SimpleApplet.html [URL
Simple Applet].

Figure 1.4 Very simple applet


1 Introduction

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

Figure 1.5 A slightly more advanced applet

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

Possible problems with the applets


There is a chance that you will have trouble seeing any applets in these Web pages.
That has to do with the low degree of homogeneity on the Web. There are a
plethora of computers, operating systems and browsers. Java applets are meant to
work in most cases, but it is inevitable that they occasionally fail to work correctly.
This problem is much more pronounced with applets than with applications,
because there are not as many different Java interpreters as there are browsers. Here
are some possible causes for you not seeing any applets at all:

• 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.

1.8 New Concepts in This Chapter


Concept Brief Explanation

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

Concept Brief Explanation

byte code Something between machine code and source code.

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.

console A text window where we communicate with a text-based program.

CPU See microprocessor.

data file Files with information used by the programs.

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.

Internet A world-wide network of computers. It is special because it consists of several types of


computers and sub-networks. Used for Web, e-mail, discussion groups and countless
other things.

Java interpreter A program in charge of executing a Java program.

JDK See SDK.

JVM Java Virtual Machine. The theoretical model for a computer, which the Java interpreter
realizes.

machine code The language of the microprocessor.

method A named part of the source code which we use whenever needed. See also chapters 3
and 4.

microprocessor The "brain" of a computer.

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.

platform independent See architecture neutral.


1.9 Review Problems

Concept Brief Explanation

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.

program code See source code.

program file A file that is a program we can run.

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.

Software Development Kit. A standard development tool for Java.

A program or computer that performs tasks at the request of clients.

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.

1.9 Review Problems


1. What is a programming language? Name three.
2. What is Java SDK? Where do you get it?
3. What is byte code?
4. Explain how we compile and run a Java program.
1 Introduction

1.10 Programming Problems


1. Enter the program Print Text in a text editor, save, compile and run it. Verify
that the printout is correct, which is to say that the program works. Implied in
this is that SDK has been installed on your machine.
2. Change the program PrintText so that it prints the greeting 50 times instead
of 10. Compile it and check to see that it works.
3. Find out what happens if you try to run the program by typing
C:\javaprograms> java PrintText.class
Try to explain what you see.
4. Find out what happens if you try to run an applet, for instance SimpleApplet.closs,
in the usual way with the program java, and not in a Web page.
I'F
t 1

Learning goals for this chapter


After completing this chapter, you will understand the following concepts:

• Variables—how the contents are interpreted depending on the type of data

• Algorithms, input data, output data, test data sets

« Sequential execution, blocks, statements, keywords, and names

• Assignment, casting

You will be able to

• Write programs that perform mathematical calculations and print the results to
the console

• Set up a test data set for these types of programs

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 much paint, or wallpaper, will you need for a wall?

• 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.2 Data and Variables


Now we will write a program that calculates the area of a rectangular surface that
could be a wall or a floor. We'll ignore windows and doorways.
We need to know the answers to three key questions to be able to solve this
problem:
1. What is the purpose of the program? What results do we expect to get? This is the
data the program prints on the screen. We call it output data. Notice that we are
looking at this from the computer's point of view. The program writes and the
program's user reads this data on the screen.

Answer: Output data is the area, measured in square meters.


2.2 Data and Variables

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:

The length of the wall (meters): 5


The height of the wall (meters): 2.3
The area of the wall is 11.5 square meters

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.

Program Listing 2.1


/*
* WallCalculations.java E.L. 2001–08–09
2 Variables. Data Types, and Expressions

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:

length height area

Figure 2.1 The variables in the program that calculate the area of a wall
2.2 Data and Variables

The area of the wall is 11.5 square meters.


Let's look a little more closely at the variables:
The computer's internal memory is made up of many small electronic
components. We can think of these as switches that can be either on or off. A switch
that can be on or off can be associated with the digit 1 or 0. This type of digit is
called a bit ("binary digit"). Eight bits make a byte. The variables we are storing
information in consist of one or more bytes. By allowing the different switches in
a variable to be on or off, we can create many different combinations of zeroes and
ones. Each combination means a specific number, letter, or character. In the
program code, we indicate how the contents of the variables will be interpreted by
setting the data type before the name of the variable.
The data type for length, height, and area is double. That means that
the contents of the variables will be interpreted as decimal numerals.
Data input from the user
Program Listing 2.2 shows the same program with data input from the user.
Compile and run the program. Compared to the previous version of the program
the advantages are obvious. There we had to insert new values into the source code
for every new wall that was going to be calculated, and then compile before we
could run the program again. This new version can calculate the area of a number
of different walls without requiring changes in the program code.
Nonetheless, the program code in Program Listing 2.2 is quite complicated. We
will explain the details in the next chapter.

Program Listing 2.2


/*
* WallCalculations2.java E.L. 2001–06–1 6
V
import javax.swing.JOptionPane;
class WallCalculations2 {
public static void main(String[] args) {
String lengthlnput = JOptionPane.showlnputDialog("The length of the wall (meters): ");
String heightlnput = JOptionPane.showlnputDialog("The height of the wall (meters): ");
double length = Double.parseDouble(lengthlnput);
double height = Double.parseDouble(heightlnput);
double area = length * height;
JOptionPane.showMessageDialog(null,
"The area of the wall is " + area + " square meters.");
System. exit(0);

/* 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

Using comments in program code


We can tell the Java compiler that text is commentary in two ways:

• By using /* and */. All text between /* and */ is ignored by the compiler.
There can easily be several lines of text between / * and * /.

• By using / /. The rest of the line is ignored.

In this book, the comments are used in the following manner:


/ * and * / are always used if the comment consists of at least one line of text.
We use // if the rest of the line should be interpreted as a comment. For example:
double price = 140.50; // price in Swedish Crowns
There's usually a header comment at the top of a file. In this book, that will include
the file name, the author's initials, the date of the most recent version of the file,
and often a short description of the file. In larger programming systems, the header
comment can contain far more comprehensive information.
Otherwise, comments are used to explain bits of code that might not be obvious.
On the other hand, it's usually assumed that the reader is familiar with the
programming language. The comment shouldn't repeat what the code statement
says. An example of a superfluous comment:
double number = 4; // declares a variable named number, and sets it equal to 4
However, in some places in this book we will use comments like this to explain new
things. In another situation these comments would be considered superfluous.
Problems
1. Change the length and height in the program in Program Listing 2.1 so that it
calculates the area of another wall.
2. Expand the program so that it also calculates the perimeter of the wall. Print out
the result.

2.3 Algorithms, Programming Errors, and Test Data


An algorithm is "a limited and ordered set of well-defined rules for solving a
problem".1 Note that the rules (instructions) are clearly defined—they shouldn't be
ambiguous. This doesn't necessarily mean that they are very detailed—we can have
algorithms with many different degrees of detail. Having different levels of detail in
algorithms is key in non-object-oriented programming, which we won't go into
here. In object-oriented programming the problem at hand is almost always

1. [Hofstad, Loland, Scott 1997, p. 19.)


2.3 Algorithms, Programming Errors, and Test Data

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.

Program Listing 2.3


/*
* WallCalculations I. Java E.L 2001 -08-09
V
class WallCalculations 1 {
public static void main(String[] args) {
double length = -2.5;
double height = 3;
if (length > 0 && height > 0) { // if length > 0 and height > 0
double area = length * height;
System.out.println("The area of the wall is * + area + " square meters.");
} else { // ...otherwise....
System.out.println("The length and/or the height has a non-positive value.");

/* 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.

2.4 Statements, Blocks, and Names


A program consists of many statements. A statement is an instruction to the
computer. It ends with a semicolon(;). A group of statements surrounded by curly
braces { } is called a block. In some contexts, a block can also be considered a
statement.
Another Random Scribd Document
with Unrelated Content
motrices y passaient rarement et que leurs roues étaient munies de
fibres minérales, très élastiques; comme, par ailleurs, les hommes
des deux oasis savaient encore se servir partiellement des énergies
énormes qu’avaient captées leurs ascendants, l’entretien exigeait
plus de surveillance que de travail. Les ferromagnétaux ne s’y
montraient guère et n’y faisaient que des dégâts insignifiants; un
piéton aurait pu y marcher une journée entière sans presque
ressentir d’influence nocive; mais il n’aurait pas été prudent de faire
des haltes trop longues ni surtout de s’y endormir: bien des malades
y avaient perdu comme Elma tous leurs globules rouges et y étaient
morts d’anémie.
Les Neuf ne couraient aucun péril: chacun dirigeait un planeur
léger qui, du reste, eût pu emporter quatre hommes. Alors même
qu’un accident surviendrait aux deux tiers des appareils, l’expédition
ne serait pas compromise.
Doués d’une élasticité presque parfaite, les planeurs étaient
construits pour résister aux chocs les plus rudes et pour braver
l’ouragan.
Manô avait pris la tête. Targ et Arva sillaient presque de
conserve. L’agitation du jeune homme ne cessait de s’accroître. Et
l’histoire des grandes catastrophes, fidèlement transmise de
génération en génération, hantait sa mémoire.

Depuis cinq cents siècles, les hommes n’occupaient plus, sur la


planète, que des îlots dérisoires. L’ombre de la déchéance avait de
loin précédé les catastrophes. A des époques fort anciennes, aux
premiers siècles de l’ère radio-active, on signale déjà la décroissance
des eaux: maints savants prédisent que l’Humanité périra par la
sécheresse. Mais quel effet ces prédictions pouvaient-elles produire
sur des peuples qui voyaient des glaciers couvrir leurs montagnes,
des rivières sans nombre arroser leurs sites, d’immenses mers battre
leurs continents? Pourtant, l’eau décroissait lentement, sûrement,
absorbée par la terre et volatilisée dans le firmament[2]. Puis, vinrent
les fortes catastrophes. On vit d’extraordinaires remaniements du
sol; parfois, des tremblements de terre, en un seul jour, détruisaient
dix ou vingt villes et des centaines de villages: de nouvelles chaînes
de montagnes se formèrent, deux fois plus hautes que les antiques
massifs des Alpes, des Andes ou de l’Himalaya; l’eau tarissait de
siècle en siècle. Ces énormes phénomènes s’aggravèrent encore. A
la surface du soleil, des métamorphoses se décelaient qui, d’après
des lois mal élucidées, retentirent sur notre pauvre globe. Il y eut un
lamentable enchaînement de catastrophes: d’une part, elles
haussèrent les hautes montagnes jusqu’à vingt-cinq et trente mille
mètres; d’autre part, elles firent disparaître d’immenses quantités
d’eau.

[2] Dans les hautes régions atmosphériques, la vapeur d’eau fut de


tout temps décomposée, par les rayons ultra-violets, en oxygène et en
hydrogène: l’hydrogène s’échappait dans l’étendue interstellaire.

On rapporte que, au début de ces révolutions sidérales, la


population humaine avait atteint le chiffre de vingt-trois milliards
d’individus. Cette masse disposait d’énergies démesurées. Elle les
tirait des protoatomes (comme nous le faisons encore, quoique
imparfaitement, nous-mêmes) et ne s’inquiétait guère de la fuite des
eaux, tellement elle avait perfectionné les artifices de la culture et de
la nutrition. Même, elle se flattait de vivre prochainement de
produits organiques élaborés par les chimistes. Plusieurs fois, ce
vieux rêve parut réalisé: chaque fois, d’étranges maladies ou des
dégénérescences rapides décimèrent les groupes soumis aux
expériences. Il fallut s’en tenir aux aliments qui nourrissaient
l’homme depuis les premiers ancêtres. A la vérité, ces aliments
subissaient de subtiles métamorphoses, tant du fait de l’élevage et
de l’agriculture que du fait des manipulations savantes. Des rations
réduites suffisaient à l’entretien d’un homme; et les organes digestifs
avaient accusé, en moins de cent siècles, une diminution notable,
tandis que l’appareil respiratoire s’accroissait en raison directe de la
raréfaction de l’atmosphère.
Les dernières bêtes sauvages disparurent; les animaux
comestibles, par comparaison à leurs ascendants, étaient de
véritables zoophytes, des masses ovoïdes et hideuses, aux membres
transformés en moignons, aux mâchoires atrophiées par le gavage.
Seules, quelques espèces d’oiseaux échappèrent à la dégradation et
prirent un merveilleux développement intellectuel.
Leur douceur, leur beauté et leur charme croissaient d’âge en
âge. Ils rendaient des services imprévus, à cause de leur instinct,
plus délicat que celui de leurs maîtres, et ces services étaient
particulièrement appréciés dans les laboratoires.
Les hommes de cette puissante époque connurent une existence
inquiète. La poésie magnifique et mystérieuse était morte. Plus de
vie sauvage, plus même ces immenses étendues presque libres: les
bois, les landes, les marais, les steppes, les jachères de la période
radio-active. Le suicide finissait par être la plus redoutable maladie
de l’espèce.

En quinze millénaires, la population terrestre descendit de vingt-


trois à quatre milliards d’âmes; les mers, réparties dans les abîmes,
n’occupaient plus que le quart de la surface; les grands fleuves et les
grands lacs avaient disparu; les monts pullulaient, immenses et
funèbres. Ainsi la planète sauvage reparaissait,—mais nue!
L’homme, cependant, luttait éperdument. Il s’était flatté, s’il ne
pouvait vivre sans eau, de fabriquer celle dont il aurait besoin pour
ses usages domestiques et agricoles; mais les matériaux utiles
devenaient rares, sinon à des profondeurs qui rendaient leur
exploitation dérisoire. Il fallut se rabattre sur des procédés de
conservation, sur des moyens ingénieux pour ménager l’écoulement
et pour tirer le maximum d’effet du fluide nourricier.
Les animaux domestiques périrent, incapables de s’habituer aux
nouvelles conditions vitales: en vain tenta-t-on de refaire des
espèces plus rustiques; une dégradation deux cents fois millénaire
avait tari l’énergie évolutive. Seuls les oiseaux et les plantes
résistaient. Celles-ci reprirent quelques formes ancestrales; ceux-là
s’adaptèrent au milieu: beaucoup, redevenant sauvages,
construisirent leurs aires à des hauteurs où l’homme pouvait
d’autant moins les poursuivre que la raréfaction de l’air, quoique bien
moindre, accompagnait celle de l’eau. Ils vécurent de déprédations
et déployèrent une ruse si raffinée qu’on ne put les empêcher de se
maintenir. Quant à ceux qui demeuraient parmi nos ancêtres, leur
sort fut d’abord épouvantable. On tenta de les avilir à l’état de bêtes
comestibles. Mais leur conscience était devenue trop lucide; ils
luttèrent affreusement pour échapper à leur sort. Il y eut des scènes
aussi hideuses que ces épisodes des temps primitifs où l’homme
mangeait l’homme, où des peuples entiers étaient réduits en
servitude. L’horreur pénétra les âmes, peu à peu on cessa de
brutaliser les compagnons de planète et de s’en repaître.
D’ailleurs, les phénomènes sismiques continuaient à remanier les
terres et à détruire les villes. Après trente mille ans de lutte, nos
ancêtres comprirent que le minéral, vaincu pendant des millions
d’années par la plante et la bête, prenait une revanche définitive. Il y
eut une période de désespoir qui ramena la population à trois cents
millions d’hommes, tandis que les mers se réduisaient au dixième de
la surface terrestre. Trois ou quatre mille ans de répit firent renaître
quelque optimisme. L’humanité entreprit de prodigieux travaux de
préservation: la lutte contre les oiseaux cessa; on se borna à les
mettre dans des conditions qui ne permettaient pas qu’ils se
multipliassent, on tira d’eux de précieux services.
Puis, les catastrophes reprirent. Les terres habitables se
rétrécirent encore. Et, il y a environ trente mille ans, eurent lieu les
remaniements suprêmes: l’humanité se trouva réduite à quelques
territoires disséminés sur la terre, redevenue vaste et formidable
comme aux premiers âges; en dehors des oasis, il devenait
impossible de se procurer l’eau nécessaire à la vie.
Depuis, une accalmie relative s’est produite. Quoique l’eau que
nous fournissent les puits creusés dans l’abîme ait encore décru, que
la population se soit réduite d’un tiers, que deux oasis aient dû être
abandonnées, l’humanité se maintient: sans doute se maintiendra-t-
elle pendant cinquante ou cent mille ans encore... Son industrie a
immensément décru. Des énergies qu’utilisait notre espèce en sa
force, l’homme des oasis ne peut plus employer qu’une faible partie.
Les appareils de communication et les appareils de travail sont
devenus moins complexes; depuis bien des millénaires, il a fallu
renoncer aux spiraloïdes qui transportaient les ancêtres à travers
l’étendue avec une vitesse dix fois plus grande que celle de nos
planeurs.
L’homme vit dans un état de résignation douce, triste et très
passive. L’esprit de création s’est éteint; il ne se réveille, par
atavisme, que dans quelques individus. De sélection en sélection, la
race a acquis un esprit d’obéissance automatique, et par là parfaite,
aux lois désormais immuables. La passion est rare, le crime nul. Une
sorte de religion est née, sans culte, sans rites: la crainte et le
respect du minéral. Les Derniers Hommes attribuent à la planète une
volonté lente et irrésistible. D’abord favorable aux règnes qui
naissent d’elle, la terre leur laisse prendre une grande puissance.
L’heure mystérieuse où elle les condamne est aussi celle où elle
favorise des règnes nouveaux.
Actuellement, ses énergies obscures favorisent le règne
ferromagnétique. On ne peut pas dire que les ferromagnétaux aient
participé à notre destruction; tout au plus ont-ils aidé à
l’anéantissement, fatal après tout, des oiseaux sauvages. Encore que
leur apparition remonte à une époque lointaine, les nouveaux êtres
ont peu évolué. Leurs mouvements sont d’une surprenante lenteur;
les plus agiles ne peuvent parcourir un décamètre par heure; et les
enceintes de fer vierge des oasis, plaquées de bismuth, sont pour
eux un obstacle infranchissable. Il leur faudrait, pour nous nuire
immédiatement, faire un saut évolutif sans rapport avec leur
développement antérieur.
On commença à percevoir l’existence du règne ferromagnétique
au déclin de l’âge radio-actif. C’étaient de bizarres taches violettes
sur les fers humains, c’est-à-dire sur les fers et les composés des
fers qui ont été modifiés par l’usage industriel. Le phénomène
n’apparut que sur des produits qui avaient maintes fois resservi:
jamais l’on ne découvrit de taches ferromagnétiques sur des fers
sauvages. Le nouveau règne n’a donc pu naître que grâce au milieu
humain. Ce fait capital a beaucoup préoccupé nos aïeux. Peut-être
fûmes-nous dans une situation analogue vis-à-vis d’une vie
antérieure qui, à son déclin, permit l’éclosion de la vie
protoplasmique.
Quoi qu’il en soit, l’humanité a constaté de bonne heure
l’existence des ferromagnétaux. Lorsque les savants eurent décrit
leurs manifestations rudimentaires, on ne douta pas que ce fussent
des êtres organisés. Leur composition est singulière. Elle n’admet
qu’une seule substance: le fer. Si d’autres corps, en quantité très
petite, s’y trouvent parfois mêlés, c’est en tant qu’impuretés,
nuisibles au développement ferromagnétique; l’organisme s’en
débarrasse, à moins qu’il ne soit très affaibli ou atteint de quelque
maladie mystérieuse. La structure du fer, à l’état vivant, est fort
variée: fer fibreux, fer granulé, fer mou, fer dur, etc. L’ensemble est
plastique et ne comporte aucun liquide. Mais ce qui caractérise
surtout les nouveaux organismes, c’est une extrême complication et
une instabilité continuelle de l’état magnétique. Cette instabilité et
cette complication sont telles que les chercheurs les plus opiniâtres
ont dû renoncer à y appliquer, non pas même des lois, mais
seulement des règles approximatives. C’est vraisemblablement là
qu’il faut voir la manifestation dominante de la vie ferromagnétique.
Lorsqu’une conscience supérieure se décèlera dans le nouveau
règne, je pense qu’elle reflétera surtout cet étrange phénomène, ou,
plutôt, qu’elle en sera l’épanouissement. En attendant, si la
conscience des ferromagnétaux existe, elle est encore élémentaire.
Ils sont à la période où le soin de la multiplication domine tout.
Néanmoins, ils ont déjà subi quelques transformations importantes.
Les écrivains de l’âge radio-actif nous font voir chaque individu
composé de trois groupes, avec tendance marquée, dans chaque
groupe, à la forme hélicoïde. Ils ne peuvent, à cette époque,
parcourir plus de cinq ou six centimètres par vingt-quatre heures;
lorsqu’on déforme leurs agglomérations, ils mettent plusieurs
semaines à les reformer. Actuellement, comme on l’a dit, ils arrivent
à franchir deux mètres par heure. De plus, ils comportent des
agglomérations de trois, cinq, sept et même neuf groupes, la forme
des groupes revêtant une grande variété. Un groupe, composé d’un
nombre considérable de corpuscules ferromagnétiques, ne peut
subsister solitaire: il faut qu’il soit complété par deux, par quatre, six
ou huit autres groupes. Une série de groupes comporte,
évidemment, des séries énergétiques, sans qu’on puisse dire de
quelle façon. A partir de l’agglomération par sept, le ferromagnétal
dépérit si l’on supprime un des groupes.
En revanche, une série ternaire peut se reformer à l’aide d’un
seul groupe, et une série quinquennaire à l’aide de trois groupes. La
reconstitution d’une série mutilée ressemble beaucoup à la genèse
des ferromagnétaux; cette genèse garde pour l’homme un caractère
profondément énigmatique. Elle s’opère à distance. Lorsqu’un
ferromagnétal prend naissance, on constate invariablement la
présence de plusieurs autres ferromagnétaux. Selon les espèces, la
formation d’un individu prend de six heures à dix jours; elle semble
exclusivement due à des phénomènes d’induction. La reconstitution
d’un ferromagnétal lésé s’opère à l’aide de procédés analogues.
Actuellement, la présence des ferromagnétaux est à peu près
inoffensive. Il en serait sans doute différemment si l’humanité
s’étendait.
En même temps qu’ils songeaient à combattre les
ferromagnétaux, nos ancêtres cherchèrent quelque méthode pour
faire tourner leur activité à l’avantage de notre espèce. Rien ne
semblait s’opposer, par exemple, à ce que la substance des
ferromagnétaux servît aux usages industriels. S’il en était ainsi, il
suffirait de protéger les machines (ce qui paraît, jadis, avoir été
réalisé sans trop de frais) d’une manière analogue à celle dont nous
préservons nos oasis... Cette solution, en apparence élégante, a été
tentée. Les annales anciennes rapportent qu’elle échoua. Le fer
transformé par la vie nouvelle se montre réfractaire à tout usage
humain. Sa structure et son magnétisme si variés en font une
substance qui ne se prête à aucune combinaison ni à aucun travail
orienté. Sans doute, cette structure semble s’uniformiser et le
magnétisme disparaître aux approches de la température de fusion
(et, a fortiori, lors de la fusion même); mais, lorsqu’on laisse le métal
se refroidir, les propriétés nuisibles reparaissent.
En outre, l’homme ne peut séjourner longtemps dans les
contrées ferromagnétiques de quelque importance. En peu d’heures,
il s’anémie. Après un jour et une nuit, il se trouve dans un état
d’extrême faiblesse. Il ne tarde pas à s’évanouir; s’il n’est pas
secouru, il succombe.
On n’ignore pas la raison immédiate de ces faits: le voisinage des
ferromagnétaux tend à nous enlever nos globules rouges. Ces
globules, presque réduits à l’état d’hémoglobine pure, s’accumulent
à la surface de l’épiderme et sont, ensuite, attirés vers les
ferromagnétaux qui les décomposent et semblent se les assimiler.
Diverses causes peuvent contre-balancer ou retarder le
phénomène. Il suffit de marcher pour n’avoir rien à craindre; à plus
forte raison suffit-il de circuler en motrice. Si l’on se vêt d’un tissu en
fibres de bismuth, on peut braver l’influence ennemie pendant deux
jours au moins; elle s’affaiblit si l’on se couche la tête au nord; elle
s’atténue spontanément lorsque le soleil est près du méridien.
Bien entendu, lorsque le nombre des ferromagnétaux décroît, le
phénomène est de moins en moins intense; un moment vient où il
s’annule, car l’organisme humain ne se laisse pas faire sans
résistance. Enfin, l’action ferromagnétique diminue d’abord selon la
courbe des distances, et devient insensible à plus de dix mètres.
On conçoit que la disparition des ferromagnétaux parût
nécessaire à nos ancêtres. Ils entreprirent la lutte avec méthode. A
l’époque où débutèrent les grandes catastrophes, cette lutte exigea
de lourds sacrifices: une sélection s’était opérée parmi les
ferromagnétaux; il fallait user d’énergies immenses pour refréner
leur pullulation.
Les remaniements planétaires qui suivirent donnèrent l’avantage
au nouveau règne; par compensation, sa présence devenait moins
inquiétante, car la quantité de métal nécessaire à l’industrie
décroissait périodiquement et les désordres sismiques faisaient
affleurer, en grandes masses, des minerais de fer natif, intangible
aux envahisseurs. Aussi, la lutte contre ceux-ci se ralentit-elle au
point de devenir négligeable. Qu’importait le péril organique au prix
de l’immense péril sidéral?...
Présentement, les ferromagnétaux ne nous inquiètent guère.
Avec nos enceintes d’hématite rouge, de limonite ou de fer
spathique, revêtues de bismuth, nous nous croyons inexpugnables.
Mais si quelque révolution improbable ramenait l’eau près de la
surface, le nouveau règne opposerait des obstacles incalculables au
développement humain, du moins à un développement de quelque
envergure.

Targ jeta un long regard sur la plaine: partout il apercevait la


teinte violette et les formes sinusoïdales particulières aux
agglomérats ferromagnétiques.
—Oui, murmurait-il..., si l’Humanité reprenait quelque envergure,
il faudrait recommencer le travail des ancêtres. Il faudrait détruire
l’ennemi ou l’utiliser. Je crains que sa destruction ne soit impossible:
un nouveau règne doit porter en soi des éléments de succès qui
défient les prévisions et les énergies d’un règne vieilli. Au rebours,
pourquoi ne trouverait-on pas une méthode qui permettrait aux deux
règnes de coexister, de s’entr’aider même? Oui, pourquoi pas?...
puisque le monde ferromagnétique tire son origine de notre
industrie? N’y a-t-il pas là l’indice d’une compatibilité profonde?
Puis, portant ses yeux vers les grands pics de l’Occident:
—Hélas! mes rêves sont ridicules. Et pourtant..., pourtant! Ne
m’aident-ils pas à vivre?... Ne me donnent-ils pas un peu de ce
jeune bonheur qui a fui pour toujours l’âme des hommes?
Il se dressa, avec un petit choc au cœur: là-bas, dans
l’échancrure du Mont des Ombres, trois grands planeurs blancs
venaient d’apparaître.

III
LA PLANÈTE HOMICIDE

Ces planeurs parurent frôler la Dent de Pourpre, inclinée sur


l’abîme; une ombre orange les enveloppait; puis ils s’argentèrent au
soleil zénithal.
—Les messagers des Terres-Rouges! s’écria Manô.
Il n’apprenait rien à ses compagnons de route: aussi bien ses
paroles n’étaient qu’un cri d’appel. Les deux escadrilles hâtaient leur
marche; bientôt, les masses pâles s’abaissèrent vers les pennes
émeraude des Hautes-Sources. Des salutations retentirent, suivies
d’un silence; les cœurs étaient lourds; on n’entendait que le
ronflement léger des turbines et le froissement des pennes. Tous
sentaient la force cruelle de ces déserts où ils semblaient siller en
maîtres.
A la fin, Targ demanda, d’une voix craintive:
—Connaît-on l’importance du désastre?
—Non, répondit un pilote au visage bistre. On ne le connaîtra pas
avant de longues heures. On sait seulement que le nombre des
morts et des blessés est considérable. Et ce ne serait rien! Mais on
craint la perte de plusieurs sources.
Il pencha la tête avec une calme amertume:
—Non seulement la récolte est perdue, mais beaucoup de
provisions ont disparu. Toutefois, s’il n’y a pas d’autre secousse, avec
l’aide des Hautes-Sources et de la Dévastation, nous pourrons vivre
pendant quelques années... La race cessera provisoirement de se
reproduire et peut-être n’aurons-nous à sacrifier personne.
Un moment encore, les escadrilles volèrent de conserve, puis le
pilote au visage bistre changea la direction: ceux des Terres-Rouges
s’éloignèrent.
Ils passèrent parmi les pics redoutables, au-dessus des gouffres,
et le long d’une pente qui eût, jadis, été couverte de pâturages:
maintenant, les ferromagnétaux y multipliaient leur descendance.
—Ce qui prouve, songea Targ, que ce versant est riche en ruines
humaines!
De nouveau, ils planèrent sur les vallées et les collines; vers les
deux tiers du jour, ils se trouvaient à trois cents kilomètres des
Terres-Rouges.
—Encore une heure! s’écria Manô.
Targ fouilla l’espace avec son télescope; il aperçut, indécises
encore, l’oasis et la zone écarlate à qui elle avait emprunté son nom.
L’esprit d’aventure, engourdi après la rencontre des grands planeurs,
se réveilla dans le cœur du jeune homme; il accéléra la vitesse de sa
machine et devança Manô.
Des vols d’oiseaux tournoyaient sur la zone rouge; plusieurs
s’avancèrent vers l’escadrille. A cinquante kilomètres de l’oasis, ils
affluèrent; leurs mélopées confirmaient le désastre et prédisaient
des secousses imminentes. Targ, le cœur serré, écoutait et regardait,
sans pouvoir articuler une parole.
La terre désertique semblait avoir subi la morsure d’une
prodigieuse charrue; à mesure qu’on approchait, l’oasis montra ses
maisons effondrées, son enceinte disloquée, les récoltes presque
englouties, de misérables fourmis humaines grouillant parmi les
décombres...
Soudain, une immense clameur déchira l’atmosphère; le vol des
oiseaux se brisa étrangement; un effrayant frisson secoua l’étendue.
La planète homicide consommait son œuvre!

Seuls, Targ et Arva avaient poussé un cri de pitié et d’horreur. Les


autres aviateurs continuaient leur route, avec la tristesse calme des
Derniers Hommes... L’oasis fut là. Elle retentissait de plaintes
sinistres. On voyait courir, ramper ou panteler de pitoyables
créatures; d’autres demeuraient immobiles, frappées par la mort;
parfois, une tête sanglante semblait sortir du sol. Le spectacle
devenait plus hideux à mesure qu’on discernait mieux les épisodes.
Les Neuf planèrent incertains. Mais le vol des oiseaux, d’abord
enfiévré par l’épouvante, s’harmonisait; aucune autre secousse
n’était prochaine; on pouvait atterrir.

Quelques membres du Grand Conseil reçurent les délégués des


Hautes-Sources. Les paroles furent rares et rapides. Le nouveau
désastre, exigeant toutes les énergies disponibles, les Neuf se
mêlèrent aux sauveteurs.
Les plaintes parurent d’abord intolérables. Des blessures atroces
avaient raison du fatalisme des adultes; les cris des enfants étaient
comme l’âme stridente et sauvage de la Douleur...
Enfin, les anesthésiques apportèrent leur aide bienfaisante.
L’ardente souffrance sombra au fond de l’inconscient. On n’entendait
plus que des clameurs éparses, les clameurs de ceux qui gisaient
dans la profondeur des ruines.
Une de ces clameurs attira Targ. Elle était craintive, non
douloureuse; elle avait un charme énigmatique et frais. Longtemps,
le jeune homme ne put la situer... Enfin, il découvrit un creux d’où
elle jaillissait plus nette. Des blocs arrêtaient le veilleur, qu’il se mit à
écarter avec prudence. Il lui fallait constamment interrompre le
travail devant les menaces sourdes du minéral: des trouées se
formaient, brusques, des pierres s’éboulaient ou bien on entendait
des vibrations suspectes.
La plainte s’était tue; la tension nerveuse et la fatigue couvraient
de sueur les tempes de Targ...
Soudain, tout sembla perdu: un pan de paroi croulait. Le
fouilleur, se sentant à la merci du minéral, baissa la tête et attendit...
Un bloc le frôla; il accepta la destinée; mais le silence et l’immobilité
se refirent.
Levant les yeux, il vit qu’une grande cavité, presque une caverne,
s’était ouverte vers la gauche: dans la pénombre, une forme
humaine était étendue. Le jeune homme enleva péniblement l’épave
vivante et sortit des décombres, à l’instant où un nouvel éboulement
rendait le boyau impraticable...

C’était une jeune femme ou une jeune fille, vêtue du maillot


argentin des Terres-Rouges. Avant toute chose, la chevelure émut le
sauveteur. Elle était de cette sorte lumineuse, que l’atavisme
ramenait à peine une fois par siècle chez les filles des hommes.
Éclatante comme les métaux précieux, fraîche comme l’eau jaillissant
des sources profondes, elle semblait un tissu d’amour, un symbole
de la grâce qui avait paré la femme à travers les âges.
Le cœur de Targ se gonfla, un tumulte héroïque emplissait son
crâne; il entrevit des actions magnanimes et glorieuses, qui ne
s’accomplissaient plus jamais parmi les Derniers Hommes... Et,
tandis qu’il admirait la fleur rouge des lèvres, la ligne délicate des
joues et leur pulpe nacrée, deux yeux s’ouvrirent, qui avaient la
couleur des matins, quand le soleil est vaste et qu’une haleine douce
court sur les solitudes...

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.

Targ franchit l’enceinte en ruines, il entra dans le désert muet et


terrible.
La lune, presque pleine, rendait invisibles les plus faibles étoiles;
elle éclairait les granits rouges et les piles violettes des
ferromagnétaux: une phosphorescence pâle ondulait par intervalles,
signe mystérieux de l’activité des nouveaux êtres.
Le jeune homme avançait dans la solitude, inattentif à sa
grandeur funèbre.
Une image brillante dominait les navrements de la catastrophe. Il
emportait comme un «double» de la chevelure vermeille; l’étoile
Véga palpitait ainsi qu’une prunelle bleue. L’amour devenait l’essence
même de sa vie; et cette vie était plus intense, plus profonde,
prodigieuse. Elle lui révélait, dans sa plénitude, ce monde de beauté
qu’il avait pressenti, et pour lequel il valait mieux mourir que de
vivre pour le morne idéal des Derniers Hommes. Par intervalles,
comme un nom devenu sacré, le nom de celle qu’il avait retirée des
décombres venait à sa lèvre:
—Erê!
Dans le farouche silence, le silence du désert éternel, comparable
au silence du grand éther où vacillaient les astres, il avançait encore.
L’air était immobile autant que les granits; le temps semblait mort,
l’espace figurait un autre espace que celui des hommes, un espace
inexorable, glacial, plein de mirages lugubres.
Pourtant, une vie était là, abominable d’être celle qui succéderait
à la vie humaine, sournoise, terrifique, inconnaissable. Deux fois,
Targ s’arrêta pour voir agir les formes phosphorescentes. La nuit ne
les endormait point. Elles se déplaçaient, pour des fins mystérieuses;
la façon dont elles glissaient sur le sol ne s’expliquait par aucun
organe. Mais il se désintéressait vite d’elles. L’image d’Erê
l’entraînait; il y avait une relation confuse entre cette marche dans la
solitude et l’héroïsme éveillé dans son âme. Il cherchait confusément
l’aventure, l’aventure impossible, l’aventure chimérique: la
découverte de l’Eau.
L’Eau, seule, pouvait lui donner Erê. Toutes les lois de l’homme le
séparaient d’elle. Hier encore, il aurait pu la rêver pour épouse: il
suffisait qu’une fille des Hautes-Sources fût, en échange, accueillie
aux Terres-Rouges. Après la catastrophe, l’échange devenait
impossible. Les Hautes-Sources recevraient des exilés, mais en les
condamnant au célibat. La loi était inexorable; Targ l’acceptait
comme une nécessité supérieure...

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.

A la fin, il se trouva devant une fente médiocre, à la base d’une


roche haute et très large, que les secousses n’avaient que faiblement
entamée. Il suffisait d’examiner la cassure, par endroits étincelante
comme du cristal, pour deviner qu’elle était récente. Targ, la jugeant
négligeable, allait s’éloigner. Des scintillations l’attirèrent. Pourquoi
ne pas l’explorer? Si elle était peu profonde, il n’aurait que quelques
pas à faire.
Elle se révéla plus longue qu’il ne l’eût espéré. Néanmoins, après
une trentaine de pas, elle commença de se rétrécir; bientôt, Targ
crut qu’il ne pourrait aller plus loin. Il s’arrêta, il examina
scrupuleusement les détails des murailles. Le passage n’était pas
encore impossible, mais il fallait ramper. Le veilleur n’hésita guère; il
s’engagea dans un trou, dont le diamètre excédait à peine la largeur
d’un homme. Le passage, sinueux et semé de pierres aiguës, devint
plus étroit encore; Targ se demanda s’il lui serait possible de revenir
en arrière.
Il était comme encastré dans la terre profonde, captif du minéral,
petite chose infiniment faible qu’un seul bloc réduirait en particules.
Mais la fièvre de la chose commencée palpitait en lui: s’il
abandonnait la tâche, avant qu’elle ne fût tout à fait impossible, il se
haïrait et se mépriserait ensuite. Il persévéra.
Les membres trempés de sueur, il avança longtemps dans les
entrailles du roc. A la fin, il eut une défaillance. Les battements de
son cœur, qui faisaient comme un grand bruit d’ailes, s’affaiblirent. Il
n’y eut plus qu’une palpitation chétive; le courage et l’espoir
tombèrent comme des fardeaux. Quand le cœur reprit quelque
force, Targ se jugea ridicule d’être engagé dans une aventure aussi
primitive.
—Ne serais-je pas un fou?
Et il commença de ramper en arrière. Alors, un désespoir atroce
l’accabla; l’image d’Erê se dessina si vive qu’elle semblait être avec
lui dans la fissure.
—Ma folie vaudrait encore mieux que l’affreuse sagesse de mes
semblables... En avant!
Il recommença l’aventure; il joua sauvagement sa vie, résolu à
ne s’arrêter que devant l’infranchissable.
Le hasard parut favorable à son audace; la crevasse s’élargit, il se
trouva dans un haut corridor de basalte dont la voûte semblait
soutenue par des colonnes d’anthracite. Une joie aiguë le saisit, il se
mit à courir; tout parut possible.
Mais la pierre est aussi pleine d’énigmes que, jadis, la forêt verte.
Soudain, le couloir se termina. Targ se trouva devant une muraille
ténébreuse dont la radiatrice tirait à peine quelques reflets...
Néanmoins, il ne cessait d’explorer les parois. Et il découvrit, à trois
mètres de hauteur, l’ouverture d’une autre crevasse.

C’était une fente un peu sinueuse, inclinée d’environ quarante


degrés sur l’horizontale, assez large pour admettre le passage d’un
homme. Le veilleur la considérait avec un mélange de joie et de
désappointement. Elle attirait sa chimérique espérance, puisqu’enfin
la voie n’était pas définitivement close; par ailleurs, elle se
manifestait décourageante, puisqu’elle reprenait vers le haut.
—Si elle ne redescend pas, il y a plus de chances qu’elle me
ramène à la surface que dans le sous-sol! grommela l’explorateur.
Il eut un geste d’insouciance et de défi, un geste qui lui était
étranger, comme à tous les hommes actuels, et qui répétait quelque
geste ancestral. Puis, il se mit en devoir d’escalader la paroi.
Elle était presque verticale et lisse. Mais Targ avait emporté
l’échelle en fibres d’arcum, que les aviateurs n’oubliaient jamais. Il la
tira de son sac d’outils. Après avoir servi à plusieurs générations, elle
était aussi souple et solide qu’aux premiers jours. Il déroula sa fine
et légère structure et, la saisissant par le milieu, il lui imprima l’élan
utile. C’était un mouvement qu’il exécutait dans la perfection. Les
crochets qui terminaient l’échelle s’agriffèrent sans peine au basalte.
En quelques secondes, l’explorateur atteignit la fente.
Il ne put retenir un cri de mécontentement. Car si la crevasse
était parfaitement praticable, en revanche elle remontait par une
pente assez forte. Tant d’efforts auraient donc été vains!
Toutefois, ayant replié l’échelle, Targ s’engagea dans la fissure.
Les premiers pas furent pénibles. Puis, le terrain s’aplanit, un couloir
se montra où plusieurs hommes auraient pu marcher de front.
Malheureusement, la pente montait toujours. Le veilleur supputa
qu’il devait se trouver à une quinzaine de mètres au-dessus du
niveau de la plaine extérieure; le voyage souterrain devenait une
ascension!...
Il marcha vers le dénouement, quel qu’il fût, avec une tranquille
amertume et tout en se reprochant la folle aventure: qu’avait-il fait
pour aboutir à une découverte qui dépasserait en importance tout ce
qu’avaient trouvé les hommes depuis des centaines de siècles?
Suffirait-il qu’il eût un caractère chimérique, une âme plus révoltée
que les autres, pour réussir là où l’effort collectif, appuyé d’un
outillage admirable, avait échoué? Une tentative comme la sienne ne
réclamait-elle pas une résignation et une patience absolues?...
Distrait, il ne s’apercevait pas que la pente se faisait plus douce.
Elle était devenue horizontale lorsqu’il se réveilla, avec un grand
sursaut: à quelques pas devant lui, la galerie commençait à
descendre!...
Elle descendit régulièrement, sur une longueur de plus d’un
kilomètre; large, plus approfondie au milieu que sur les bords, la
marche y était généralement commode, à peine interrompue par
quelque bloc ou par quelque fissure. Sans doute, à une époque
lointaine, un cours d’eau souterrain s’y frayait passage.
Cependant, les déblais s’accumulèrent, parmi lesquels il en était
de récents, puis l’issue parut de nouveau bouchée.
—La galerie ne s’arrêtait pas ici, fit le jeune homme. Ce sont des
remaniements de l’écorce terrestre qui l’ont interrompue, mais
quand? Hier..., il y a mille ans..., il y a cent mille ans?
Il ne s’arrêta pas à examiner les éboulis, parmi lesquels il eût
reconnu la trace de convulsions récentes. Toute sa perspicacité se
concentrait à découvrir un passage. Il ne tarda pas à apercevoir une
fissure. Étroite et haute, dure, hérissée, rebutante, elle ne le trahit
point: il retrouva sa galerie. Elle continuait à descendre, toujours
plus spacieuse; à la fin, sa largeur moyenne atteignait plus de cent
mètres.
Les derniers doutes de Targ s’évanouirent: un véritable fleuve
souterrain avait, jadis, coulé là. A priori, cette conviction était
encourageante. A la réflexion, elle inquiétait l’Oasite. De ce que l’eau
avait jadis abondé, il ne s’ensuivait aucunement qu’elle fût
prochaine. Au contraire! Toutes les sources actuellement utilisées se
trouvaient loin des endroits où le liquide de vie avait afflué... C’était
presque une loi.

A trois reprises encore, la galerie parut finir en cul-de-sac;


chaque fois, Targ retrouva un passage. Elle se termina, cependant.
Un trou immense, un gouffre apparut aux yeux de l’homme.
Las et triste, il s’assit sur la pierre. Ce fut un moment plus terrible
que lorsqu’il rampait, là-haut, dans une galerie étouffante. Toute
nouvelle tentative serait une amère folie. Il fallait revenir! Mais son
cœur se révolta contre sa pensée. L’âme des aventures s’éleva,
accrue par l’étonnant voyage qu’il venait de faire. Le gouffre ne
l’épouvanta plus.
—Et quand il faudrait mourir? s’écria-t-il.
Déjà, il s’engageait entre des pointes de granit.
Abandonné à des inspirations rapides, il était descendu par
miracle à une profondeur de trente mètres, lorsqu’il fit un faux
mouvement et bascula.
—Fini! soupira-t-il.
Il s’écroula dans le vide.

V
AU FOND DES ABIMES

Un choc l’arrêta. Non le choc raide de la chute sur le granit, mais


un choc élastique, assez violent, toutefois, pour l’étourdir. Quand il
reprit conscience, il se trouva suspendu dans la pénombre et, se
tâtant, il découvrit qu’une saillie avait accroché son sac d’outils. Les
courroies du sac, rattachées à son torse, le retenaient: faites,
comme son échelle, en fibres d’arcum, il savait qu’elles ne céderaient
point. En revanche, le sac pouvait se détacher de la saillie.
Targ se sentait étrangement calme. Il calcula sans hâte ses
chances de perte et de salut: le sac embrassait la saillie près de
l’attache des courroies, en sorte que la prise était bonne.
L’explorateur tâta la paroi rocheuse. Outre la saillie, sa main
rencontra des surfaces raboteuses, puis le vide; ses pieds
trouvèrent, vers la gauche, un appui que, après quelques
tâtonnements, il jugea être une petite plate-forme. En empoignant la
saillie d’une part, en s’étayant, d’autre part, sur la plate-forme, il
pouvait se passer d’autre soutien.
Quand il eut choisi la position qu’il estima la plus commode, il
réussit à détacher le sac. Plus libre alors de ses gestes, il darda de
toutes parts les rais de sa radiatrice. La plate-forme était assez large
pour qu’un homme s’y tînt debout et même exécutât de faibles
mouvements. Au-dessus, une rainure du roc permettait à la rigueur
de fixer les crochets de l’échelle; ensuite, l’ascension semblait
praticable, jusqu’à l’endroit d’où l’Oasite était tombé. Au-dessous,
rien que le gouffre, avec des murailles verticales.
—Je puis remonter, conclut le jeune homme... Mais la descente
est impossible...
Il ne songeait plus qu’il venait d’échapper à la mort: seul, le dépit
de l’effort vain agitait son âme. Avec un long soupir, il lâcha la saillie
et, s’accrochant aux aspérités, il réussit à s’établir sur la plate-forme.
Ses tempes bourdonnaient, une torpeur tenait ses membres et son
cerveau; son découragement était si lourd qu’il se sentait peu à peu
succomber à l’appel vertigineux de l’abîme. Quand il se ranima, il
promena instinctivement ses doigts sur la muraille granitique et
s’aperçut de nouveau qu’elle se dérobait, vers la moitié de sa
hauteur. Il se baissa alors, il poussa un faible cri: la plate-forme se
trouvait à l’entrée d’une cavité, que les rais de la radiatrice
révélèrent considérable.
Il eut un rire silencieux. S’il allait à la défaite, du moins n’aurait-il
pas couru une aventure qui ne valait pas la peine d’être tentée!
S’assurant qu’aucun outil ne lui manquait et surtout que l’échelle
d’arcum était en bon ordre, il s’engagea dans la caverne. Elle étalait
une voûte de cristal de roche et de gemmes. A chaque mouvement
de la lampe, des éclairs rebondissaient, mystérieux et féeriques. Les
innombrables âmes des cristaux s’éveillaient à la lumière: c’était un
crépuscule souterrain, éblouissant et furtif, une grêle infinitésimale
de lueurs écarlates, orangées, jonquille, hyacinthe ou sinople. Targ y
voyait un reflet de la vie minérale, de cette vie vaste et minuscule,
menaçante et profonde, qui avait le dernier mot avec les hommes,
qui aurait, un jour, le dernier mot avec le règne ferromagnétique.
Dans ce moment, il ne la redoutait pas. Il considérait pourtant la
caverne avec le respect que les Derniers Hommes vouent aux
existences sourdes qui, ayant présidé aux Origines, gardent intactes
leurs formes et leurs énergies.
Un vague mysticisme fut en lui, non point le mysticisme sans
espérance des Oasites déchus, mais le mysticisme qui conduisit,
jadis, les cœurs hasardeux. S’il se défiait toujours des pièges de la
terre, il avait du moins cette foi qui succède aux efforts heureux et
qui transporte dans l’avenir les victoires du passé.

Après la caverne vint un couloir aux pentes capricieuses.


Plusieurs fois encore il fallut ramper, pour franchir des passes. Puis,
le couloir reprit; la pente devint raide au point que Targ craignit un
nouveau gouffre. Cette pente s’adoucit. Elle se fit presque aussi
commode qu’une route. Et le veilleur descendait avec sécurité,
lorsque les pièges reprirent. Sans que le couloir se fût rétréci en
hauteur ni en largeur, il se ferma. Un mur de gneiss était là, qui
luisait sournoisement aux lueurs de la lampe. En vain l’Oasite le
sondait en tous sens; aucune grosse fissure ne se révéla.
—C’est la fin logique de l’aventure! gémit-il... L’abîme, qui s’est
joué des efforts, du génie et des appareils de toute l’humanité, ne
pouvait être favorable à un petit animal solitaire!
Il s’assit, recru de fatigue et de tristesse. La route serait dure,
maintenant! Abattu par la défaite, aurait-il seulement la force d’aller
jusqu’au bout?
Il demeura là longtemps, écrasé sous sa détresse. Il ne pouvait
se décider à repartir. Par intervalles, il dardait sa lampe sur la
muraille blafarde... Enfin, il se releva. Mais alors, saisi d’une sorte de
fureur, il introduisit ses poings dans toutes les menues fissures, il tira
désespérément sur les saillies...
Son cœur se mit à battre: quelque chose avait bougé.

Quelque chose avait bougé. Un pan de la paroi oscillait. Avec un


han sourd, et de toute sa vigueur, Targ attaqua la pierre. Elle
bascula; elle faillit écraser l’homme; un trou apparut, triangulaire:
l’aventure n’était pas finie encore!
Haletant, plein de méfiance, Targ pénétra dans le roc, courbé
d’abord, puis debout, car la fissure s’agrandissait à chaque pas. Et il
avançait dans une sorte de somnambulisme, s’attendant à de
nouveaux obstacles, lorsqu’il crut revoir un gouffre.
Il ne se trompait point. La fissure aboutissait au vide; mais, vers
la droite, une masse déclive se détachait, énorme. Pour y atteindre,
Targ dut se pencher au dehors et se hisser à la force des poignets.
La pente était praticable. Lorsque le veilleur eut parcouru une
vingtaine de mètres, une sensation étrange le saisit, et découvrant
son hygroscope il le tendit sur le gouffre. Alors, il sentit positivement
la pâleur et le froid se déposer sur son visage...
Dans l’atmosphère souterraine, une vapeur flottait, invisible
encore à la lumière. L’eau était venue!
Targ poussa une clameur de triomphe; il dut s’asseoir, paralysé
par la surprise et la joie de la victoire. Puis, l’incertitude le reprit.
Sans doute, le fluide vivant était là, il allait apparaître; mais la
déception serait plus insupportable, s’il n’y avait qu’une source
insignifiante ou une faible nappe. A pas lents, plein de crainte, le
veilleur reprit la descente... Les preuves se multiplièrent; un
miroitement s’apercevait par intervalles...
Et brusquement, tandis que Targ contournait une saillie verticale,
l’eau se révéla.

VI
LES FERROMAGNÉTAUX

Deux heures avant l’aube, Targ se retrouva dans la plaine, au


bord de la crevasse où avait débuté son voyage au pays des ombres.
Affreusement las, il contemplait, au fond de l’horizon, la lune
écarlate, pareille à une fournaise ronde et prête à s’éteindre. Elle
disparut. Dans la nuit immense, les étoiles se ranimèrent.
Alors, le veilleur voulut se remettre en route. Ses jambes
semblaient de pierre, ses épaules s’affaissaient douloureusement et,
par tout son corps, passait une telle langueur qu’il se laissa choir sur
un bloc... Les paupières entrecloses, il revécut les heures qu’il venait
de passer dans les abîmes. Le retour avait été épouvantable. Malgré
qu’il eût pris soin d’accumuler les traces de son passage, il s’était
égaré. Puis, déjà épuisé par les efforts précédents, il avait failli
s’évanouir. Le temps semblait d’une longueur incommensurable; Targ
était comme un mineur qui aurait passé de longs mois dans la terre
cruelle...
Tout de même, le voici revenu sur la surface où vivent encore ses
frères, voici les astres qui, à travers les âges, exaltèrent les rêves de
l’homme; bientôt, l’aube divine va reparaître dans l’étendue.
—L’aube! balbutia le jeune homme... Le jour!
Il étendit les bras vers l’orient, dans un geste d’extase; puis, ses
yeux se refermèrent, et, sans qu’il en eût conscience, il s’étendit sur
le sol.

Une lueur rouge le réveilla. Soulevant avec peine les paupières, il


aperçut, au fond de l’horizon, l’orbe immense du soleil.
—Allons! debout..., se dit-il.
Mais une torpeur invincible le clouait au sol; ses pensées
flottaient engourdies, la fatigue lui prêchait le renoncement. Il allait
se rendormir, lorsqu’il sentit un léger picotement par tout l’épiderme.
Et il vit, sur sa main, à côté des écorchures qu’il s’était faites aux
pierres, des points rouges caractéristiques.
—Les ferromagnétaux, murmura-t-il. Ils boivent ma vie!
Dans sa lassitude, l’aventure ne l’effraya guère. C’était comme
une chose lointaine, étrangère, presque symbolique. Non seulement
il ne ressentait aucune souffrance, mais la sensation se révélait
presque agréable; c’était une sorte de vertige, une griserie légère et
lente qui devait ressembler à l’euthanasie... Soudain, les images
d’Erê et d’Arva traversèrent sa mémoire, suivies d’un ressaut
d’énergie.
—Je ne veux pas mourir! gémit-il. Je ne veux pas!
Il revécut obscurément sa lutte, ses souffrances, sa victoire. Là-
bas, aux Terres-Rouges, la vie l’attirait, fraîche et charmante. Non, il
ne voulait pas périr; il voulait voir longtemps encore les aurores et
les crépuscules; il voulait combattre les forces mystérieuses.
Et, rappelant sa volonté dormante, d’un effort terrible, il tenta de
se redresser.

VII
L’EAU, MÈRE DE LA VIE

Au matin, Arva ne soupçonna point l’absence de Targ. Il s’était


surmené la veille: sans doute, recru de fatigue, prolongeait-il son
repos. Pourtant, après deux heures d’attente, elle s’étonna. Et elle
finit par frapper à la cloison de la chambre que le veilleur avait
choisie. Rien ne répondit. Peut-être était-il sorti alors qu’elle
dormait? Elle frappa encore, puis elle poussa sur le commutateur de
la porte: celle-ci, en s’enroulant, découvrit une chambre vide.
La jeune fille y entra et vit toutes choses disposées en bon ordre:
le lit d’arcum était relevé contre la muraille, les objets de toilette
intacts; rien n’annonçait la présence récente d’un homme. Et
quelque appréhension serra le cœur de la visiteuse.
Elle alla trouver Manô; tous deux interrogèrent les oiseaux et les
hommes, sans obtenir une réponse utile. C’était anormal, et peut-
être inquiétant. Car l’oasis, après le tremblement de terre, demeurait
pleine de pièges. Targ pouvait être tombé dans une fissure ou avoir
été surpris par un éboulement.
—Plutôt est-il sorti de grand matin, fit l’optimiste Manô. Comme il
est homme d’ordre, il aura d’abord rangé sa chambre... Allons à la
découverte!
Arva restait anxieuse. Les communications étant devenues
incertaines et beaucoup d’ondifères ayant été renversés, les
recherches n’avançaient point.
Vers midi, Arva errait tristement, parmi des décombres, aux
confins de l’oasis et du désert, lorsqu’un essaim d’oiseaux parut,
avec de longs cris: Targ était retrouvé!
Elle n’eut qu’à monter sur l’enceinte, elle le vit qui venait, lointain
encore, d’un pas lourd...
Son vêtement était déchiré, des estafilades lui balafraient le cou,
le visage et les mains; tout son corps exprimait la fatigue; le regard,
seul, conservait sa fraîcheur.
—D’où viens-tu? cria Arva.
Il répondit:
—Je viens de la terre profonde.
Mais il n’en voulut pas dire davantage.

Le bruit de son retour s’étant répandu, ses compagnons de


voyage vinrent au-devant de lui. Et l’un d’eux, lui ayant reproché
d’avoir retardé leur départ, il repartit:
—Ne me le reprochez pas, car j’apporte de grandes nouvelles.
Cette réponse surprit et choqua les auditeurs. Comment un
homme pouvait-il apporter des nouvelles qui ne fussent à la
connaissance des autres hommes? De telles paroles avaient un sens,
jadis, lorsque la terre était inconnue et pleine de ressources, lorsque
le hasard demeurait parmi les êtres, et que les peuples ou les
individus opposaient leurs destins. Mais, à présent que la planète est
tarie, que les hommes ne peuvent plus lutter entre eux, que toute
chose est résolue par des lois inflexibles, que personne ne prévoit
les périls avant les oiseaux et les instruments, ce sont des propos
ineptes.
—De grandes nouvelles! répéta dédaigneusement celui qui avait
fait les reproches... Êtes-vous devenu fou, veilleur?
—Vous verrez bientôt si je suis devenu fou! Allons trouver le
Conseil des Terres-Rouges.
—Vous l’avez fait attendre.
Targ ne répondit plus. Il se tourna vers sa sœur et lui dit:
—Va, et ramène celle que j’ai sauvée hier... Sa présence est
nécessaire.

Le Grand Conseil des Terres-Rouges était réuni, au centre de


l’oasis. Il n’était pas au complet, plusieurs de ses membres ayant
succombé dans le désastre. Rien n’annonçait la douleur, à peine la
résignation, dans l’attitude des survivants. La fatalité était en eux,
présente comme la vie même.
Ils accueillirent les Neuf avec un calme presque inerte. Et Cimor,
qui présidait, dit d’une voix uniforme:
—Vous nous apportiez le secours des Hautes-Sources et les
Hautes-Sources sont frappées elles-mêmes. La fin des hommes
paraît très proche... Les oasis ne savent plus même quelles sont
celles qui pourront secourir les autres...
—Elles ne doivent même plus se secourir, ajouta Rem, le premier
chef des Eaux. La loi le défend. Il est équitable, lorsque les eaux ont
tari, que la solidarité disparaisse. Chaque oasis réglera son sort.
Targ s’avança au-devant des Neuf et affirma:
—Les eaux peuvent reparaître.
Rem le considéra avec un mépris tranquille:
—Tout peut reparaître, jeune homme. Mais elles ont disparu.
Alors, le veilleur, ayant jeté un regard au fond de la salle et
aperçu la chevelure de lumière, reprit avec tremblement:
—Les eaux reparaîtront pour les Terres-Rouges.
Une réprobation paisible parut sur quelques faces; tout le monde
garda le silence.
—Elles reparaîtront, s’écria Targ avec force. Et je puis le dire,
puisque je les ai vues.
Cette fois, une faible émotion, née de la seule image qui pût
agiter les Derniers Hommes, l’image d’une eau jaillissante, passa de
proche en proche. Et le ton de Targ, par sa véhémence et sa
sincérité, fit presque naître un espoir. Mais le doute revint vite. Ces
yeux trop vivants, les blessures, le vêtement déchiré, encourageaient
les méfiances: quoique rares, les fous n’avaient pas encore disparu
de la planète.
Cimor fit un signe léger. Quelques hommes cernèrent lentement
le veilleur. Il vit ce mouvement et en comprit la signification. Sans
trouble, il ouvrit sa boîte à outils, saisit son mince appareil
chromographique et, déroulant une feuille, il fit apparaître les
épreuves qu’il avait prises dans les entrailles du sol.
C’étaient des images aussi précises que la réalité même. Dès
qu’elles eurent frappé les yeux des plus proches, les exclamations se
heurtèrent. Un saisissement véritable, presque une exaltation,
s’empara des assistants. Car tous reconnaissaient le fluide
redoutable et sacré.
Manô, plus impressionnable que les autres, clama d’une voix
retentissante. Le cri, répercuté par les ondifères, se répandit au
dehors; une multitude rapide cerna le hall; l’unique délire qui pouvait
encore soulever les Derniers Hommes enivra la masse.
Targ se transfigura; il fut presque dieu; les âmes, pareilles aux
âmes anciennes, élevaient vers lui un enthousiasme mystique; des
faces déferlaient, des yeux mornes s’emplissaient de feu, une
espérance démesurée rompait le long atavisme de la résignation. Et
les membres du Grand Conseil eux-mêmes, perdus dans l’être
collectif, s’abandonnaient au tumulte.
Targ seul pouvait obtenir le silence. Il fit signe à la foule qu’il
voulait parler; les voix s’éteignirent, la houle des têtes s’apaisa; une
attention ardente dilatait les visages.
Le veilleur, se tournant vers cette lueur blonde qu’Erê mêlait aux
chevelures sombres, déclara:
—Peuple des Terres-Rouges, l’eau que j’ai découverte est sur
votre territoire: elle vous appartient. Mais la loi humaine me donne
un droit sur elle; avant de vous la céder, je réclame mon privilège!
—Vous serez le premier d’entre nous! dit Cimor. C’est la règle.
—Ce n’est pas cela que je demande, répondit doucement le
veilleur.
Il fit signe à la foule qu’on lui livrât passage. Puis, il se dirigea
vers Erê. Quand il fut près d’elle, il s’inclina et dit d’une voix ardente:
—C’est entre vos mains que je remets les eaux, maîtresse de
mon destin... Vous seule pouvez me donner ma récompense!
Elle écoutait, surprise et palpitante. Car de telles paroles ne
s’entendaient jamais plus. Dans un autre moment, à peine si elle les
eût comprises. Mais au milieu de l’exaltation des cœurs, et avec la
vision féerique des sources souterraines, tout son être se troubla:
l’émotion magnifique qui agitait le veilleur se refléta sur le visage
nacré de la vierge.

VIII
ET SEULES SURVIVENT LES TERRES-ROUGES

Dans les années qui suivirent, la terre n’eut que de faibles


secousses. Mais la dernière catastrophe avait suffi pour frapper de
mort les oasis. Celles qui avaient vu disparaître toute leur eau ne
l’avaient point reconquise. Aux Hautes-Sources, elle avait tari
pendant dix-huit mois, puis s’était évanouie dans les gouffres
insondables. Seules, les Terres-Rouges avaient connu de vastes
espérances. La nappe trouvée par Targ donnait une eau abondante
et moins impure que celle des sources disparues. Non seulement elle
suffisait à l’entretien des survivants, mais on avait pu recueillir le
faible groupe qui s’était sauvé à la Dévastation et beaucoup
d’habitants des Hautes-Sources.
Là, s’arrêtait le secours possible. Une hérédité de cinquante
millénaires les ayant adaptés aux lois inexorables, les Derniers
Hommes acceptaient sans révolte le jugement du destin. Il n’y eut
donc aucune guerre; à peine si quelques individus tentèrent de
fléchir la règle et vinrent en suppliants aux Terres-Rouges. On ne
pouvait que les rejeter: la pitié eût été une suprême injustice et une
forfaiture.
A mesure que s’épuisaient les provisions, chaque oasis désignait
les habitants qui devaient périr. On sacrifia d’abord les vieillards, puis
les enfants, sauf un petit nombre qui furent réservés dans
l’hypothèse d’un revirement possible de la planète, puis tous ceux
dont la structure était vicieuse ou chétive.
L’euthanasie était d’une extrême douceur. Dès que les
condamnés avaient absorbé les merveilleux poisons, toute crainte
s’abolissait. Leurs veilles étaient une extase permanente, leurs
sommeils profonds comme la mort. L’idée du néant les ravissait, leur
joie croissait jusqu’à la torpeur finale.
Beaucoup devançaient l’heure. Peu à peu, ce fut une contagion.
Dans les oasis équatoriales, on n’attendit pas la fin des provisions; il
restait encore de l’eau dans quelques réservoirs, et déjà les derniers
habitants avaient disparu.
Il fallut quatre ans pour anéantir le peuple des Hautes-Sources.
Alors, les oasis furent saisies par l’immense désert, les
ferromagnétaux occupèrent la place des hommes.
Après la découverte de Targ, les Terres-Rouges prospérèrent. On
avait reconstitué l’oasis vers l’Est, dans un territoire où la rareté des
ferromagnétaux rendait leur destruction facile. Les constructions, le
défrichement, le captage des eaux se firent en six mois. La première
récolte fut belle, la seconde merveilleuse.
Malgré la mort successive des autres communautés, les hommes
de l’Oasis Rouge vivaient dans une sorte d’espérance. N’étaient-ils
pas la peuplade élue, celle en faveur de qui, pour la première fois
depuis cent siècles, la loi implacable avait fléchi? Targ entretenait cet
état des âmes. Son influence était grande; il avait l’attrait des
créatures triomphantes et leur prestige symbolique.
Cependant, sa victoire n’avait impressionné personne autant que
lui-même. Il y voyait une obscure récompense et, plus encore, une
confirmation de sa foi. Son esprit d’aventure s’épanouissait; il eut
des aspirations presque comparables à celles des ancêtres
héroïques. Et l’amour qu’il ressentait pour Erê et les deux enfants
nés d’elle se mêlait de rêves dont il n’osait parler à personne, hormis
sa femme ou sa sœur, car il les savait incompréhensibles aux
Derniers Hommes.
Manô ignorait ces fièvres. Sa vie restait directe. Il ne songeait
guère au passé, moins encore à l’avenir. Il goûtait la douceur
uniforme des jours; il vivait auprès de sa femme, Arva, une
existence aussi insoucieuse que celle des oiseaux argentés dont les
groupes, chaque matin, planaient sur l’oasis. Comme ses premiers
enfants, à cause de leur belle structure, avaient été parmi les
émigrants accueillis aux Terres-Rouges, à peine si une mélancolie
fugitive le saisissait en songeant au dépérissement des Hautes-
Sources.
Au rebours, ce dépérissement tourmentait Targ: maintes fois, son
planeur le conduisit à l’oasis natale. Il cherchait l’eau avec
acharnement, il s’éloignait des routes protectrices, il visitait des
étendues terribles où les ferromagnétaux vivent la vie des jeunes
règnes. Avec quelques hommes de l’oasis, il avait sondé cent
gouffres. Quoique les recherches demeurassent vaines, Targ ne se
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like