100% found this document useful (25 votes)
82 views

Download full Java the UML way integrating object oriented design and programming Else Lervik ebook all chapters

oriented

Uploaded by

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

Download full Java the UML way integrating object oriented design and programming Else Lervik ebook all chapters

oriented

Uploaded by

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

Download the full version of the ebook at

https://ebookultra.com

Java the UML way integrating object oriented


design and programming Else Lervik

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

Explore and download more ebook at https://ebookultra.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

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/

ebookultra.com

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/

ebookultra.com

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/

ebookultra.com

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/

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

ebookultra.com

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

Beginning C Object Oriented Programming 2nd Edition Dan


Clark

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

ebookultra.com

Object Oriented Programming in C 4th Edition E.


Balagurusamy

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

ebookultra.com

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/
ebookultra.com
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.
Exploring the Variety of Random
Documents with Different Content
[761] “Ruso puro de la vieja Moscovia, dice M. A. Leroy-Beaulieu,
gran ruso de sangre eslava, mezclada de finlandés, físicamente
un tipo del pueblo más que de la aristocracia”. (Revue des Deux
Mondes, 15 de diciembre de 1910).
[762] 1857.
[763] 1862.
[764] El Fin de un Mundo (1905 y enero de 1906). Véase el telegrama dirigido por
Tolstoi a un diario americano:
“La agitación de los zemstvos tiene por objeto limitar el poder despótico y
establecer un gobierno representativo. Que triunfen o no, el resultado seguro será
el aplazamiento del verdadero mejoramiento social. La agitación política, al
producir la ilusión funesta de este mejoramiento por medios exteriores, detiene al
verdadero progreso, como es posible comprobarlo por el ejemplo de todos los
Estados constitucionales: Francia, Inglaterra, América”. (El movimiento social en
Rusia. M. Bienstock ha introducido este artículo en el Prefacio del Gran Crimen,
traducción francesa, 1905). En una larga e interesante carta a una dama que le
pedía formase parte de un Comité para la propagación de la lectura y la escritura
entre el pueblo, Tolstoi expresa otros cargos contra los liberales: Han
desempeñado el papel de engañados; se han hecho cómplices, por miedo, de la
autocracia; su participación en el gobierno da a éste un prestigio moral, y los
habitúa a compromisos que rápidamente los convierten en instrumentos del poder.
Alejandro II decía que todos los liberales estaban prontos a venderse a cambio de
honores cuando no de dinero. Alejandro III ha podido aniquilar sin peligros la obra
liberal de su padre: “Los liberales cuchicheaban entre ellos, porque tal cosa no les
agradaba, pero continuaban formando parte de los tribunales, seguían al servicio
del Estado y en la prensa. En la prensa hacían alusión a cosas sobre las cuales la
alusión estaba permitida; pero callaban sobre todo lo que estaba prohibido hablar,
y publicaban cuanto se les ordenaba publicar”. Lo mismo hacen bajo Nicolás II:
“¿Cuándo este joven que no sabe nada, que no comprende nada, responde con
audacia y falta de tacto a los representantes del pueblo, protestan los liberales?
De ninguna manera... De todas partes se envían al joven czar cobardes y
aduladoras felicitaciones”. (Correspondencia inédita, páginas 283-306).
[765] Guerra y Revolución.
En Resurrección, cuando el examen en casación del juicio de la Maslova, en el
Senado, es un darwinista materialista quien más se opone a la revisión porque le
choca, secretamente, que Nekhludov quiera casarse por deber con una prostituta:
toda manifestación del deber, y, más todavía, del sentimiento religioso, le produce
el efecto de una injuria personal. (Tomo I, página 359).
[766] Véanse como tipos, en Resurrección, a Novodvorov, el
agitador revolucionario, cuya vanidad y el egoísmo excesivo han
esterilizado su gran inteligencia. Imaginación nula; “ausencia total
de las cualidades morales y estéticas que producen la duda”. En
seguida, unido a sus pasos, como su sombra, Markel, el obrero
que se ha convertido en revolucionario por humillación y por
deseo de venganza, adorador apasionado de la ciencia que no
comprende, anticlerical con fanatismo, y asceta. Se encontrará
también en Aún tres muertos, o en Lo divino y lo humano,
(traducción francesa publicada en el volumen intitulado Los
Revolucionarios, 1906) algunos especímenes de la nueva
generación revolucionaria: Romana y sus amigos, que desprecian
a los antiguos terroristas y pretenden llegar científicamente a los
fines que persiguen, transformando al pueblo agricultor en pueblo
industrial.
[767] Carta al japonés Izo-Abe, de fines de 1904.
(Correspondencia inédita.)
[768] Las palabras vivientes de L. N. Tolstoi, notas de Teneromo,
capítulo Socialismo, (publicado en traducción francesa en Los
Revolucionarios, 1906).
[769] Ibid.
[770] Conversación con Paul Boyer. (Le Temps, 4 de noviembre
de 1902).
[771] El Fin de un Mundo.
[772] “La más cruel de las esclavitudes está en ser privado de la
tierra; porque el esclavo que tiene un dueño, es esclavo de uno
solo; pero el hombre privado del derecho de la tierra es el esclavo
de todo el mundo”. (El Fin de un Mundo, capítulo VII).
[773] Rusia estaba, en efecto, en una situación especial, y si el error de Tolstoi ha
sido atribuir también esta situación al conjunto de los Estados europeos, no hay
que sorprenderse de que se haya mostrado principalmente sensible para los
sufrimientos que le tocaban más de cerca. Véase en El Gran Crimen, sus
conversaciones en el camino de Tula, con los campesinos, que carecían todos de
pan porque la tierra les faltaba, y que todos, en el fondo, esperaban que la tierra
viniese a sus manos. La población agrícola de la nación forma el 80 por ciento. Un
centenar de millares de hombres, dice Tolstoi, mueren de hambre a consecuencia
del embargo de la tierra por los propietarios rurales. Cuando se llega a hablarles,
como remedio de sus males, de la libertad de la prensa, de la separación de la
iglesia y el Estado, de la representación nacional, y aun de la jornada de ocho
horas, se burla uno de ellos impunemente.
“Quienes aparentan buscar, por todos los medios, el mejoramiento de la situación
de las masas populares, recuerdan lo que pasa en el teatro cuando todos los
espectadores ven perfectamente al actor que está oculto, en tanto que los otros
que toman parte en la representación y que también lo ven, fingen no verlo, y se
esfuerzan por distraer mutuamente su atención”.
No hay otro remedio que devolver la tierra al pueblo que trabaja; y, para la
resolución de esta cuestión agraria, Tolstoi preconiza la doctrina de Henry George
y su proyecto de un impuesto único sobre el valor del suelo. Éste es su Evangelio
económico, y sobre él vuelve incansablemente, y tanto se lo ha asimilado que a
menudo, en sus obras, emplea hasta frases enteras de Henry George.
[774] “La ley de no-resistencia al mal es la clave de la bóveda de
todo el edificio. Admitir la ley de la ayuda mutua, desconociendo
el precepto de la no-resistencia, equivale a construir la bóveda sin
cerrarla en su parte central”. (El Fin de un Mundo.)
[775] En una carta de 1900, a un amigo (Correspondencia
inédita, página 312), Tolstoi se queja de la falsa interpretación
dada a su principio de la no-resistencia. Se confunde, dice: No te
opongas al mal haciendo el mal... con No te opongas al mal, es
decir, con: “Sé indiferente al mal...”. “Cuando la lucha contra el
mal es el único objeto del cristianismo y el mandamiento de la
no-resistencia al mal se da como el medio de lucha más eficaz”.
[776] El Fin de un Mundo.
[777] Tolstoi retrató dos tipos de estos “sectarios”, uno al final de
Resurrección, otro en Aún tres muertos.
[778] Después de que Tolstoi condenó la agitación de los
zemstvos, Gorki interpretaba el descontento de sus amigos,
escribiendo: “Este hombre se ha convertido en el esclavo de su
idea. Largo tiempo hace que se aísla de la vida rusa y ya no
escucha la voz del pueblo. Se coloca a demasiada altura, por
encima de Rusia”.
[779] Era para él un sufrimiento agobiador no poder ser
perseguido. Tenía sed de martirio; pero el gobierno, muy
prudente, se cuidaba bien de darle esa satisfacción. “En torno
mío se persigue a mis amigos y se me deja tranquilo, aun
cuando, si alguno hay perjudicial, soy yo. Evidentemente no valgo
bastante para ser perseguido, y de ello tengo vergüenza”. (Carta
a Teneromo, de 1892, Correspondencia inédita, página 184). “Es
evidente que no soy digno de sufrir persecuciones, y me será
preciso morir así, sin haber podido, por los sufrimientos físicos,
dar testimonio de la verdad”. (A Teneromo, 16 de mayo de 1892.
Ibid. Página 186). “Me es penoso estar en libertad”. (A Teneromo,
1.º de junio de 1894. Ibid. Página 188). ¡Dios sabe, sin embargo,
que no daba motivo para eso! Insultaba a los czares, atacaba a la
patria “este horrible fetiche al cual los hombres sacrifican su vida,
y su libertad, y su razón”. (El Fin de un Mundo). Véase en Guerra
y Revolución, el resumen que hace de la historia de Rusia. Es una
galería de monstruos: “el chiflado Iván el Terrible, el borracho
Pedro I, la ignorante cocinera Catarina I, la prostituida Elizabeth,
el degenerado Pablo, el parricida Alejandro I” (el único para quien
Tolstoi tuvo, sin embargo, alguna secreta ternura), “el cruel e
ignorante Nicolás I, Alejandro II, poco inteligente, más malo que
bueno, Alejandro III, seguramente un tonto, brutal e ignorante;
Nicolás II, un inocente oficial de húsares; rodeado de bribones,
un joven que no sabe nada, que no comprende nada”.
[780] Carta a Gontcharenko, refractario, del 19 de enero de 1905.
(Correspondencia inédita, página 264).
[781] A los dukhobors del Cáucaso, 1897. (Ibid. Página 239).
[782] Carta a un amigo, 1900. (Ibid. Páginas 308-309).
[783] A Gontcharenko, 12 de febrero de 1905. (Ibid. Página 265).
[784] A los dukhobors del Cáucaso, 1897. (Ibid. Página 240).
[785] A Gontcharenko, 19 de enero de 1905. (Ibid. Página 264).
[786] A un amigo, noviembre de 1901. (Ibid. Página 326).
[787] “Es como una hendidura en la máquina neumática; todo el
soplo de egoísmo que se quería aspirar del alma humana, vuelve
a entrar a ella”. Y emplea todo su ingenio en demostrar que el
texto original ha sido leído mal y que las palabras exactas del
segundo Mandamiento eran: “Ama a tu prójimo como a Él mismo
(como a Dios”). (Conversaciones con Teneromo).
[788] Conversaciones con Teneromo.
[789] Carta a un chino, octubre de 1906. (Correspondencia
inédita, página 381 y siguientes).
[790] Tolstoi expresaba ya este temor en su carta de 1906.
[791] “No vale la pena negarse al servicio militar y policíaco, para
admitir la propiedad, que se sostiene solamente por el servicio
militar y de policía. Los hombres que llenan este servicio y sacan
provecho de la propiedad obran mejor que aquéllos que se
niegan a todo servicio y gozan de la propiedad”. (Carta a los
dukhobors del Canadá, 1899. Correspondencia inédita, páginas
248-260).
[792] Léase en Las Conversaciones con Teneromo la hermosa
página “sobre el sabio judío que, sumergido en su libro, no ha
visto los siglos derrumbarse sobre su cabeza y los pueblos que
aparecían y desaparecían de la tierra”.
[793] “Ver el progreso de Europa en los horrores del Estado
moderno, el Estado sangrante, querer crear un nuevo Judenstaat,
es un pecado abominable” (Ibid.).
[794] Llamamiento a los políticos, 1905.
[795] Se encontrará en el Apéndice de El Gran Crimen y en la
traducción francesa de los Consejos a los Dirigidos (título ruso: Al
pueblo trabajador), un Llamamiento de una sociedad japonesa
para el Restablecimiento de la Libertad de la Tierra.
[796] Carta a Paul Sabatier, 7 de noviembre de 1906.
(Correspondencia inédita, página 375).
[797] Cartas a un amigo, junio de 1892 y noviembre de 1901.
[798] Guerra y Revolución.
[799] Carta a un amigo. (Correspondencia inédita, páginas 354-
55).
[800] Ibid. Acaso se trata aquí de la Historia de un Dukhobor,
cuyo título figura en la lista de las obras inéditas de Tolstoi.
[801] “Imaginad que todos los hombres que poseen la verdad se
reuniesen para vivir juntos y se instalasen en una isla: ¿Sería esto
la vida?” (A un amigo, marzo de 1901, Correspondencia inédita,
página 325).
[802] 1.º de diciembre de 1910.
[803] 16 de mayo de 1892. Tolstoi veía entonces a su mujer sufrir
por la muerte de un niño, y nada podía hacer para consolarla.
[804] Carta de enero de 1883.
[805] “No reprocharé jamás a nadie que no tenga religión. El mal
está en que los hombres mienten, fingiendo tener esa religión”. Y
más adelante: “Que Dios nos libre de fingir amor porque esto es
peor que el odio”. (Correspondencia inédita, páginas 344 y 348).
[806] Revue des Deux Mondes, 15 de diciembre de 1910.
[807] Revue des Deux Mondes, 15 de diciembre de 1910.
[808] A un amigo, 10 de diciembre de 1903.
[809] Le Figaro, 27 de diciembre de 1910. La carta, después de la
muerte de Tolstoi, fué entregada a la condesa por su yerno, el
príncipe Obolensky, a quien Tolstoi la había confiado algunos años
antes. A esta carta se unía otra, igualmente dirigida a la condesa
y que trataba de asuntos íntimos de la vida conyugal. La condesa
la destruyó después de haberla leído. (Nota comunicada por
Taciana Sukhotin, hija mayor de Tolstoi).
[810] Este estado de sufrimiento databa, pues, de 1881, es decir,
del invierno pasado en Moscú y del descubrimiento que entonces
hizo Tolstoi de la miseria social.
[811] Carta a un amigo (la traducción francesa, hecha por M.
Halpérine-Kaminsky, ha sido publicada con el título de Profesión
de fe en el volumen Placeres Crueles, 1895).
[812] Parece que sufrió en sus últimos años y sobre todo en sus
últimos meses, la influencia de Vladimir-Grigoritch Tchertkov,
amigo devoto que, establecido largo tiempo en Inglaterra, había
consagrado su fortuna a publicar y divulgar la obra íntegra de
Tolstoi. Tchertkov fué atacado violentamente por uno de los hijos
de Tolstoi, León; pero si se ha podido acusar su intransigencia de
espíritu, nadie ha puesto en duda su absoluta consagración; y, sin
aprobar la dureza, acaso inhumana, de algunos actos de los
cuales se cree advertir su inspiración (como el testamento por el
cual Tolstoi privó a su mujer de la propiedad de todos sus
escritos, sin excepción, comprendidos en ellos sus cartas
privadas), es posible creer que estuvo más enamorado de la
gloria de su amigo que el mismo Tolstoi.
[813] La Correspondencia de La Unión para la Verdad, en su
número de 1.º de enero de 1911, publicó una interesante relación
de esta fuga. Tolstoi bruscamente partió de Yasnaia Poliana el 28
de octubre de 1910 (10 de noviembre), hacia las cinco de la
mañana. Lo acompañaba el doctor Makovitski. Su hija Alejandra,
que Tchertkov llama su “colaboradora más íntima”, estaba en el
secreto de la partida. Llegó el mismo día, a las seis de la tarde, al
monasterio de Optina, uno de los más célebres santuarios de
Rusia, donde había estado varias veces en peregrinación; allí
pasó la noche y, a la mañana siguiente, escribió allí mismo un
largo artículo sobre la pena de muerte. En la tarde del 29 de
octubre (11 de noviembre), fué al monasterio de Chamordino,
donde su hermana María era monja; comió con ella y le comunicó
el deseo que habría tenido de pasar el fin de su vida en Optina,
“encargándose de desempeñar las más humildes labores, pero
con la condición de que no se le obligase a ir a la iglesia”. Durmió
en Chamordino; hizo, en la mañana siguiente, un paseo a la aldea
vecina, donde pensaba tomar alojamiento, y volvió a ver a su
hermana en la tarde. A las cinco llegó inopinadamente su hija
Alejandra, quien sin duda le previno que su fuga era conocida y
que habían salido en su seguimiento; y se pusieron en camino, en
el acto, de noche. “Tolstoi, Alejandra y Makovitski se dirigieron
hacia la estación de Koselsk, probablemente con la intención de
ganar las provincias del Sur, quizás las colonias formadas por los
dukhobors en el Cáucaso”. En el camino, Tolstoi enfermó y hubo
de ponerse en cama en la estación de Astapovo. Fué allí donde
murió.
[814] Diario, fecha de 28 de octubre de 1879. (Traducción de
Bienstock. Véase Vida y Obra). He aquí el pasaje entero, que es
uno de los más bellos: “Hay en este mundo gentes pesadas, sin
alas, que se agitan abajo. Entre ellas hay algunos fuertes como
Napoleón. Dejan rastros terribles entre los hombres, siembran la
discordia y arrasan siempre la tierra. Hay hombres que se dejan
crecer las alas, se lanzan lentamente y flotan, como los monjes.
Hay hombres ligeros, que se levantan fácilmente y vuelven a caer,
los buenos idealistas. Y hay hombres de alas poderosas... Hay
hombres celestes que, por amor a los hombres, descienden sobre
la tierra replegando sus alas, y enseñan a los otros a volar.
Después, cuando ya no son necesarios, remontan el vuelo, como
Cristo”.
[815] “Se puede vivir solamente mientras que se está ebrio de
vida” (Confesiones 1879). “Estoy loco de la vida... Es el estío, el
estío delicioso. Este año he luchado por largo tiempo; pero la
belleza de la Naturaleza me ha vencido. Me regocijo con la vida”.
(Carta a Fet, julio de 1880). Estas líneas fueron escritas en plena
crisis religiosa.
[816] En su Diario, fechado en octubre de 1865: “El pensamiento
de la muerte...”. “Yo quiero y amo la inmortalidad”.
[817] “Me embriagaba con esta cólera hirviente de indignación,
que amo en mí, que aun la excito cuando la siento, porque obra
sobre mí de manera calmante, y me da, por algunos instantes al
menos, una elasticidad extraordinaria, la energía y el fuego de
todas las capacidades físicas y morales”. (Diario del Príncipe D.
Nekhludov, Lucerna, 1857).
[818] Su artículo sobre la Guerra, a propósito del Congreso
Universal de la Paz, en Londres, en 1891, es una ruda sátira
contra los pacifistas, que creen en el arbitraje entre las naciones.
“Es la historia del pájaro al cual se coge después de haberle
puesto un grano de sal sobre la cola”. Es tan fácil de cogerlo
después de todo. Equivale a burlarse de las gentes hablarles de
arbitraje y de desarme consentido por los Estados. ¡Charlatanería
todo eso! Naturalmente los gobiernos aprueban: ¡los buenos
apóstoles! Saben bien que esto no les impedirá nunca enviar
millones de gentes al matadero, cuando les plazca hacerlo. (El
reino de Dios está en nosotros, capítulo VI).
[819] La Naturaleza fué siempre “el mejor amigo” de Tolstoi,
como se complacía en decirlo: “Un amigo, está bien; pero morirá,
se irá a cualquier parte y no se le podrá seguir, en tanto que la
naturaleza, a la cual estamos unidos por acto de venta y la
poseemos por herencia, es mejor. Mi naturaleza es fría, repulsora,
exigente, estorbosa; pero es un amigo que se conservará hasta la
muerte, y cuando muramos entraremos en ella”. (Carta a Fet, de
19 de mayo de 1861. Correspondencia inédita, página 31).
Participaba de la vida de la naturaleza, renacía en cada
primavera: “Marzo y abril son mis mejores meses para el trabajo”.
(A Fet, el 23 de marzo de 1877). Lo amodorraba el fin del otoño:
“Es para mí la estación más muerta, no pienso en nada, no
escribo nada, me siento agradablemente estúpido”. (A Fet, el 21
de octubre de 1869). Pero la naturaleza que hablaba íntimamente
a su corazón, era la naturaleza que lo circundaba, la de Yasnaia
Poliana. Aun cuando, en el curso de su viaje a Suiza, haya escrito
notas muy hermosas sobre el lago de Ginebra, allí se sentía
extranjero, y su unión con la tierra natal le parecía entonces más
estrecha y más dulce: “Amo a la naturaleza, cuando por todas
partes me rodea, cuando por todas partes me envuelve el aire
cálido que se derrama hasta la lejanía infinita, cuando esta misma
yerba jugosa que he chafado al sentarme viste de verdura los
campos infinitos; cuando estas mismas hojas que, agitadas por el
viento, brindan sombra a mi rostro, se unen para formar el
sombrío azul de la floresta lejana; cuando este mismo aire que
respiro forma el azul claro del cielo infinito: cuando estoy solo
para gozar de la naturaleza, cuando, en torno mío, revuelan y
zumban millones de insectos y cantan los pájaros. El gozo
principal de la naturaleza está para mí en cuanto me siento
formar parte de toda ella. Aquí (en Suiza) las infinitas lejanías son
hermosas, pero estoy desligado de ellas”. (Mayo de 1857).
[820] Conversaciones con Paul Boyer. (Le Temps, 28 de agosto de 1901). De
hecho podría uno confundirlas a menudo, como en esta profesión de fe de Julia
moribunda:
“Lo que me era imposible creer, nunca he podido decir que lo creía; y siempre he
creído lo que decía creer. Era todo lo que podía hacer”.
Que puede relacionarse con la carta de Tolstoi al Santo Sínodo:
“Es posible que mis creencias molesten o desagraden; pero no me es posible
cambiarlas, como no me es posible cambiar de cuerpo. No puedo creer otra cosa
que lo que creo en esta hora en que me dispongo a volver hacia el Dios de quien
procedo”.
O bien con este pasaje de la Respuesta a Cristóbal de Beaumont, que nos parece
ser toda Tolstoi:
“Soy discípulo de Jesucristo, y mi Maestro ha dicho que quien ama a su hermano
cumple la ley”.
O todavía:
“Toda la oración dominical, íntegra, está contenida en estas palabras: ¡Cúmplase
tu voluntad!” (Tercera carta de la montaña.)
En relación con:
“Reemplazo todas mis plegarias con el Pater Noster. Todas las peticiones que yo
puedo dirigir a Dios están expresadas con mayor altura moral por estas palabras:
¡Cúmplase tu voluntad!” (Diario de Tolstoi, en el Cáucaso, 1852-53).
La semejanza de pensamientos no es menos frecuente en el terreno del arte que
en el de la religión:
“La primera regla del arte de escribir, dice Rousseau, consiste en hablar con
claridad y expresar con exactitud nuestro pensamiento”.
Y Tolstoi:
“Pensad lo que queráis, pero de tal manera que cada palabra pueda ser
comprendida por todos. No es posible escribir nada mal en una lengua que sea
perfectamente clara”.
He demostrado antes que las descripciones satíricas de la Opera de París, en La
Nueva Eloísa, tienen muchas relaciones con las críticas de Tolstoi en ¿Qué es el
Arte?
[821] Diario, 6 de enero de 1903 (citado en el Prefacio de Tolstoi
a sus Recuerdos, volumen primero de Vida y Obra de Tolstoi,
publicados por Birukov).
[822] Cuarto Paseo.
[823] Carta a Birukov.
[824] Sebastopol en mayo de 1855.
[825] “La verdad... la única cosa que me ha quedado de mi
concepción moral, la única cosa que cumpliré todavía”. (17 de
octubre de 1860).
[826] Ibid.
[827] “El amor a los hombres es el estado natural del alma, y
nosotros no lo advertimos”. (Diario, en la época que fué
estudiante en Kazan).
[828] “La verdad se abrirá para el amor...”. (Confesiones, 1879-
81). “Yo, que situaba a la verdad en la unidad del amor...”. (Ibid.)
[829] “¿Me habláis siempre de energía? Pero la base de la
energía está en el amor, dijo Ana, y el amor no se da nunca a
voluntad”. (Ana Karenina, II, página 270).
[830] “La belleza y el amor, estas dos razones de vivir”. (La
Guerra y la Paz, II, página 285).
[831] “Creo en Dios, que es para mí el Amor”. (Carta al Santo
Sínodo, 1901). “¡Sí, el amor!... No el amor egoísta, sino el amor
tal como yo lo he experimentado, por la primera vez en mi vida,
cuando vi a mi lado a mi enemigo moribundo, y lo amé... Es la
esencia misma del alma. Amar a su prójimo, amar a sus
enemigos, amar a todos y cada uno, ¡eso es amar a Dios en
todas sus manifestaciones!... Amar a un ser que nos es grato, es
amor humano; pero amar al enemigo, ¡esto casi es amor
divino!...”. (El Príncipe Andrés, moribundo, en La Guerra y la Paz,
III, página 176).
[832] “El amor apasionado del artista por su asunto, es el corazón
del arte. Sin amor no hay obra de arte posible”. (Carta de
septiembre de 1889. “Leo Tolstois Briefe 1848 bis 1910”, Berlín,
1911).
[833] “Porque yo escribo libros, sé todo el mal que ellos hacen...”.
(Carta de Tolstoi a P. V. Vériguine, jefe de los dukhobors, de 21 de
noviembre de 1897. Correspondencia inédita, página 241).
[834] Véase La Mañana de un Señor, o bien, en Las Confesiones,
los retratos extremadamente idealizados de estos hombres
sencillos, buenos, contentos de su suerte, tranquilos, que
comprenden la vida; o bien, al fin de la segunda parte de
Resurrección, esta visión “de una humanidad, de una tierra
nueva”, que aparece a Nekhludov, cuando encuentra a los obreros
que vuelven de su trabajo.
[835] “Un cristiano no podría ser moralmente superior o inferior a
otro; pero es más cristiano a medida que más rápidamente
avanza en la vida de la perfección, cualquiera que sea el grado en
el cual se encuentre, en un momento dado: de suerte que la
virtud estacionaria del fariseo es menos cristiana que la del
ladrón, cuya alma esté en pleno movimiento hacia lo ideal, y que
se arrepiente sobre su cruz”. (Placeres Crueles. Traducción de
Halpérine-Kaminsky).
APÉNDICE
(Nota a la página 394).

