100% found this document useful (1 vote)
56 views

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

way

Uploaded by

zoniasphine29
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
56 views

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

way

Uploaded by

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

Visit https://ebookultra.

com to download the full version and


explore more ebooks

Java the UML way integrating object oriented design


and programming Else Lervik

_____ Click the link below to download _____


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

Explore and download more ebooks at ebookultra.com


Here are some recommended products that might interest you.
You can download now and explore!

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): cs-books@wiley.co.uk
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.
Discovering Diverse Content Through
Random Scribd Documents
Biró kiüritette a nadrágzsebeit is. Tizenhét darab aranya volt,
mint később kiderült.
Masa grófnő leült, s az asszonyok hatodik érzékével azonnal
kitalálta, hogyan lehet a legcsunyábban játszani. Mint a félénk
játékosok legtöbbnyire, egy-egy számoszlopra tett, még pedig nem
mindig, hanem lesve a valószinüséget, mint azok a lutrizó
kávénénikék, a kik az évek óta ki nem jött számokon csüggenek
makacs, kitartó szerelemmel.
Ha nagy szerencséje talál lenni, nyerhetett volna még egyszer
annyit, mint a mennyit koczkáztatott. De nem volt szerencséje.
Elúszott a három első arany, aztán elúszott a negyedik és az
ötödik is. Majdnem megsiratta őket. És ettől fogva még
óvatosabban, még takarékosabban játszott.
Igazán, nagyon kedves volt.
Akárhányszor láttam házmester-kisasszonyokat – értekezett a
monte-carloi eset szemtanuja – a kik azelőtt soha még csak nem is
képzeltek egy rakáson száz forintot, s a kik két polka között, a bac
asztalnál, a legnagyobb hidegvérrel vesztették el az ebül szerzett
ezreket, s mondhatom, kedveseknek találtam azokat a tarka tollu kis
madarakat, a kik égi öntudatlansággal és derült szemtelenséggel
csipegetik fel az elibéjük került apró gyöngyszemeket.
De ezt a nábob-ivadékot, jó gazdasszony-rémületével, még
kedvesebbnek találtam, mint azokat a pompázó csatorna-virágokat.
Istenem, azt, hogy a szemétdomb koronkint megelevenedik, s
gőzeiből apró tündérek szállanak szerte, láthatjuk mindnyájan; s
mindennap látni azt is, hogy ezek a hegyes fogú kis tündérek »a
rágcsálók és őrlők« tökéletességével tudják megenni a
leghatalmasabb vagyonokat is. De olyan hölgyet, a ki minden
esztendőben épittet egy templomot, s a kinek legforróbb
vágyakozása, hogy vagy százhúsz frankkal lefőzze a monte-carloi
bankot, ilyen hölgyet még keveset láttam. Mondhatom, önöket is
mulattatta volna ez a ritka látvány.
Szóval oda gyökereztem a hátuk mögé, és nem bántam meg.
Biró mosolyogva nézte a feleségét, de meglátszott az arczán,
hogy nagyon szeretne odakünn lenni és szivarozni.
Az asszonyka végtelen komolysággal merült a számitgatásaiba,
de minél okosabb akart lenni, annál jobban vesztett; megpróbált
számsorra, megpróbált számnégyszögre játszani, hiába.
Elúszott bizony a tizenhetedik arany is.
– Tizenhét arany! – kiáltott fel olyan hangon, hogy a játék-terem
kalandokat leső vén hiénáiban édes reménységek kezdtek sarjadzani
(azt hitték, hogy mindenét elvesztette) – tizenhét arany! Egy egész
vagyont játszottam el!
– Hja, kedvesem – szólt Biró mosolyogva – a kit annyian és
annyira imádnak, mint önt, annak nem szabad játszania!
– Milyen ravaszság! – botránkozott az asszonyka. – Észrevette,
hogy most már magára kerülne a sor (mert nekem határozottan
szerencsétlen kezem van), s hogy megszabaduljon ettől a robottól,
nem átallja belekapaszkodni az özönviz előtti közmondásba,
csakhogy meg ne kérhessem rá… de azért is megkérem. Kedves,
kedves férjem-uram, nyerje vissza a pénzemet! Ugy-e, visszanyeri?
De megigéri, hogy ha száz frankot elveszit, nem játszik tovább?!…
– Szivesen – felelt Biró mosolyogva, és engedelmeskedett.
Igazán, ha véletlenül nem ismerem őket, azt hittem volna, hogy
az egész jelenetet kieszelték előre.
Biró úgy tett, mint a ki csak azért siet teljesiteni egy asszonyi
szeszélyt, hogy annál hamarabb véget vessen az egész
gyerekességnek, de engem nem csalt meg. Én arról a módról, a
hogy a száz frankját az asztalra vetette, rögtön fölismertem benne a
nagy játékost.
Ilyen lehet az a jelenet, mikor Plunkett kiveszi a Nancy ügyetlen
kis kezéből a gyeplőt és maga kezdi hajtani a lovakat. Előbb csak
támolygott a kocsi, a négy ló négy felé húzott; de a hogy megérzik a
mester kezét, a csengős, operett-lovak paripákká változnak át, s a
kocsi pokoli biztossággal repül előre, mint a Phaëton szekere.
A játék istene megérezte, hogy most az ő embere lépett az
asztalhoz, és úgy fogadta, a mint illik, hódolattal.
Bezzeg, nem krajczároskodott ez! Számra tett, mint az igaziak. A
kettesre játszott.
A gonosz szerszám perdült. Masának alig volt ideje, hogy
megkérdezze, mire tett az ura, már kiáltották:
– Kettő, fekete, páros, innen!
S még el se hangzott ez a pár szó, a háromezerötszáz frank már
ott hevert a száz frank fölött.
Más embernek ilyen esetekben az öreg napjai jutnak eszébe;
szükségét érzi annak, hogy félre tegyen, s nem tud okosabbat, mint
zsebre gyűrni a váratlan nyereséget, aztán szépen haza koczogni.
Azok már hősies jellemek, a kik a nyert pénzzel szinre vagy »innen«-
re-»túl«-ra játszanak tovább; olyat, ki teljes nyereségre
megismételje a tétjét s még egyszer számra játszszék: csak két
embert ismertem. Az egyik a szegény Barcsi volt, a ki, mint
emlékeznek, elrulettezte az egész örökségét, a másik Biró Jenő úr.
Csakhogy Biró Jenő úr nem pusztán a tétjét hagyta az asztalon,
hanem az egész nyereségét is. Voltak, a kik azt hitték, hogy hirtelen
megbolondult; s a közelben sokan megvárták ezt a nevezetes tétet,
csak azért, hogy az ellenkező esélyekre vessék magukat.
Biró Jenő úr a harminczasra tett. Mindenki a feketét, a
páratlanokat és az »innen«-t rakta.
– Nem lehet tenni többé!
Nem, nem volt megbolondulva. Olyan hideg és közönbös maradt,
mintha nem is őt érdekelte volna a legerősebben az a szeszélyesen
szaladgáló kis játékszer, melynek ugrándozását annyi szem kisérte.
Udvarolt a feleségének, pedig ennél az asztalnál az ég
leggyönyörűségesebb angyalainak se szoktak udvarolni.
Csak akkor fordult meg, mikor hallotta, hogy kiáltják:
– Harmincz, vörös, páros, túl!
Képzelhetik önök a meglepetést!
A mi pénz volt az asztalon, az természetesen mind hozzá
vándorolt. Ugy hiszem, a bank maga is megérezte ezt a kis érvágást.
Hozzá se nyúlt.
– Ez a harminczas nagyon derék szám – szólt a feleségéhez. –
Megérdemli, hogy még egyszer tegyünk rá.
Nem, ezt az őrült izgalmat nem tudják elképzelni. Akárhányszor
láttam, hogy egy-egy leégett játékos ott a teremben puffantotta
agyon magát, illedelmesen visszavonulva valamelyik sarokba;
mondhatom, a kutya se törődik velök. Láttam azt is, mikor miss
Moore, a kit önök mindnyájan ismertek, ott az asztalnál bolondult
meg, s kibontott ősz hajjal szaladgált a teremben, mint egy vén
Ophelia. Ezt már nézték, de nem sokáig, mert hamar kidobták
szegényt. Láttam végre, mikor Webb, kétszer egymásután fosztotta
ki a bankot. Ez már derekas izgalom volt. De ahhoz hasonló
jelenetet, a milyen ez után következett, úgy hiszem, ebben a
században már nem lát Monte-Carlo.
Egy ember, a ki csak számra játszik, a ki kétszer egymásután
nyert, s a ki másodszor tesz ugyanarra a számra, nem száz frankos,
hanem százezres tétet: ez az ember vagy kötöznivaló bolond… vagy
ez az ember nem ember, hanem maga az ördög.
Persze, hogy az ördög.
Nekem legalább a Mefistofele zenéje zúgott a fülemben, mikor a
kisértetes zörgésre következő pillanatnyi síri csöndet megtörte a
játékbank egyik tisztviselőjének a szava:
– Harmincz, vörös, páros, túl!
S mintha hallottam volna a basszista kaczagását.
Természetesen, nem tudták kifizetni. A banknak különben is rossz
napja volt; a pénzkészletből nem telt ki az óriási összeg.
Biró Jenő úrnak tehát várnia kellett, mig a főpénztárból elhozzák
a neki járó, és a játék folytatásához szükséges pénzösszeget. Elég
hamar megtörtént, de még sem oly gyorsan, mint Biró kivánhatta
volna. Nem kerülhette ki, hogy neki ne essenek. A babonások –
pedig ki nem babonás ebben a teremben? – megrohanták minden
oldalról. Könyörögtek neki, hogy tegyen még egyszer, legalább egy,
egyetlen egy aranyat; csak még egyszer, csak egy aranyat, hogy ész
nélkül kapaszkodhassanak bele a kabátjába.
– Nem – szólt Biró Jenő úr – egy aranyat se teszek többet.
Tessék elhinni, ő volt az egyetlen ember a teremben, a ki józan
maradt. Mi többiek, mindnyájan meg voltunk bolondulva.
Szentűl meg voltunk győződve, hogy ez után már világ végeztéig
mindig a harminczas fog nyerni.
A játék persze nem akadt fenn s a Biró vezérlete hiján a
harminczas számra vetettük magunkat. Én is elvesztettem egy
ezrest. A zéró jött ki.
– És Biró Jenő úr? – kérdezte valaki a monte-carlói úr hallgatói
közül.
– Biró Jenő úr úgy tett, a mint beszélt. Egy garast se tett többé;
nem tett egy szerencse-aranyat se. Karjára fűzte a feleségét, hátat
forditott a bűnbarlangnak és talán vissza se nézett. Bejárta San-
Remot, Bordigherát, Ospedalettit, Mentonet, s mindazt, a mit
érdemes megnézni, és nem törődött többé a játékteremmel, a mint
mi nem törődünk egy elhasznált keztyűvel.
A monte-carlói urat sokan hallgatták, a kik közül néhányan a sors
kiválasztottjai közé tartoztak. De ebben a sok fejben ugyanegy dolog
történhetett: mert mikor az elbeszélés véget ért, senki se szólt
semmit.
Ez annál nevezetesebb volt, mert sok emberen egy és ugyanaz az
érzés is különböző hatásokban szokott nyilvánulni. A fájdalom az
egyiket bőbeszédűvé, a másikat némává teszi, a szerelem hol
fecsegővé tesz, hol szótalanná, a harag néha tombol, néha magába
zárkózik. Csak egy érzés van, mely minden embert minden
körülmény között egyformán hallgataggá tesz: az irigység.
Az irigység igen rossz hírben álló érzelem, pedig ennek a sanda
czégnek sokkal nagyobb közönsége van, mint képzelné az ember. És
nincs az a bőség, a mely megóvjon a csábitásaitól.
A társaságban akárhány ember volt, a ki jóval nagyobb
vagyonnal rendelkezett, mint a mekkora a monte-carlói asztalnál
verődött össze, hogy megalapitani segitsen egy uj pénzkirályságot.
De, istenem, mekkora különbség a szerzésben! Mennyi ősre kellett
nekik szert tenniök, milyen gondosan kellett megválasztaniok a
szüleiket, mig ez az ember öt percznyi előkelő viselkedéssel ott van,
a hová ők csak annyi körültekintés után érkeztek!
Az izgalom is mámoritó lehetett, ha a nagy kalandor nyugalmat
szinlelt is. És ez a hatalmasan rideg kijelentés, hogy egy garast se
tesz többé! Ez az akaraterő, hogy a szerencse-aranyat sem adta ki a
kezéből! Bizonyára, ez az »egy aranyat sem« méltó rá, hogy helyet
foglaljon a történelem arany könyvében a mellett a nagy mondás
mellett, hogy: »Szó nélkül halál!«
Legelőször Simi gróf kapta vissza a szavát. Ő volt a legszűzibb
lélek a társaságban.