LAS OBRAS PÓSTUMAS DE TOLSTOI[836].


Tolstoi dejaba al morir una gran cantidad de obras inéditas, de las
cuales la mayor parte ha sido publicada después y forman tres
volúmenes en la traducción francesa de J. W. Bienstock (Colección
Nelson).
Estas obras son de todas las épocas de su vida, habiendo algunas
que remontan hasta 1883 (Diario de un Loco), y otras de los últimos
años. Comprenden cuentos, novelas, obras teatrales y diálogos, y
muchas que quedaron sin acabar. Yo las dividiría, de buena gana, en
dos clases: las obras que Tolstoi escribió por voluntad moral y las
que escribió por instinto artístico. En un corto número de ellas,
armoniosamente se funden las dos tendencias.
Por desgracia hay que deplorar que su desinterés de la gloria
literaria—acaso también un secreto propósito de mortificación—
hayan impedido a Tolstoi proseguir la composición de las obras que
se anunciaban como las más hermosas. En este número citaremos El
Diario Póstumo del Viejo Feodor Kuzmitch. Es ésta la famosa leyenda
del Zar Alejandro I, que haciéndose pasar por muerto y
marchándose, con un falso nombre, envejeció en Siberia por
expiación voluntaria. Se advierte que Tolstoi estaba enamorado de
este asunto e identificado con su héroe, y no podemos consolarnos
con que sólo nos queden de este “diario” los primeros capítulos. Por
el vigor y la frescura del relato, valen estos capítulos tanto como las
mejores páginas de Resurrección. En ellos hay retratos inolvidables
(la vieja Catarina II) y principalmente una primorosa pintura del Zar,
místico y violento, cuya naturaleza orgullosa tiene todavía
sobresaltos de despertar en el anciano tranquilo.
El padre Sergio (1891-1904) pertenece también a la mejor manera
de Tolstoi; pero la narración está un poco cortada. Tiene por asunto
la historia de un hombre que busca a Dios en la soledad y el
ascetismo, por orgullo herido, que acaba por encontrarlo entre los
hombres, viviendo para ellos. La salvaje violencia de algunas páginas
conmueve hasta hacer un nudo en la garganta. Nada de más sobrio
y trágico que la escena en que el héroe descubre la villanía de
aquélla a quien amaba; su prometida, la mujer a quien adoraba
como a una santa, ha sido amante del Zar, que era por él venerado
apasionadamente. No menos conmovedora es la noche de tentación,
en que el monje, para recobrar la paz del alma turbada, se corta un
dedo con un hacha. A estos episodios feroces se opone la
conversación melancólica del final, con la pobre viejecita amiga de la
infancia, y las últimas páginas que son de un laconismo indiferente y
sereno.
El asunto de La Madre es también emocionante. Una buena y
razonable madre de familia, que después de haberse consagrado
enteramente a los suyos durante cuarenta años, se encuentra sola,
sin actividad, sin razón de vivir, y, aunque es librepensadora, se
acoge al abrigo de un convento y escribe allí su Diario. Pero de esta
obra solamente quedaron las primeras páginas.
De un arte superior son una serie de pequeños relatos: Alexis el
Tonto, que participa de la vena de los hermosos cuentos populares,
es la historia de un espíritu simple, siempre sacrificado, siempre
dulcemente satisfecho, y que así muere. Después del Baile (20 de
agosto de 1903), en que un anciano cuenta cómo amó a una
muchacha y cómo cesó bruscamente de amarla, después de haber
visto al padre de ella, un coronel, ordenar que fuera azotado un
soldado; obra perfecta, primero, de un exquisito encanto de
recuerdos juveniles y luego de una alucinante precisión. Lo que yo
he visto en sueños (13 de noviembre de 1906): Un príncipe no
perdona a su hija, a quien adoraba, porque se ha escapado de la
casa después de dejarse seducir; pero apenas vuelve a verle, es él
quien le pide perdón; y sin embargo (la ternura de Tolstoi y su
idealismo no lo engañan nunca), no puede alcanzar a vencer el
sentimiento de disgusto que le causa la vista del hijo de su hija.
Khodynka, novela corta cuya acción pasa en 1893: se trata de una
joven princesa rusa que ha querido tomar parte en una fiesta
popular de Moscú, y se encuentra, presa de un gran pánico,
pisoteada, medio muerta, y reanimada por un obrero que ha sido él
mismo rudamente atropellado. Por un instante un sentimiento de
fraternidad afectuosa los une; se separan después y no volverán a
verse más.
De dimensiones más vastas y que anuncian una novela épica, es
Hadji-Mourad (diciembre de 1902), que refiere un episodio de las
guerras del Cáucaso en 1851[837]. Tolstoi, al escribirla, se
encontraba en la plena posesión de sus procedimientos artísticos. En
ella la visión (de los ojos y del alma) es perfecta; pero, y esto es
curioso, no llegamos a interesarnos verdaderamente en la historia,
porque se advierte que Tolstoi mismo no se interesa en ella. Cada
personaje que aparece en el curso de la narración, despierta en él la
misma simpatía, y de cada uno, aunque no haga más que pasar
delante de nuestros ojos, hace un retrato acabado; pero a fuerza de
amar a todos no prefiere a ninguno. Parece que escribió este notable
cuento sin ninguna necesidad interior y sólo por necesidad física;
pues como otros ejercitan sus músculos, es necesario que él
ejercitara su mecanismo intelectual; tenía necesidad de crear;
creaba.

Otras obras tienen un acento personal que llega a menudo hasta la


angustia. Algunas son autobiográficas, como el Diario de un Loco
(20 de octubre de 1883), que contiene el recuerdo de las primeras
noches de espanto de Tolstoi, antes de la crisis de 1869;[838] y como
El Diablo (19 de noviembre de 1889). Este último y largo cuento
tiene dos partes, que son de primer orden sin duda y, por desgracia,
un desenlace absurdo: un propietario rural que tiene relaciones con
una joven campesina que vive en sus propiedades, se casa y cuida,
porque es honesto y ama a su mujer, de alejar a esta campesina;
pero ella se le ha metido por los ojos, y no puede mirarla sin
desearla. La busca, y acaba por recobrarla; siente que no podrá ya
separarse de ella, y se mata. Los retratos de este hombre, bueno,
débil, robusto, miope, inteligente, sincero, trabajador y
atormentado; de su joven mujer, romántica y enamorada, que lo
idealiza, y de la hermosa y sana campesina, ardorosa y sin pudor,
son obras maestras. Es chocante que Tolstoi haya puesto tanto de
intención moral en el fin del cuento, como no lo puso en la historia
vivida, porque él tuvo realmente una aventura análoga.
La luz brilla en las tinieblas, drama en cinco actos, ofrece muchas
debilidades artísticas; pero, cuando se conoce la tragedia oculta de
la vejez de Tolstoi ¡qué conmovedora es esta obra que, con otros
nombres, presenta en escena a Tolstoi y a los suyos! Nicolás
Ivanovitch Sarintzeff llega a tener la misma fe que el autor de ¿Qué
debemos hacer?, y ensaya ponerla en práctica, lo cual no le está
permitido. Las lágrimas de su mujer (¿sinceras o simuladas?) le
impiden abandonar a los suyos; se queda en su casa, donde vive
pobremente, trabajando en la carpintería; su mujer y sus hijos
continúan haciendo vida de lujo y dando fiestas, y aunque él no
toma parte en ellas, se le acusa de hipocresía. Sin embargo, por su
influencia moral, por la simple radiación de su personalidad, hace en
torno suyo prosélitos y desventurados. Un “pope”, convencido por
sus doctrinas, abandona la iglesia; un joven de buena familia rehúsa
prestar el servicio militar y se hace enviar al batallón de disciplina; y
mientras tanto, el pobre Sarintzeff-Tolstoi es desgarrado por la duda.
¿Está en el error? ¿No arrastra inútilmente a los otros al sufrimiento
y a la muerte? Al fin no encuentra otra solución a sus angustias que
dejarse matar por el joven a quien sin querer condujo a la pérdida.
Se encuentra también, en una breve narración de los últimos
tiempos de la vida de Tolstoi, No hay culpable (septiembre de 1910),
la misma confesión dolorosa de un hombre que sufre horriblemente
por su situación, de la cual no puede salir. A los ricos ociosos se
oponen los pobres abrumados de trabajo, y ni los unos ni los otros
sienten la inepcia monstruosa de semejante estado social.
Dos obras de teatro tienen un alto valor; una es la obrita campesina
que combate los daños del alcohol, intitulada Todas las cualidades
vienen de ella (probablemente de 1910). Los personajes son muy
individuales y sus rasgos típicos y su ridículo lenguaje fueron
sorprendidos de manera muy divertida; el campesino que, a la
postre, perdona a un ladrón, es a la vez noble y cómico por su
inconsciente grandeza moral y por su ingenuo amor propio. La
segunda de estas piezas, de una importancia muy distinta, es un
drama en doce cuadros, El cadáver viviente, que muestra a gentes
débiles y buenas aplastadas por la estúpida máquina social. El
héroe, Fedia, es un hombre que se ha perdido por su bondad misma
y por el profundo sentimiento moral que oculta bajo una vida de
libertino, porque sufre de una manera intolerable con la bajeza del
mundo y con su propia indignidad; pero no tiene la fuerza necesaria
para reaccionar. Tiene una mujer a quien ama, que es buena,
tranquila, razonable, pero “sin la uva que se pone en la sidra para
hacerla espumar”, “sin el burbujeo en la vida” que procura el olvido.
Y el olvido le es indispensable.
“Nosotros todos, en nuestro medio, dice, tenemos delante tres
caminos, y únicamente tres. Ser funcionario, ganar dinero y sumar
más villanía a la del medio en el cual vivimos. Y esto me disgusta;
tal vez yo no sería capaz de hacerlo... El segundo camino es aquél
en el cual se combate esta villanía, pero para esto es necesario ser
un héroe, y yo no lo soy. Queda el tercero: olvidarse, beber,
engañarse en fiestas, cantar; este es el camino que yo he escogido,
y ya veis vosotros a dónde me ha conducido...”[839].
Y en otro pasaje:
“¿Cómo he llegado a perderme? Desde luego, por el vino. No es que
yo sienta placer en beber; pero he tenido siempre el sentimiento de
que todo lo que se hace en torno mío no es lo que debía hacerse; y
siento vergüenza... Y en cuanto a ser de la nobleza, o director de
banco, ¡eso sí que es vergonzoso, muy vergonzoso!... Después de
haber bebido ya no tiene uno vergüenza... Y luego, la música, pero
no de ópera o de Beethoven, sino la de los zíngaros, esa que os
derrama en el alma tanta vida, tanta energía... Luego, los bellos ojos
negros, las sonrisas... Pero mientras más os encanta todo eso, más
se siente la vergüenza, y después...”.[840]
Ha abandonado a su mujer porque comprende que él le hace mal a
ella y que ella no le hace a él ningún bien; la deja con un amigo de
quien ella es amada y al que también ella ama, sin confesárselo, y
que se parecen. Desaparece en los bajos fondos de la bohemia, y
todo así se resuelve bien; los otros dos son felices, y él, en la
medida en que puede serlo. Pero la sociedad no permite que nadie
obre sin su consentimiento, y reduce estúpidamente a Fedia al
suicidio, si no quiere que sus dos amigos sean condenados por
bigamia. Esta extraña obra, tan profundamente rusa y que refleja el
desaliento de los mejores después de las grandes esperanzas de la
revolución, que fueron destrozadas, es sencilla, sobria, sin ningún
efecto declamatorio. Todos los caracteres son verdaderos y vivientes,
aun los de los personajes que aparecen en segundo plano, como la
joven hermana, intransigente y apasionada en su concepción moral
del amor y del matrimonio; la buena figura acompasada del bravo
Karenin, y la vieja mamá, petrificada en sus nobles prejuicios,
conservadora, autoritaria en sus palabras, acomodaticia en sus
actos; y aun podría decirse lo mismo de las siluetas fugitivas de los
zíngaros y de los abogados.