É
– És ha meggondolom – szólt – hogy nekem egy külvárosi
jelenetem van ettől az embertől, egy külvárosi jelenetem, a melyet
ötven forintért vásároltam!
– Az a külvárosi jelenet is abban a műhelyben készült, a melyből
a multkori Van Ostade került ki – felelt a monte-carlói úr.
Simi grófnak a képvásárlásban való szerencsétlensége
közmondásos volt. Külvárosi jelenetével is kinevették. Egy valódi
Birót nem vásárolnak ötven forintért.
VI.

Simi gróf meg volt sértve. Azért se hagyta a dolgot annyiban.


Megvizsgáltatta a képet egy szakértővel.
A szakértő megállapitotta, hogy a munka eredeti. Megjegyezte
ugyan, hogy a mester első korszakából való, de nem hunyhatott
szemet a fiatalkori mű szembeszökő szépségei előtt.
És hogy megerősitse az itéletét, nyomban felajánlott érte ezer
forintot.
Simi gróf néma megvetéssel felelt, s még az nap kiadta a
rendeletet, hogy vigyék át a képet az előszobából a nagy terembe.
A következő héten aztán, mikor az Illustrated London News és a
párisi Illustration egyszerre adták ki a Biró Jenő úr arczképét, Simi
gróf a szokottnál gyakrabban nézett be az olvasóterembe, s mint
ragadozó madár vetette rá magát azokra a gyanútalanokra, a kik az
emlitett képes lapokon szenderegtek.
Nem engedte el nekik, hogy az ő gyüjteményében van egy
külvárosi jelenet, mely kétségtelenül a nagy Biróé, egy valódi Biró,
mely a mester első korszakából való.
S a fáradsága nem is veszett kárba, mert szép lassan kiköszörülte
azt a csorbát, melyet szakértelmének hírén régi balsikerei ütöttek.
– Jobb orra van, mint hittük – mondogatták eleinte, ha a képeiről
beszéltek. – Egy párszor lefőzték ugyan, de, istenem, kit nem lehet
egyszer-kétszer megtéveszteni?! A szakemberek is megbotlanak
néha, kivált képdolgokban. És azt meg kell adni neki, hogy fölismerte
Biróban a nagy tehetséget. Ez már valami.
Később aztán elfelejtették a csalódásait, csak azt tudták róla,
hogy ő volt az első, a ki Birónak a tehetséget fölismerte. A tréfa élét
vesztette; nem akadt többé, a ki műérzékét fitymálta, kicsinyelte
volna. Egy szép nap arra ébredt, hogy az első rangú szakértők között
emlegetik.
Hogyne! Mikor ő volt az, a ki a nagy Birót fölfedezte.
......
Nem volt két ilyen nevü festő. A nagy Biró a mi szegény barátunk
volt.
Ha valaki azt kérdezné, hogy miképpen jutott Biró a »nagy«
jelzőhöz, erre csak azt lehetne felelni, a mit az olvasó már úgyis tud.
A London News kiadta az arczképét, mint a monte-carlói szerencsés
játékosét, az Illustration, mint Darzens kitünő tanitványáét, a kiről
mostanában annyit beszélnek, végre kiadták a magyar képes
ujságok is, a melyek már mint kitünő hazánkfiát emlegették.
S ha valaki ezt keveslené, ha azt vetné ellen, hogy az ujság-
elismerésektől a nagyságig még egy nagy lépés van, ezzel szemben
csak arra lehet hivatkozni, hogy méltóztassék megszámlálni: hány
nagyságot ismerünk, a mely nem az ujságok egybehangzó
dicséretein épült?
VII.