No he citado algunas obras cuya intención dogmática y moral


domina la vida libre del arte, aun cuando jamás haga tropezar a
Tolstoi en su lucidez psicológica.
El falso cupón es un largo relato, casi una novela, que trata de
demostrar el encadenamiento, en el mundo, de todos los actos
individuales, buenos y malos. Una falsificación cometida por dos
colegiales desencadena toda una serie de crímenes, de más en más
horribles, hasta que el acto de la resignación santa de una pobre
mujer asesinada por una salvaje, conmueve al asesino y, por ella, de
uno en otro, se llega hasta los primeros autores de todo el mal,
quienes por esta manera se encuentran así salvados por sus
víctimas. El tema es soberbio y toca en epopeya; la obra habría
podido levantarse hasta la fatal grandeza de las tragedias antiguas;
pero la narración es demasiado larga, muy cortada, sin amplitud, y
aun cuando cada personaje esté justamente caracterizado, todos
resultan indiferentes.
La cordura infantil es una serie de veintiún diálogos entre niños
sobre todos los grandes temas, religión, arte, ciencia, instrucción,
patria, etc., que no carecen de vigor imaginativo, pero en los cuales
el procedimiento seguido fatiga pronto por repetirse tan a menudo.
El joven zar, que medita en las desventuras que causa a pesar suyo,
es una de las obras más débiles de la recopilación. En fin, me
contentaré con enumerar algunos de estos bosquejos fragmentarios:
Dos peregrinos, El pope Vasili, ¿Quiénes son los asesinos?, etc.

En el conjunto de estas obras sorprende el vigor intelectual


conservado por Tolstoi hasta su último día[841]. Puede parecer
verboso cuando expone sus ideas sociales; pero siempre que está
frente a una acción, de algún personaje viviente, el soñador
humanitario desaparece y no queda más que el artista de mirada de
águila, de mirada que va recto al corazón. Nunca perdió esta lucidez
soberana; el único empobrecimiento que yo advierto, en cuanto al
arte, viene del lado de la pasión. Aparte de cortos instantes, se tiene
la impresión de que ya no son para Tolstoi sus obras lo esencial en
su vida, que son o bien un pasatiempo necesario, o bien un
instrumento para la acción; porque es la acción su verdadero objeto,
y ya no el arte. Cuando ocurre que se deja recobrar por esta ilusión
apasionada, parece que de ella tuviera vergüenza; corta pronto por
lo sano, o acaso, como en el Diario póstumo del viejo Feodor
Kusmitch, abandona completamente la obra que lo ponía en peligro
de volver a unir las cadenas que lo ligaban al arte... Ejemplo único
de un gran artista, en plena fuerza creadora y por ella atormentado,
que la resiste y que la inmola a su Dios.
NOTAS:
[836] Mme. Tatiana Soukhotine, hija mayor de Tolstoi, me ha
hecho observar que la verdadera ortografía del nombre de Tolstoi,
en francés, es con una y. Así aparece efectivamente la firma de
Tolstoi en una carta que recibí de él.
[837] “Del cual fuí testigo, en parte”, escribía Tolstoi.
[838] Véase en la página 328.
[839] Acto V, cuadro I.
[840] Acto III, cuadro II.
[841] Esta salud de espíritu se manifiesta en las narraciones que
fueron hechas por Tchertkov y por el testimonio de los médicos
en la última enfermedad de Tolstoi. Casi hasta el fin continuó
escribiendo o dictando su Diario.
SE ACABÓ DE IMPRIMIR EN LOS TALLERES
DEL DEPARTAMENTO EDITORIAL
DE LA SECRETARÍA DE EDUCACIÓN PÚBLICA
EL 13 DE SEPTBRE. DE 1923,
EN MÉXICO.
*** END OF THE PROJECT GUTENBERG EBOOK VIDAS
EJEMPLARES: BEETHOVEN—MIGUEL ÁNGEL—TOLSTOI ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™

You might also like