A szerencse, attól fogva, hogy Monte-Carlóban hozzászegődött,


hű maradt Biró Jenő úrhoz. A szerencse is asszony; s nem azok a
legmulandóbb viszonyaink, a melyeket a legkésőbben kötünk.
Ez a kései szerető, akárhová lépett Biró Jenő úr, mindenütt ott
járt a nyomában. Elválaszthatatlanok voltak.
A játékterembe ugyan nem kisérte többé, de talált más alkalmat,
hogy a hűségét bebizonyitsa. Biró Jenő úr nem játszott többet;
okosabbat csinált ennél: üzleteket.
És minden vállalkozásának mesés sikere volt. Ha az egész
környéket elverte a jég, az ő földeit kikerülte a csapás; ha a szél
kifútt a tárczájából egy ezrest, hazatérőben ott találta meg a pénzt a
park kapujánál, egy bokron fennakadva.
A legőrültebb vállalatok aranybányákká váltak, ha ő állt az élükre;
a bot kivirágzott volna a keze között, hogy ha virágszállitásra adja
magát.
A mihez hozzányúlt, aranynyá változott a keze között, mint Midás
királyról beszéli a mese.
Az ilyen embert a világ mindig meg tudja becsülni érdeme
szerint; megbecsülte Biró Jenő urat is.
Elhalmozták tisztességgel, kitüntetésekkel; válogathatott a
méltóságok között; mindenféle rangú szolgahad leste a parancs-
szavát; mindennap bebizonyitották neki, hogy milyen végtelen nagy
ember, s még életében tudta az egész világ, hogy hol fog majd a
szobra állani.
Nagy ember volt, kétségtelenül nagy, kiváló ember. Voltak az élet
játékasztalánál sokan, de csak ő találta ki, hogy másodszor is a
harminczas fog kijönni.
VIII.

Eleinte úgy látszott, hogy Biró Jenő úr meg tudja becsülni, a mit
a tűnő pillanat ád, s ki tudja színi minden virágnak a mézét.
Nem mintha az apró anyagi örömökre vetette volna magát, de a
szeméből, mely néha-néha a régi fényben ragyogott fel, ki lehetett
olvasni, hogy neki is megvannak a maga gyönyörűségei.
Igy fel-fellángolt néha a szeme, ha egy-egy régi ismerőse
magasztalni kezdte előtte valamelyik halhatatlan alkotását, melylyel
szives volt megajándékozni a világot. Ilyenkor aligha a bóknak
örvendett oly nagyon; mert bókban, hízelgésben ugyancsak volt
része. De, úgy tetszik, annak is van valami titkos öröme, ha az
ember mélységesen megvetheti egy-egy felebarátját.
Ezekben a szerencsés napokban, mikor az áldás csak úgy ömlött
a fejére, nagyobbára viszontlátta a régi ismerőseit. Vezekényi,
Weinberger úr, az egykori jury-tag O betűvé görbülve jelentek meg
előtte, kérvén egyben-másban a kegyes pártfogását. Sietett
teljesiteni a kivánságaikat, s meglátszott rajta, hogy szivesen adja az
alamizsnáját.
Ilyenkor valósággal jókedve volt. Néha még mosolyogni is látták.
Megérhette azt az örömet is, hogy jelentékeny szolgálatot
tehetett egykori pártfogójának, a gardénia-herczegnek, a kinek
társaságában valaha annyi kellemes, gondolattalan órát töltött.
A gardénia-herczeg ugyanis, hosszas várakozás után, elfoglalta
ősei trónját, de alig foglalta el, nemsokára kénytelen volt ismét
elhagyni, s kivonulni székvárosából, mely különben se tartozott a
hajlandóságainak megfelelő helyek közé. Nyugalomba tették, a mibe
a gardénia-herczeg némi húzódozás után, bele is törődött.
Ez a kis húzódozás azonban – polgári háborunak nem lehet
mondani, legfeljebb polgári csetepaténak – sok pénzébe került a
gardénia-herczegnek, s a fegyvergyárosok, a kik tudvalevőleg több
pénzt tudnak elnyelni, mint a világ összes hölgyecskéi, pillanatnyi
zavarba sodorták.
Ebből a pillanatnyi zavarból Masa grófnő és Biró Jenő úr
segitették ki a nyugalmazott királyt, néhány millió frank barátságos
kölcsönnel, melyet a virágok barátja, ki a királyságból csak az
udvariasságot őrizhette meg, olyan gardéniák kiséretében sietett
megküldeni, a milyenek sem azelőtt, sem azóta nem termettek ezen
a szép világon.
IX.

Akármit mondanak is a költők, jobb selyemmel párnázott


kocsiban járni, mint gyalog, fel a hegyre, déli egy órakor; jobb
Derbyt nyerni, mint olyan költőnek lenni, a kit minden omnibuszló
legázol; végre jobb, ha az embert az egész világ süvegeli, mint hogy
ha folyton oldalba lökdösik.
De akármilyen jó dolog is a kényelem, ha az ember sokáig jár
selyemmel párnázott kocsiban, végre ezt is megúnja, s ha valaki
háromszor egymásután megnyeri a Derbyt, utóljára ezt az örömet se
tudja méltányolni. Azonképpen, ha a szerencse gyermekét folyton-
folyvást, mindig süvegelik, többnyire elfelejti, hogy őt oldalba is
lökdöshetnék. Igy történt Biró Jenő úrral is.
Beleszokott a selyem párnákba; nem tűnt fel neki többé, milyen
jó módban él, s ettől fogva úgy kezdte találni, hogy ő voltaképpen
igen sajnálatraméltó ember.
A kinek megvan mindene, a mit az ember maga körül kivánhat,
az rendesen magában keres valamit, a mit aztán nem lehet
megtalálni.
Biró Jenő úr is magában kereste, a mije hiányzott, és ő is hiába
kereste, a mint hogy ez mindig igy szokott történni.
Eszébe jutott, hogy eddig, ha szomorú élete volt is, ha meg
kellett is izlelnie minden emberi szerencsétlenséget, fájdalmat és
nyomorúságot, volt egy vigasztalója, az, hogy magát nem vádolhatta
soha. Eddig mindig volt egy jóbarátja, a ki őt szerette, s a kiben
megbízhatott: önmaga.
Azóta elvesztette ezt a jóbarátot. S ha azt mondjuk, hogy
elvesztette, csak szépitjük a dolgot. Mert a rideg igazság az, hogy:
feláldozta, eladta.
X.

Attól a naptól fogva, a mikor eszébe jutott, hogy áldozatot


hozott, a fejébe vette azt is, hogy tulajdonképpen semmiért áldozta
fel lelkének a békéjét.
Mióta fiának a sorsa biztositva volt, úgy tűnt fel előtte, mintha a
gyermek jövőjén aggódni soha sem s lett volna oka. Ha túl vagyunk
valami bajon, az első dolgunk, hogy kicsinyelni kezdjük a
veszedelmet, a melyben forogtunk.
Miért áldozta fel tehát az énjét? Egy kis bőségért, mint az utolsó
szédelgő. Olyan bőségért, melynek örömét nem tudta élvezni.
Ez a bőség pedig egyre növekedett. Biró Jenő úr már régen
összetette a kezét, de a vagyona csak nőtt magától, és egyre
rohamosabban, mint a hógörgeteg.
Csinálhatott akármit, minden birtokából uj birtokok támadtak, s
Biró Jenő úr úgy tekintett erre a nagy áldásra, mint a Bűnre,
melynek mindig uj bűnöket kell szülnie.
Az emberek nem tudták megérteni, hogy ennyi szerencse
kegyeltje mért jár mindig olyan arczczal, mintha az orra vére folynék.
ÖTÖDIK RÉSZ.

I.

Naplót irni – a legtöbbször azok gyöngesége, a kik senkinek se


mondhatják el azt, a mi a leginkább foglalkoztatja őket. Kislányoké,
a kiket nyugtalanná tesz, megzavar, lázba ejt az a csodálatos
átváltozás, mely egy idő óta hatalmába keritette a lelköket, –
szerelmes lányoké, a kik még nem tartanak ott, hogy megvallhassák
érzéseiket annak, a kit ezek a mindenkor egyforma, gyermekes
mondanivalók nagyon is érdekelnek, – asszonyoké, a kiknek titkuk
van.
Ezeknek a kislányoknak, szerelmes lányoknak és titkot takargató
asszonyoknak a lelkéből kikivánkozik valami. Az elhallgatott,
feltartóztatott, fojtogatott érzések annyira megáradnak bennök, hogy
az özönnek ki kell fakadnia valahol. És ha nem gyónhatják meg
nyugtalanságaikat egy hozzájok hasonló valakinek, a kiben
tökéletesen megbíznak, ha nem suttoghatják el titkaikat még a
titoktartó, de részvéttelen nádasnak sem, mit van mit tenniök:
kilehellik, kipityergik sóhajaikat a magánosságban, vágyódásaikat
kiöntik szavak helyett betűkbe, sorokba, és vallomásuknak örök
rejtőzködésre kárhoztatott tanúit, hogy árulóikká ne válhassanak,
elcsukják egy kapcsos, kulcscsal zárható könyvbe.
Később, mikor már van kinek elmondaniok, hogy mi jár a
fejökben: nem nyitják ki többé a kapcsos könyvet. Vagy, ha igen,
nem azért nyitják ki, hogy megint irjanak bele, hanem: hogy
mulassanak azon, a mi már benne van. A napló egész tartalma
egyszerre gyermekességnek tűnik fel előttük. Milyen ostobák voltak
– akkor! És nem hinnék el, hogy a mit ezek a gyerekes sorok sírnak
el, az valóban komoly valami, – hogy nem ők lettek komolyabbakká,
hanem a körülményeik váltak vidámabbra. A bőségben élő szívesen
és derülten gondol azokra a kalandos napokra, a mikor minduntalan
koplalnia kellett; a mit akkor állott ki, most már vidám, humoros,
tréfás dolognak tűnik fel előtte, a boldog ifjuság, a kalandos élet
mulatságos tartozékának. Bőségének tudatában,
elbizakodottságában, mely tulajdon erejének véli azt, a miben csak a
sors kedvezését kellene látnia, nem tudja elképzelni, hogy régi esete,
régi gyöngesége, régi keserve igen komoly dolog volt, mely könnyen
végzetessé válhatott volna, ha az idegen erők, a körülötte s nem
benne működő erők, véletlenül, meg nem könyörülnek rajta.
Naplót irni – sokszor azoknak a gyöngesége, a kik szerelmesek
magukba. A kik benyomásaikat, már akármi kelti fel ezeket a
benyomásokat, minden esetben érdemesnek tartják a följegyzésre; a
kik megfigyelésüket olyan értékesnek vélik, hogy sajnálnák, ha ez a
számos, szép megfigyelés mind veszendőbe menne. Naplót irnak
tehát, hogy ezekben az érdekes dolgokban mások is
gyönyörködhessenek, vagy legalább még egyszer
gyönyörködhessenek ők maguk, később, esztendők multán, a mikor
ez a sok elfelejtett holmi megint ujnak tűnik fel előttük.
Ezeknek már érdemes naplót írniok, mert a második czélt
bizonyosan elérik.
Naplót irni – végül, szoktak, nagyritkán, olyanok is, a kikkel vagy
a kik előtt minduntalan történik valami följegyzésre méltó.
A napló-irók nagy sokasága ennek a három csoportnak egyikéhez
vagy másikához tartozik. Én, Biró Jenő, a ki az itt következő
jegyzeteket irom, nem tartozom a három csoport egyikéhez sem.
Nem érzem a szükségét annak, hogy elmondjam valakinek, a mi
a leginkább foglalkoztat. Vagy ha bennem is szendereg ilyes
hajlandóság, ez még nem növekedett, s aligha fog növekedni
ellenállhatatlan vágygyá. Soha se voltam nagyon közlékeny
természetű. Életem sora, emberismeretem s a hosszú megszokás
zárkozottá tett. A lelkemből nem kivánkozik ki semmiféle vallomás.
Nem keresem a rokon lelket, a ki megértsen. Tudom, hogy nem igen
van ilyen rokon lélek, és ha véletlenül mégis akadna, rokonomat
vallomásaimból mindössze az érdekelné, hogy esetem mennyire
hasonlit az övéhez. Rokonomnak magának is sokkal több baja volna,
semhogy valami nagyon törődnék velem; éppen elég neki a magáé.
De szerelmes se vagyok magamba. Nem képzelem, hogy
benyomásaim akárkit is érdekelhetnének. És nem akarom megőrizni
a feledéstől azt, a mit ma gondolok és érzek. Nem hiszem, hogy
valaha gyönyörüséget találhatnék ezekben a följegyzésekben. Soha
se leszek kiváncsi arra, hogy milyen voltam öt, tiz, tizenöt
esztendővel ezelőtt. Ettől a tanulmánytól nem remélek semmi
örömet.
És végre nem történik se velem, se körülöttem semmi olyas, a
minek a följegyzéséért érdemes volna tollat fognom. Azt, hogy az
élet arasznyi, és mégis a szomorúságok egész hegyei férnek belé, –
hogy az emberek a rosszasággal milyen keveset érnek el, és mégis
milyen rosszak tudnak lenni, – hogy a jó ember milyen áldás, és
hogy mégis ebben az áldásban mennyivel kevesebb részünk van,
mint a napfény áldásában, – hogy a boldogsághoz voltaképpen
milyen kevés kellene annak az embernek, a ki magát, a többieket és
a természetet megérti, és mégis, néha éppen azok a legkevésbbé
boldogok, a kik a legszerényebbek, a legkevésbbé követelők – ezt
ugyan fölösleges untalan ismételni.
Már jó ideje egyik napom tökéletesen olyan, mint a másik. És
hogy mi történik kívül, a világban, azt talán minden ember közűl én
tudom a legkevésbbé. Ugy élek, mint a pók, mely hangtalanul szövi
hálóját egy sötét zugban, és egy cseppet se törődik azzal, a a mi a
napfényen élőket foglalkoztatja, izgatja, futkározásra s küzdelmekre
birja. Csak éppen akkor mozdulok ki remeteségemből, a mikor az
élet eleséget követelő föltételei már nem tűrik meg, hogy a
rejtekemben maradjak.
Mért irom hát ezeket a följegyzéseket?
Időtöltésből. Hogy elöljek vele egy pár órát, a mikor nincs más
választásom, mint: tépelődni, tovább tépelődni, vagy:
ákombákomokat vetni papirra.
Mindennap van egy pár órám, a mely a gyönyörüségé. Él –
hálaistennek, él! – egy kis lény a világon, a kiért én is mintha élnék.
A kinek a jövőjéért mozgok, táplálkozom, igyekszem dolgozni, már a
mennyire tudok, a kinek az érdekében teljesiteni szeretném azt a
feladatot, melyet mindnyájunkra ránk róttak, melynek végső czélja
ismeretlen, s melynek teljesitése rám nézve még terhesebb, mint a
legtöbb küzködőre nézve, mert én már nem reménykedem, mint
ezek, nekem már nincs jövőm, csak jelenem, s a jelenem az, hogy
az életnek ezt az egyetlen, – mindig oly rövid! – gyönyörüségét
napról-napra megujuló, sok óráig tartó, s szinte elviselhetetlenül
nyomasztó szenvedéssel kell megfizetnem. Él egy kis lény, a ki
szerelmemből fakadt, s annak szivéből, a kit mindenekfelett
szerettem. Hallgatni ennek a kis lénynek a gügyögését, látni
arczocskáján az imádott vonásokat, annak a vonásait, a kit el kellett
temetnem, viszontlátni rajta, elevenen, valamit az ő lényéből, az ő
szemét, az ő ajkait, élve látni egy picziséget az ő szépségéből, az ő
bájából, nap-nap után valami ujat fedezni fel benne, a mi az ő
életének a folytatása, a mit a halál legalább emléknek meghagyott
nekem, a piczi lény mosolygásából, formáiból, mozdulataiból
ráismerni ő rá, a ki ime, nem mult el egészen, elnézni
gyermekünknek a növekedését játszani vele, ha ébren van, s lesni a
lélekzetét, ha alszik – bizonyára isteni gyönyörüség… s aligha irom
ezeket a sorokat, ha ez a gyönyörüségem nem, marad meg. De ez a
gyönyörüségem naponkint csak egy pár óráig tarthat – ennek a kis
lénynek az érdekében. Az az ápolás, a melyre szüksége van, a
legjobb ápolás, a melyben részesülhet, az éjszaka óráira mindig,
könyörtelenül elválaszt tőle, és nappal is tovább, mint szeretném.
Mert csak nappal dolgozhatom, és dolgoznom kell, érte.
Dolgozom, a mennyit és a hogyan tudok; akkor, a mikor csak
egyátalán képes vagyok rá. De kedv nélkül dolgozom és hamar
kimerülök. A rajzolás elemeire oktatni vásott sihedereket, a kiknek a
rajzoláshoz nincs semmi hajlandóságuk és nincs a legcsekélyebb
jóakaratuk – nem nekem való mesterség. Képpel látni el egy olyan
élczlapot, melynek a tartalmát megvetem, nemcsak hogy megaláz
magam előtt, nemcsak hogy folytonosan sérti lelkiismeretemet,
becsvágyamat, s a bennem szemérmesen rejtőzködő, de
leküzdhetetlen emberi méltóságérzetet: nagyon fáraszt is. Ugy
látszik, nemsokára már megszabadulhatok ettől a robottól s ettől a
boszorkánynyomástól; rövid idő mulva talán már nem lesz, a mi
lefokozza bennem azt a megbecsülést, a melylyel magunk iránt
viseltetnünk kell, azt az önérzetet, a melyre minden embernek
szüksége van ahhoz, hogy eredményes munkát végezhessen. Ugy
látszik, a közel jövőben elérhetem, hogy csak a művészi munkának
éljek. Van valaki, a ki megkedvelte a képeimet; ennek a valakinek
már utánzói is akadtak; ha festek, már nem dolgozom hiába. Örülök
ennek a fordulatnak, de örömem nem zavartalan, hanem
elégedetlenséggel és bizalmatlansággal elegyes. A jobbnak igérkező
jövő alapja nem egészen tiszta, s igen ingadozónak látszik. A mi
kiemel rabszolgaságomból, nem az, a minek a segitsége büszkévé
tenne; nem a művészet igazi szeretete, nem a jóizlésü nagyközönség
tartós megbecsülése. Hanem egyetlen egy embernek a szeszélye –
olyan emberé, a kinek a gondolkozása felszines s az izlése nem
tulságosan finom, a ki a művészi munkát is csak úgy nézi, a hogy
egy szép agarat vagy egy ügyes szerkezetü automobilt – s ezen a
szeszélyen kivül, a (valószinüen csak rövid ideig tartó) divat, mely
nyomon követi a fejedelmi szeszélyt. Ez a siker nem tesz büszkévé,
még kevésbbé elbizakodottá, sőt éppen nem elégiti ki az
önérzetemet. Azonkivül nem igen biztat azzal, hogy a jobb jövő
maradandó lesz. És mindezek koronájául elégedetlennek kell lennem
magammal is. Mi hasznom uj keletü kis sikereimből, mikor azt kell
látnom, hogy azok a képeim, a melyekkel ilyen eredményt érek el,
nem érnek annyit, néha sokkal, nagyon sokkal gyöngébbek, mint a
régiek, a melyek az ördögnek se kellettek?! Azért még akkor is kedv
É
nélkül dolgozom, a mikor festek. Érzem, hogy fogy a tehetségem, s
hogy már nem vagyok a régi erőmben; látom, hogy az a lélek, mely
a régi képeimnek valami értéket adott, az ujakon egyre
halványabban mutatkozik; sőt látnom kell azt is, hogy nemcsak a
művészi erőm, hanem még a munkaképességem is mind inkább
hanyatlik. És ez a keserves tudat, ez a szomorú látvány csak annál
jobban megbénit, csak annál hamarább elfáraszt.
Aztán, mikor tökéletesen bele fáradtam a munkába, és mikor –
késő este – ki vagyok zárva arról a helyről, a hol egyetlen örömömet
találom, egyedül maradok gondolataimmal. Szenvedésemmel;
fájdalmas emlékeimmel. Ó, nem akarok felejteni! Az emlékeim
becsesek nekem; hiszen nem maradt egyebem, csak a gyermekem
meg az emlékeim. És úgy érzem, Ő addig nem halt meg egészen, a
míg legalább az én emlékemben még ott van az a kép, a mely
valaha az Ő lényéből sugárzott, a mig tekintetének, mosolyának,
hangjának a benyomása legalább az én lelkemben él. Hogyne
őrizném hát az emlékeimet! Annál féltékenyebben őrzöm, mert
keservesen érzem, mily hitványul gyönge az emberi emlékezet, s
hogy legféltettebb benyomásaink hamarább illannak el, mint a
heliotrop illata egy nyitva felejtett illatszeres üvegből. És még se
adhatom át magamat egészen az emlékeimnek, az örömtelen
magánosság s a kénytelen pihenés óráiban sem. Az emlékezés
nekem még, akármennyire lelki szükségem, s akármilyen jóleső
érzésekkel vegyes, mégis nagyon fájdalmas; a szenvedés tulságosan
kimerít. Pedig szükségem van az erőmre, hogy dolgozni tudjak a
fiunkért.
Azért nem temetkezhetem bele a multba olyan mélyen, mint a
mennyire szeretném. Mikor már nagyon sajog a fájdalmam, ki kell
ragadnom magamat ebből az elernyesztő érzésből. De nem
menekülhetek a jövő képéhez sem. A jövőbe nézve csak kétségek
gyötörnek. És még folyvást órák választanak el attól az időtől, a
mikor el tudok aludni. Nagy ideje már, hogy igen keveset alszom;
akkor is inkább csak kábultan pihenek.
Ezeket az órákat, a melyekben hiába várom az álom vágyát, vagy
legalább a megváltó kábultságot, el kell ölnöm valamivel. Ugy teszek
tehát, mint a ki munkaközben, fél-pihenésül, firkál, rajzolgat, s
abrakadabrákkal, emberfejekkel, mértani ábrázolatokkal vagy
semmit se jelentő hieroglifákkal rójja tele az előtte heverő tiszta
papirlapot. Leirom ide, a mi olykor foglalkoztat, s a min egy kissé
elszórakozom.
Nem naplót irok. Ha a napi élményeimet akarnám ide jegyezni,
jóformán mindennap ugyanazt kellene leirnom, és annak a sok
egyformaságnak, a melyet napról-napra ujra meg ujra átélek, akár
hosszadalmas, akár rövid, de szükségképpen csupa ismétléssel járó
följegyzése már nem szórakoztatna. Csak időnkint irok ebbe a
könyvbe; olyankor, a mikor más menedéket már nem találok. És csak
azt irom ide, a mi éppen eszembe jut, de nem éppen először jut
eszembe.
Nincs több szándékom, mint a czéltalanul rajzolgatónak. Nem
szántam ezeket a följegyzéseket senkinek. Hanem azért el kell
számolnom azzal a gondolattal, hogy mi történhetik ezzel a könyvvel
a halálom után.
Az bizonyos, hogy nem szeretném, ha olyanok kezébe kerülne, a
kiknek idegen voltam és mindig idegen maradok. Nem azért irok az
érzéseimről, hogy akárki turkálhasson bennök; mindenkinek vannak
kedves családi levelei, a melyeket nem szivesen látna a zsibvásáron.
De gondom lesz rá, hogy ez a könyv ne kerülhessen röhögő
kiváncsiak kezébe.
Van valaki, a ki elolvashatja. A fiam, ha majd huszonöt esztendős
lesz. Nem czélom éppen, nem is kivánom, de nem bánom, ha
elolvassa. Legalább meggyőződhetik róla, hogy akármit beszéljenek
is az apjáról egy olyan korszakban, a melyben semmi se általános,
csak az éhség és a falánkság: az apja nem volt se elmebajos, se
beteg idegzetü ember, sőt talán ostoba ficzkó sem, ha ugyan nem
mindenki ostoba ficzkó, a ki valami egyebet is kiván az élettől, és
nem csak: garast, sok garast, mentül több garast.
II.

Olyanoktól, a kik derülten birálják embertársaikat és soha se


néznek vissza arra a csekélységre, a mi a multjokban egy kissé
feketéllik: az édesanyára, a ki éhen halt s a kivel nem törődtek, – a
felebarátra, a kit gyöngéd, a büntetőtörvénynyel egy cseppet se
ellenkező formában, de azért nem kevésbbé hathatós módon
segitettek kituszkolni ebből az árnyékvilágból, – az elhagyott
kedvesre, a kit a nyomoruságba taszitottak, – a magzatra, a kinek
életefonalát a lehető legkorábban juttatták Atroposz párka ollós
kezébe, – a szegényekre, a kiknek ügyesen elvarázsolt piszkos
krajczárjaiból, bűzös párnáiból, utálatos verejtékéből angol
kényelemmel berendezett, jó illatú otthont épitettek maguknak, – a
testvérre, a kit kizsákmányoltak, – a párbajban lelőtt ellenfélre, a
kinek a holttestéből talapzatot készitettek maguknak, hogy végül
mint államférfiak magasodjanak ki a sokaságból, – a
megrágalmazott vetélytársakra, a kiket előbb elbuktattak, aztán
elsirattak, hogy az üres helyekre ők ülhessenek, – a megtévesztett
ezrekre, a kiknek ostoba bizalmát, ostoba meggyőződését vagy
ostoba érzéseit okosságuk adófizetőivé tették, – és igy tovább, mert
ennek soha se volna vége, – az ilyenektől gyakran hallani efféle
nyilatkozatot:
– A világnak haladnia kell, és a haladásnak erős akaratú, kemény
legényekre van szüksége, nem érzelgős, puha lényekre. Az érzelgős
ember nem férfias; az érzelgős férfi nevetséges, ostoba, utálnivaló.
Érzelgősnek ők háromféle embert neveznek. Mindenekelőtt az
olyat, a kit az ostoba meggyőződés még arra is rábir, hogy e miatt
ellentétbe keveredjék a tulajdon érdekével. Azután az olyan embert,
a kinek az érzései erősek, mélyek, tartósak, s a ki, érzésből, még
áldozatokra is képes. Végül azokat, a kikre (előttük örökkön
megérthetetlen) nagy hatással van a szerelem, a részvét érzése,
vagy a fájdalom.
Érzelgés vagy érzés nekik mindegy. Se a két szót, se a két
fogalmat nem tudják egymástól megkülönböztetni. Minthogy érzés
nem igen van bennök: a nagy és a mély érzést képtelenek
megérteni. És mert ők taplós szivüek: az érezni tudókat szánalmasan
gyöngéknek, betegeknek, ostobáknak, maguk alatt valóknak nézik.
Ha az orrszarvúval meg tudná értetni valaki, hogy az ember
bőrén a szúnyogcsipésre hólyagok támadnak, az orrszarvú
agyvelejében bizonyára valami olyan képzetféle derengene fel, hogy:
az ember igen gyatra és alsórendü állat. Pedig abból, hogy az
orrszarvú bőre föl se veszi azt, a mi az érzékenyebb bőrű embernek
már egy kissé fájdalmas, nem az következik, hogy az orrszarvú
egészséges, az ember pedig beteg, nem az, hogy az orrszarvú eszes,
és az ember ostoba, hanem csak az, hogy az orrszarvú és az ember
két különböző állat.
Ezeknek a taplós szivü felsőbb lényeknek, a kik olyannyira
szivükön viselik a világ haladását, s oly meghatóan gondoskodnak a
messze jövő ismeretleneiről, miután fenevadak módjára viselkedtek
a hozzájok tartozókkal szemben, azt lehetne mondani:
Meglehet, hogy a világot ezentúl azok fogják előbbre vinni, a
kikben annyira túlteng az értelem, hogy minden érzést kiszorit a
lelkükből, de eddig nem egészen igy történt. A mi a társadalom mai
berendezésében jó és az eleveneknek hasznos, olyan halottak
alkották meg, a kik a meggyőződéseiket előbbre helyezték a
személyes érdeküknél. A mi az előttünk lévő emberi alkotásokban
maradandó, vagy legalább tartósabb, mint az egyes ember élete,
nagyrészt (s ha csak a leginkább kiemelkedő jelenségeket tekintjük:
általában) olyanok műve, a kik érzésből képesek voltak áldozatokra
is. A legértékesebb eredmények, a melyekhez az emberi elme valaha
eljutott, azok, a melyeknek felkutatását az érzés sürgette;
kivívásukban olyanok működtek közre, a kikben az érzékenység és
ennek megfelelően a részvét érzése fejlődöttebb volt, mint a nagy
tömegben, mig az érzés nélkül való értelmesek megelégedtek azzal,
hogy tarkává tették a világtörténelmet.
Mi teremtette meg, például, a művészeteket, ha nem az érzés?
(Mert, ha a szépet szeretjük: öntudatlanul is a jót keressük; azt, a mi
a természetben vigasztaló; azt, a mi a természet és az ember
rendeltetésében azonos.) Igaz, csinálnak ma már úgynevezett
művészetet ügyeskedéssel, tisztán »észből« is; de a remekműveket,
a melyekhez a divat hóbortjainak ellenére is vissza-visszatér az
emberiség, mindenkor a nagy és mély érzések sugallták.
Érezni tudni: nem beteges állapot, hanem a fejlődöttebb emberi
léleknek egyik tulajdonsága. (Mert az érzés kiigazodik a homályos
képzetek közt, a hol az értelem nem tud itélni; mert az érzés
birodalma: a csak sejthető; az, a mi az észnek örökre
»ignorabimus«; az, a mi csak a bennünk rejlő legtitokzatosabb
valamivel, az ösztönszerü itélettel, a természeti erő legrejtelmesebb
részével közelithető meg.) Adomány, mely olyan, mint az élet többi
adománya: nemcsak gyönyörűséggel jár, hanem bajjal és
fájdalommal is.
És nem természetes-e, hogy a művész, a kit aprócseprő dolgok
kevésbbé foglalnak le, tehát kevésbbé szórakoztatnak el, mint más
embert, – a ki a többieknél szabadabban adhatja át magát az
érzésének, mert hisz ez: kötelességének nem ellensége, hanem
ellenkezőleg: ihletének forrása, – hogy a művész, a ki végre is az
egész természet életében megnyilvánuló örök érzés egyik követe
volna (mert az életfolyamatok bonyodalmas összejátszásában nem
csak egy titokzatos erő, nem csak egy titokzatos önző czél
jelentkezik, hanem egy még titokzatosabb, minden szervessel és
szervetlennel szemben hozzája mérten gondoskodó örök érzés is,
mely mintha a bennünk lévő érzőképesség ősforrása volna), – hogy
a művész erősebben érez, mint a számitó kalmár?
Hallom, hogy számitó kalmárok, a kik festenek és űzérkednek a
képeikkel, azt beszélik rólam, talán meggyőződésből, de talán egy
kissé azért is, hogy így könnyebben rázhassanak le a nyakukról, s ne
kellessen éppen kiöklözniök a piaczról… szóval a barátaim azt
mondják, hogy beteg lélek vagyok. Mert egészséges lélek-e az, a
melyen ilyen sokáig rágódik a fájdalom? Ők sokallják, a mi nekem
fáj.
III.

Lehet, hogy, ha többet forognék az emberek között, már nem


mondanák rólam, hogy beteg lélek vagyok, és – már nem érezném
annyira, a mi most csak úgy fáj, mint a legelső napon. Az életünk
föltételeit szabályozó törvény úgy kivánja, hogy az uj benyomások
háttérbe szoritsák a régieket; hogy a sok apró uj benyomás háttérbe
szoritsa a legerősebb régi benyomást is; s hogy a sokszor, sokára
háttérbe szoritott régi benyomások lassankint elhalványodjanak,
elsorvadjanak. Ha keresném a felejtést, ha el akarnám altatni a
szivemet, ha azt kivánnám, hogy valami elölje a fájdalmamat, ha
nekem is csak egy óhajtásom volna: átaludni azt az időt, a mig a
sebem beheged, s valami lelki altatószer használata után kábultan
helyeződni át abba az állapotba, abba az időpontba, a mikor az
ember már nem emlékszik s nem érez, – csak sokat kellene az
emberek közé mennem, és nekem is sikerülne az, a mi sikerül
másoknak, a gyászolók ama nagy többségének, a melyben megvan
az ehhez való jó szándék.
Nem keresem a felejtést. Ragaszkodom az emlékeimhez, a mig
ragaszkodhatom. A nekem oly kedves, drága képeket, a mult képeit,
a melyek, ha olykor összefacsarják a szivemet, fölidézik az eltünt
napok édességét is, s meg-megjelenésükkel egy kissé vigasztalnak –
nem akarom elűzni. Nem akarom elűzni kedvesem árnyékát; árnyéka
is kedves nekem. Nem félek, nem kínos nekem Rá gondolni.
Megőrzöm, a mi Ő belőle még él, a mig megőrizhetem. Hisz azok a
képek is, a melyek a legerősebben dobogtatták meg szivünket, oly
hamar elillannak a tehetetlen emlékezet elől! Hisz amúgy is oly korán
következik el az az óra, a mikor az idő már mindentől meglopott
bennünket, a mikor boldogságunk egész paradicsomából csak valami
iszonyuan kevés, homályos, zavaros álomfoszlány marad meg
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like