Essential Java For Scientists And Engineers 1st Brian D Hahn
Essential Java For Scientists And Engineers 1st Brian D Hahn
Essential Java For Scientists And Engineers 1st Brian D Hahn
Unit 2 COMMERCIAL BANKING, Corporate banking.pptxAnubalaSuresh1
How to Manage Large Scrollbar in Odoo 18 POSCeline George
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptxSireQuinn
How to Create Odoo JS Dialog_Popup in Odoo 18Celine George
Post Dated Cheque(PDC) Management in Odoo 18Celine George
Talk on Critical Theory, Part One, Philosophy of Social SciencesSoraj Hongladarom
Ad
Essential Java For Scientists And Engineers 1st Brian D Hahn
1. Essential Java For Scientists And Engineers 1st
Brian D Hahn download
https://ebookbell.com/product/essential-java-for-scientists-and-
engineers-1st-brian-d-hahn-922826
Explore and download more ebooks at ebookbell.com
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Essential Java For Scientists And Engineers 1st Edition Brian Hahn
https://ebookbell.com/product/essential-java-for-scientists-and-
engineers-1st-edition-brian-hahn-1533566
Essential Java For Ap Compsci From Programming To Computer Science 1st
Edition Doug Winnie
https://ebookbell.com/product/essential-java-for-ap-compsci-from-
programming-to-computer-science-1st-edition-doug-winnie-33789578
Continuous Delivery In Java Essential Tools And Best Practices For
Deploying Code To Production 1st Edition Daniel Bryant
https://ebookbell.com/product/continuous-delivery-in-java-essential-
tools-and-best-practices-for-deploying-code-to-production-1st-edition-
daniel-bryant-11902512
Energyefficient Hvac Design An Essential Guide For Sustainable
Building 1st Edition Javad Khazaii Auth
https://ebookbell.com/product/energyefficient-hvac-design-an-
essential-guide-for-sustainable-building-1st-edition-javad-khazaii-
auth-4932784
3. Essential Java 3d Fast Developing 3d Graphics Applications In Java 1st
Edition Ian Palmer Bsc
https://ebookbell.com/product/essential-java-3d-fast-
developing-3d-graphics-applications-in-java-1st-edition-ian-palmer-
bsc-4198752
Learn Java 12 Programming A Stepbystep Guide To Learning Essential
Concepts In Java Se 10 11 And 12 1st Edition Nick Samoylov
https://ebookbell.com/product/learn-java-12-programming-a-stepbystep-
guide-to-learning-essential-concepts-in-java-se-10-11-and-12-1st-
edition-nick-samoylov-11265456
Sun Java Web Server The Essential Guide Nelson Bill Srinivasan
https://ebookbell.com/product/sun-java-web-server-the-essential-guide-
nelson-bill-srinivasan-21995480
Essential App Engine Building Highperformance Java Apps With Google
App Engine 1st Edition Adriaan De Jonge
https://ebookbell.com/product/essential-app-engine-building-
highperformance-java-apps-with-google-app-engine-1st-edition-adriaan-
de-jonge-2347282
Android Studio Electric Eel Essentials Java Edition Developing Android
Apps Using Android Studio 202211 And Java 1st Edition Neil Smyth
https://ebookbell.com/product/android-studio-electric-eel-essentials-
java-edition-developing-android-apps-using-android-studio-202211-and-
java-1st-edition-neil-smyth-49039778
6. Essential Java
for
Scientists and Engineers
Brian D. Hahn
Department of Mathematics & Applied Mathematics
University of Cape Town
Rondebosch
South Africa
Katherine M. Malan
Department of Computer Science
University of Cape Town
Rondebosch
South Africa
OXFORD AMSTERDAM BOSTON LONDON NEW YORK PARIS
SAN DIEGO SAN FRANCISCO SINGAPORE SYDNEY TOKYO
7. Butterworth-Heinemann
An imprint of Elsevier Science
Linacre House, Jordan Hill, Oxford OX2 8DP
225 Wildwood Avenue, Woburn, MA 01801-2041
First published 2002
Copyright c
2002 Brian D. Hahn and Katherine M. Malan. All rights reserved
The right of Brian D. Hahn and Katherine M. Malan to be identified
as the authors of this work has been asserted in accordance with
the Copyright, Designs and Patents Act 1988
All rights reserved. No part of this publication
may be reproduced in any material form (including
photocopying or storing in any medium by electronic
means and whether or not transiently or incidentally
to some other use of this publication) without the
written permission of the copyright holder except
in accordance with the provisions 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, England W1T 4LP.
Applications for the copyright holder’s written permission
to reproduce any part of this publication should be addressed
to the publishers
British Library Cataloguing in Publication Data
A catalogue record for this book is available from the British Library
Library of Congress Cataloguing in Publication Data
A catalogue record for this book is available from the Library of Congress
ISBN 0 7506 5422 8
For information on all Butterworth-Heinemann publications visit our website at www.bh.com
Typeset by Laserwords Private Limited, Chennai, India.
Printed and bound in Martins the Printers of Berwick Upon Tweed
8. Contents
Preface xiii
Acknowledgements xvi
Part I Essentials 1
1 Getting going 3
1.1 Introduction to programming 3
Java as a programming language 3
1.2 Setting up your computer for programming in Java 4
Installing Java 2 4
Jikes as an alternative compiler 5
Installing the essential package 6
1.3 Writing your first Java program 6
What happens when a program is compiled? 7
Understanding FirstProgram 7
Commands for printing to the screen 8
1.4 Input and output 9
How input from the keyboard works 10
Reading in numbers from the keyboard 10
Input without the Keyboard class (optional) 10
Example: calculating compound interest 11
1.5 Comments 11
1.6 Using objects 12
Using the Turtle class 12
Help on the essential package 13
Using the Graph class 14
1.7 Java on the WWW (optional) 15
2 Java programming basics 20
2.1 Compound interest again 20
2.2 Primitive data types 23
Bits and bytes 23
v
9. vi Contents
Numeric constants 24
double is default 24
2.3 Names 25
Identifiers 25
Case sensitivity 25
Variables 25
2.4 Vertical motion under gravity 26
2.5 Operators, expressions and assignments 27
Arithmetic operators 27
Precedence 27
Increment and decrement operators 28
Assignments and assignment operators 29
Cast operators 30
2.6 Repeating with for 30
Turtle spirals 30
Growing an investment 33
The for statement 34
Alternative ways of counting with for 35
Square rooting with Newton 35
Factorials! 36
Limit of a sequence 37
Reading data from a text file 37
2.7 Deciding with if 38
The if-else statement 40
The if-else-if statement 40
The if-else-if ladder 40
for and if: counting passes 41
Rolling dice 41
Logical operators 42
Boolean variables 43
Nested ifs 44
The switch statement 44
2.8 Characters 45
Escape sequences 45
2.9 Math methods 46
2.10 Programming style 46
3 Solving a problem in Java 55
3.1 Introduction 55
3.2 The class provider, class user and end user 56
3.3 What are objects and classes? 56
Looking at the Turtle class in more depth 57
3.4 Writing and using a simple class 58
3.5 How memory works 59
What is memory? 59
How objects and primitives are stored in memory 60
The null keyword 60
3.6 The String class 62
Equality testing of strings 63
3.7 Understanding methods 63
Method arguments 63
Return types 64
Signature of a method 64
10. Contents vii
Constructors 64
More on the import statement 65
3.8 Example: simulating a rabbit colony 66
Data members of RabbitColony 66
Methods of RabbitColony 66
Using the RabbitColony class 67
Defining the grow() method 68
Defining the grow(int n) method 68
Defining the getNumRabbits() method 68
Tracing UseRabbitColony 69
3.9 Access modifiers 70
The public and private keywords 70
Other access modifiers 70
3.10 Example: simulating the growth of trees 71
Data members for the Tree class 71
Methods of the Tree class 71
A main method to test the class 72
Writing the methods 72
When to define a default constructor 73
The this keyword 74
3.11 Scope 74
3.12 More on object handles 75
Passing objects to methods 75
Object handles and assignment 78
3.13 The static keyword 80
Understanding static 80
Constants 81
Static methods 81
The main method revisited 83
3.14 Naming conventions 83
3.15 Using the Java API 84
3.16 Making your own package (optional) 84
4 More on loops 89
4.1 Determinate repetition with for 89
Binomial coefficient 89
for loops with non-unit increments 90
Plotting a projectile trajectory with Essential Grapher 91
Update processes 93
The nested for loop 96
4.2 Indeterminate repetition with while 98
Rolling a dice for a six 98
The while statement 99
A guessing game 100
Prime numbers 101
Projectile trajectory 102
Reading an unknown amount of data 103
The do-while statement 104
while versus do-while 105
5 Debugging 114
5.1 Compilation errors 114
5.2 Run-time errors 117
11. viii Contents
5.3 Errors in logic 119
Debugging logical errors 119
5.4 Rounding errors 119
6 Arrays and matrices 123
6.1 Introduction 123
Why bother with arrays? 123
6.2 The basics of arrays 125
Declaring and initializing an array 125
Indexing elements of an array 125
Looping through an array 126
6.3 Passing arrays to methods 128
6.4 Frequency distributions: a simple bar chart 128
6.5 Multi-dimensional arrays 129
A concrete example 130
Matrix multiplication 131
6.6 Arrays of objects 133
6.7 Sorting an array 134
Part II More advanced topics 141
7 Inheritance 143
7.1 Introduction 143
What is inheritance? 143
Generalization and specialization 144
7.2 Inheritance in Java 145
Reusing code through specialization 146
Overriding methods 148
The protected keyword 150
7.3 Constructors and inheritance 150
Default constructors 151
The super keyword 151
Parameterized constructors 152
7.4 The Object class 152
The toString method 153
7.5 Abstract classes and interfaces 154
Why bother with abstract classes? 155
Interfaces 155
8 Graphical user interfaces (GUIs) 160
8.1 Introduction 160
GUIs in Java 160
Understanding events 161
8.2 Building a Swing application 161
A first version 161
Shutting down the application properly 161
Components and containers 162
Adding a button to the application 162
Organizing the code in a better way 163
Adding a label 164
Getting the button to do something 165
Listeners as nested classes 165
12. Contents ix
8.3 Arranging components 167
The FlowLayout manager 167
The BorderLayout manager 168
Adding borders to components 169
8.4 A colour chooser application 170
Planning the GUI 170
Defining the colour 170
Adding the components 170
Adding the sliders and labels 172
Programming the behaviour 173
8.5 Painting 174
PacMan and the Blocks 176
8.6 Drawing mathematical graphs 185
8.7 Fractals 189
The Julia set 189
The Mandelbrot set 192
9 Input/output 197
9.1 Introduction 197
9.2 Input through command line parameters 198
9.3 Input from the keyboard without the essential package 198
9.4 Streams 199
Output redirection 199
The System class 200
The InputStream and InputStreamReader classes 200
The BufferedReader class 201
Reading in numbers 201
9.5 File input/output 201
Types of files 202
File handling 202
Reading in from a text file 203
Writing to files 203
9.6 Manipulating data 204
Tokenizing strings 204
9.7 Streams and the Internet 205
10 Exceptions 209
10.1 Introduction 209
10.2 Exceptions in Java 209
Exception classes 210
10.3 Throwing exceptions 211
When to specify the throws clause in a method header 213
10.4 Handling exceptions 214
Example: finding averages 214
Catching an exception 215
What happens when an exception is thrown 217
10.5 Exceptions and file input 217
Groups of exceptions 218
Forcing the exceptions 218
Catching FileNotFoundException and
EOFException 219
Looping while file not found 220
The finally statement 221
13. x Contents
Part III Some applications 225
11 Simulation 227
11.1 Random number generation 227
The Math.random method 227
Seeding the random number generator 228
The Random class 228
Normal (Gaussian) random numbers 229
11.2 Spinning coins 229
11.3 Rolling dice 230
11.4 Bacteria division 230
11.5 Radioactive decay 230
Estimation of half-life 232
11.6 A random walk 233
11.7 Traffic flow 236
12 Modelling with matrices 242
12.1 Using the Matrix class 242
The identity matrix 244
12.2 Networks 244
A spy ring 244
The reachability matrix 246
12.3 Leslie matrices: population growth 248
12.4 Markov processes 252
A random walk 253
12.5 Linear equations 256
Limitations of the invert method of Matrix 258
The residual 258
Ill-conditioned systems 258
13 Introduction to numerical methods 262
13.1 Equations 262
Newton’s method 262
A Function class 263
Defining a new exception 266
Complex roots 267
The Bisection method 269
13.2 Numerical differentiation 270
13.3 Integration 272
The Trapezoidal rule 272
Simpson’s rule 274
13.4 First-order differential equations 274
Euler’s method 275
Example: bacteria growth 275
A predictor-corrector method 277
13.5 Runge–Kutta methods 279
Runge–Kutta fourth-order formulae 279
Systems of differential equations: a predator-prey model 280
Implementation of the numerical solution 280
13.6 Driver: a GUI to solve ODEs 284
Setting up a model to run with Driver 284
Using Driver 287
Chaos 287
14. Contents xi
13.7 A partial differential equation 290
Heat conduction 290
Appendix A Keywords 298
Appendix B Operators 299
Appendix C Syntax quick reference 300
C.1 Primitive type declarations 300
C.2 Methods 300
C.3 Classes 301
C.4 Decisions 301
C.5 Loops 302
Appendix D Solutions to selected exercises 304
Index 333
15. Preface
This book serves as an introduction to the programming language Java. In addition it focuses on how
Java, and object-oriented programming, can be used to solve science and engineering problems. As such,
some of the examples necessarily involve aspects of first-year university mathematics, particularly in
the final chapter. However, these examples are self-contained, and omitting them will not hinder your
programming development.
Features
• The book is accessible to beginners, with no programming experience.
• We use a hands-on or ‘dive-in’ approach which gets you writing and running programs immediately.
• The fundamentals of Java programming are motivated throughout with many examples from a
number of different scientific and engineering areas, as well as from business and everyday life.
Beginners, as well as experienced programmers wishing to learn Java as an additional language,
should therefore find plenty of interest in the book.
• It provides a good introduction to object-oriented programming. Solutions to problems throughout
the book show how data and operations on that data can be modelled together in classes. In this
way code is easy to maintain, extend and reuse.
• We have provided a pre-written package of code to help in such areas as
– simple keyboard input and file input/output;
– matrix manipulation;
– scientific graphing.
Approach
• Our style is informal. New concepts are often motivated with a coded example before being
generalized.
• Readers are frequently invited to try appropriate exercises at the end of each chapter as they advance
through the chapter.
• Throughout the book, we use Java applications, rather than applets (although we do provide an
example of an applet in Chapter 1).
xiii
16. xiv Preface
• All the examples in this book have been compiled and interpreted using Sun Microsystems’ Java 2
compiler (in particular version 1.3.1 of the Java Software Development Kit).
Resources
• Each chapter begins with a set of objectives and concludes with a summary and numerous exercises.
These exercises have been gleaned from many years’ experience of running hands-on programming
courses and writing books for beginners and professionals alike, on problem solving in Basic,
Fortran, Pascal, C, C++ and MATLAB.
• The appendices include a quick reference to Java syntax and solutions to selected exercises.
• The book’s website, www.bh.com/companions/essentialjava, provides links to material such as:
– code for the essential package, containing our pre-written classes;
– Java source code of all completed code that appears in the text;
– solutions to selected exercises in individual file format.
Solutions to the remaining exercises are password-restricted, and are available only to lecturers who
adopt the book for use in their courses. To obtain a password please e-mail [email protected]
with the following details: course title, number of students, your job title and work postal address.
Organization of the book
The book is organized into three parts:
1. Essentials (Chapters 1–6)
This part covers what we believe to be the essentials of programming in Java: using pre-defined
objects and methods, basic programming concepts and constructs (primitive data types, variables,
expressions, loops and decisions), writing your own classes, debugging code, arrays.
2. More advanced topics (Chapters 7–10)
Inheritance, building your own graphical user interfaces, exceptions, input and output.
3. Some applications (Chapters 11–13)
Simulation, matrices (use of our essential.Matrix class in fields such as reachability, popula-
tion dynamics, Markov processes, linear equations), numerical methods.
Chapter 1
Chapter 2
Chapter 3
Chapter 4 Chapter 6 Chapter 7 Chapter 8
Chapter 5 Chapter 11 Chapter 12 Chapter 9
Chapter 10
Chapter 13
Figure 1 Dependency diagram showing relationships between the chapters
17. Preface xv
Dependencies between the chapters are shown in Figure 1. We strongly recommend that a course should
cover at least the first seven chapters (including inheritance), even though all seven chapters are not
strictly needed to proceed to some of the more advanced topics.
18. Acknowledgements
Our warm thanks to the following, who all contributed in some way to this book: Natalie Jones, Andy
Shearman, Travis Milewski, Robb Anderson, Donald Cook, Mike Linck, Mike Rolfe and Kevin Colville.
We also wish to thank the University of Cape Town for study and research leave, and the University
of Cape Town and the National Research Foundation for funding aspects of the project.
Finally, our thanks to our families for their love, understanding and encouragement during all the ups
and downs of writing this book.
Brian D. Hahn
[email protected]
Katherine M. Malan
[email protected]
January 2002
xvi
20. 1
Getting going
Objectives
By the end of this chapter, you should be able to do the following:
• set up your computer to be ready for programming in Java;
• compile and run a simple program which reads in from the keyboard and prints out to the screen;
• use the Turtle class and Graph class to draw graphics on the screen;
• write a simple Java program that can be run in a World Wide Web (WWW) browser (optional).
1.1 Introduction to programming
Computers have become an essential part of our everyday lives. Even if you don’t use a computer for
writing letters, browsing the Internet, or playing games, you are using computers every time you draw
money from an ATM, use your cell phone, or phone automatic directory enquiries. A computer on its
own has no intelligence. All that a computer can do is follow a detailed set of instructions, so it has to be
programmed with these instructions for it to be useful. That’s where the task of the programmer lies: in
writing programs to make computers useful to people. Every bit of software, from your wordprocessor,
to your web browser, was written by a programmer (or more likely, a team of programmers).
The set of instructions that a computer can understand is called machine language. In machine language,
everything is encoded as binary numbers (1’s and 0’s). Not so long ago, programmers had to write
programs in this machine language. Thankfully, we have now advanced to a stage where we can write
programs in high-level languages, such as Java. It is the job of the compiler (just another program)
to translate programs written in a programming language into machine code, so that it can be run on
a computer. Some games programmers still choose to use low-level assembly language (very close to
machine code), because the programs run faster.
Java as a programming language
Java has an interesting history. It was developed in 1991 by James Gosling of Sun Microsystems. Gosling
was part of a secret team of 13 staff, called the ‘Green Team’. The aim was not to develop a new language,
but rather to develop digitally controlled consumer devices and computers. While developing a home-
entertainment device controller (called *7), the team saw the need for a new processor-independent
language. The first version was called ‘Oak’ (after the tree outside Gosling’s window). Although *7
3
21. 4 Essential Java for Scientists and Engineers
never took off, the language did and in 1995, Netscape announced that Java would be incorporated
into Netscape Navigator. Since then, Java has gained enormous popularity as an Internet programming
language. Although Java has become famous for its ability to do Internet programming, it is also a good
general programming language. We chose to write a book on Java, because it is popular and a well-
designed object-oriented language. One of the main features of Java (and part of the reason why it works
so well on the Internet), is that it is platform independent. It achieves this by using something called
the ‘Java Virtual Machine’ (JVM). As explained before, computers can only follow machine language
instructions, so programs written in high-level languages have to be compiled into machine code for them
to work. The problem is that each type of machine has its own machine language, so a program compiled
for a MS Windows NT machine won’t work on a Macintosh machine. What Java does is compile down
to an intermediate code called bytecode. This bytecode is machine independent, but has to be interpreted
by the JVM. This process of interpreting will be explained in Section 1.3.
1.2 Setting up your computer for programming in Java
There are two pieces of software which you will need before you can start programming:
• An editor or an IDE (Integrated Development Environment). An editor is a program which
allows you to type in text and save it to a file. A text editor differs from a word processor in
that it does not normally do formatting (such as different font sizes). Some text editors (such as
Microsoft’s Notepad) have no special features for programmers, while other editors have special
features to support programmers. There are many shareware and freeware editors available from
online software libraries (such as TUCOWS, which you can find at http://www.tucows.com). Look
for an editor which has Java syntax colouring (also called syntax highlighting).
IDE’s, on the other hand, provide facilities for editing and compiling programs, as well as other
support for programmers. The downside to using an IDE, is that you normally have to pay for
it. A further factor to consider is that some Java IDE’s provide features which complicate Java
programming (such as the need to create projects), so in some cases it may even be easier to use a
simple text editor, rather than an IDE. Sun has a list of recommended IDE’s on their website (they
are listed on the download page of Java 2). We have assumed in this book that you will be using a
text editor rather than an IDE.
• A Java compiler. This is the software that will compile your program. We recommend that you use
Sun Microsystems, Inc. Java Software Development Kit (SDK). This is the popular choice, mainly
because it is freely available. In this book we have used version 1.3.1, but you are free to use a later
version (instructions on how to download and install this are given below). Other Java 2 compatible
compilers will also be fine.
Installing Java 2
The name ‘Java 2’ refers to all the releases of Sun’s Java SDK starting with release 1.2 (and including
releases 1.3.x). Versions before this were known as ‘Java 1’. To set up Java 2 on your computer, do the
following:
1. Using your favourite web browser, go to Sun’s Java web site: http://www.java.sun.com
2. Follow the links from ‘Products and APIs’ to ‘Java 2 Platform, Standard Edition’ (the SDK). Select
the relevant platform and follow the instructions. At the end of the installation, your directory
structure should look something like the listing shown in Figure 1.1.
3. We recommend that you download the Java 2 Platform Standard Edition Documentation as well. As
you learn to program, you will need to reference this documentation frequently and it will help to
have it easily accessible.
4. You will need to change your PATH variable to include the folder which contains the javac.exe
and java.exe files. You will find the details on how to do this in the readme.html file inside
the jdk folder.
22. Getting going 5
Figure 1.1 Directory listing showing how Java 2 will be installed
Jikes as an alternative compiler
You may find that the Java 2 compiler is slow on your computer at home. If you do find that it is very
slow, you can try Jikes as an alternative faster compiler. Jikes is developed by IBM and is Open Source
Software. It works with Sun’s SDK, so you still need to install Java 2 as described above (you actually
only need to install the runtime environment or JRE). Like Java 2, Jikes is free. You can download it
from the following website:
http://oss.software.ibm.com/developerworks/opensource/jikes/
The zip file that you download contains a file called jikes.exe. The easiest way to set up Jikes is to
do the following:
23. 6 Essential Java for Scientists and Engineers
1. Change your PATH variable to include the folder which contains the file jikes.exe.
2. Provide a definition for JIKESPATH as follows (Note: this assumes that Java has been installed on
your C: drive. If this is not the case, then change the folder accordingly):
set JIKESPATH=c:jdk1.3.1jrelibrt.jar;
c:jdk1.3.1jrelibextessential.jar
3. You can now use the command jikes in the place of javac to do your compiling.
Installing the essential package
The website that accompanies this textbook contains a package of Java code, which we will use from
time to time in the text. This package is called essential, and contains functionality for drawing
graphs, working with matrices and much more. It is very simple to install the essential package.
On the website you will find a file called essential.jar. All you have to do is copy this file into a
particular place in the jdk folder. In this way we are installing essential as an extension to Java.
Copy the file essential.jar into the following directory:
c:jdk1.3.1jrelibext
If your version of the SDK is stored somewhere else, then copy it to the equivalent jrelibext
folder.
1.3 Writing your first Java program
We will now write our first program in Java. We want you to start programming as soon as possible, so
don’t worry if there are things that you don’t understand. The details will be explained later.
1. Write the program
Open your editor and type in the following Java program:
public class FirstProgram
{
public static void main (String[] args)
{
System.out.print(Hello, 2 + 3 = );
System.out.println(2 + 3);
System.out.println(Good Bye);
}
}
Make sure you type it in exactly as it appears above. Java is case-sensitive, which means that it
makes a difference if a letter is in uppercase or lowercase. In Java, System is not the same as
SYSTEM, or even system.
2. Save the program
Save the program in a file called FirstProgram.java. Once again, the case is significant, so
make sure that the F and P are in uppercase and the rest are in lowercase.
3. Compile the program
Open an MS-DOS Prompt window, change the directory to the directory where you saved your file
and type in the following command:
javac FirstProgram.java
24. Getting going 7
Figure 1.2 Results from running and compiling FirstProgram.java
After you push Enter, it should simply return to the prompt. If there are errors, you will have to go
back to the editor and make sure you have copied down the code correctly. Remember that case is
significant! Continue with steps 2 and 3 until you have no errors.
4. Run the program
Once your program has successfully compiled (with no errors), you can run the program by typing
in the following command:
java FirstProgram
You should see the output shown in Figure 1.2.
What happens when a program is compiled?
When you compile FirstProgram.java, using the javac command, a file is created called First-
Program.class. This .class file is in Java bytecode format (close to machine code). If you try to
open this file with your text editor, you will either get an error, or it will display a few strange characters.
When you run the program, using the java command, the .class file is interpreted by the Java Virtual
Machine. If you want somebody else to run one of your programs, all you need to do is send them the
.class file. As long as they have the Java Runtime Environment installed on their computer, they will
be able to run your program, without needing to re-compile it for their machine.
Understanding FirstProgram
We will now explain how the program works. Figure 1.3 illustrates the parts of a simple Java program.
The parts written in the grey area are what you will need every time you write a program. We call this
the ‘application template’, because it is the basic structure within which we write simple programs. The
only part of the grey area which will be different for different programs is the name of the program (also
the name of the class). Each time you write a program, you must decide what to call your program. For
example, here is the outline of a program called AnotherProgram:
public class AnotherProgram
{
public static void main(String[] args)
{
}
}
25. 8 Essential Java for Scientists and Engineers
The statements in the
grey part are what we
call the application
template. It contains
the framework within
which you need to
type your statements.
Later we will explain
what each part of the
application template
means.
The white part of the program is where you
type your statements to be executed.
System.out.print(Hello, 2 + 3 = );
System.out.println(2 + 3);
System.out.println(Good Bye);
public class
{
public static void main (String[] args)
{
{
{
FirstProgram
FirstProgram is the name of the program.
This name must be exactly the same as the
name of the file that program is saved in.
The file must have a .java extension.
Figure 1.3 The parts of FirstProgram.java
This program will do nothing if it is run, because there are no statements between the middle curly
braces. We call the curly braces block markers, because they mark the beginnings and endings of blocks
of code. In the application template, the first curly brace and the last curly brace are block markers for
the whole program, i.e. they denote the beginning and end of the program. The middle two braces are
block markers for the portion of code called the main method. The purpose of the main method will be
explained later.
Now try the following:
1. Make a copy of FirstProgram and save it as SecondProgram.java.
2. In SecondProgram.java, change the name of the program after the class statement to
SecondProgram.
3. Save, compile and run SecondProgram.
You now have a copy of the program, which you can modify later.
Commands for printing to the screen
Now that you understand how to structure a simple program (even if you don’t understand the detail),
we will look at the statements inside the main method. Here are the statements inside our first program:
System.out.print(Hello, 2 + 3 = );
System.out.println(2 + 3);
System.out.println(Good Bye);
First notice that each line terminates with a semi-colon. This indicates the end of a statement and is
analogous to the full stop at the end of a sentence in the English language.
All three lines start with System.out, which refers to the screen of the computer. The command
System.out.print is an instruction to the screen to print something out. The details of what should
be printed are given inside the parentheses (round brackets).
In the case of the first statement, we are asking the screen to display a string . A string is simply a
sequence of characters enclosed in double quotation marks. In the first line of our program, the string to
26. Getting going 9
Table 1.1 Output illustrating the difference between print
and println
Code Output
System.out.println(hello); hello
System.out.println(there); there
System.out.print(one ); one two three
System.out.print(two ); four five
System.out.println(three );
System.out.print(four );
System.out.println(five );
be printed is the sequence of characters, starting with the character ’H’ and ending with an equals sign
and a space. The result of the print statement is that the string is simply printed out exactly as it looks
in between the quotes.
The second line is a little different. Firstly, it has a sum inside the parentheses, rather than a string, as
in the first statement. What Java does in this case is to work out the answer to the sum (i.e. 5), before
displaying it. If it had been inside quotes (“2 + 3”), then the answer would not have been worked out
and would have been displayed simply as the character ‘2’ followed by a space, the plus sign another
space and the character ‘3’.
Secondly, it uses a command called println rather than print. The difference between println
and print, is that println will display the details inside the parentheses and then output a new line
(equivalent to pressing the enter key on the keyboard). The print command, on the other hand, stays on
the same output line until more information is displayed. A few examples will illustrate this difference.
In Table 1.1 the left column gives examples of Java statements, while the right-hand column show
what would be printed onto the screen when the statements are compiled and run as part of a Java
program. Do you understand why the output will look like that?
Finally, the last statement simply displays the string “Good bye” before the program stops.
Now try to do Exercises 1.1 and 1.2 at the end of the chapter.
1.4 Input and output
We have looked at how to do output (printing things to the screen) using the print and println
statements. In this section we will explain the difference between input and output and show how to get
input from the keyboard using Java statements.
The important thing to realise when we talk about input and output in computing, is that it is in
reference to the computer, not to ourselves. Output flows out of the computer and input flows into the
computer. Examples of devices which display computer output are screens and printers. Input devices,
on the other hand, include keyboards, mouse pointers and joysticks.
In Java, it is quite complicated to read in from the keyboard. To simplify things, we have created a
class called Keyboard, which is part of the essential package (mentioned in Section 1.2). We will
start by looking at a simple example which inputs the name of the person using the program:
import essential.*;
public class NameEcho
{
public static void main (String[] args)
{
System.out.print(Enter your name: );
String name = Keyboard.readLine();
System.out.println(Hello + name + !);
}
}
27. 10 Essential Java for Scientists and Engineers
Notice that the program starts with:
import essential.*;
This line is necessary when you are using any of the classes that are provided with this textbook. The
name of the program (or class) is NameEcho, so to test it, you will need to save it in a file called
NameEcho.java. Compile and run the program and see what happens.
Notice how the program pauses in order to get input from you, the user, via the keyboard. Type in
your name at the prompt and see what happens.
How input from the keyboard works
In the second line of the program, the statement:
Keyboard.readLine();
reads in a line of text from the keyboard. When you push Enter, it will store the string in a variable
called name (variables will be discussed in the next chapter). The last line of the program prints out the
string “Hello”, followed by the contents of the variable name (the string entered on the keyboard) and
an exclamation mark. Notice that the ‘+’ signs are not printed. When used between strings, a ‘+’ sign
concatenates the strings.
Now try Exercise 1.3.
Reading in numbers from the keyboard
In the example above, the Keyboard class was used with readLine to read in a string. If we want to
read in a whole number, we need to use readInt, instead of readLine, as in the following example:
import essential.*;
public class Square
{
public static void main (String[] args)
{
System.out.print(Enter a number: );
int num = Keyboard.readInt();
System.out.println(The square is: + (num*num));
}
}
Notice in this program, the use of the * operator for performing multiplication . The statement:
int num = Keyboard.readInt();
suspends the program until a number is entered on the keyboard, followed by Enter. The number is then
stored in the variable called num (which is of type integer). Try running this program to see how it
responds to different input. What will happen if you type in a string instead of a number? What will
happen if you type in a real number (such as 2.5)?
Now try to do Exercise 1.4.
Input without the Keyboard class (optional)
As mentioned before, the Keyboard class is there to simplify the process of reading input. For those
who are interested, we have written an equivalent program to Square. Although it behaves the same as
28. Getting going 11
the previous program, this program is written without using the Keyboard class. We will not explain
the details, since it is shown here purely for interest.
import java.io.*;
public class Square2
{
public static void main (String args []) throws IOException
{
BufferedReader in = new BufferedReader (
new InputStreamReader(System.in));
System.out.print(Enter a number: );
String s = in.readLine();
int num = Integer.parseInt(s);
System.out.println(The square is: + (num*num));
}
}
Notice that a package called java.io is imported (this is Java’s standard package for performing input
and output). The essential package is not needed, so is not imported.
Example: calculating compound interest
Let’s look at a more complicated example using numbers to calculate compound interest:
import essential.*;
public class CompoundInterest
{
public static void main (String[] args)
{
System.out.print(Enter a balance: );
double balance = Keyboard.readDouble();
System.out.print(Enter a rate: );
double rate = Keyboard.readDouble();
balance = balance + (rate * balance);
System.out.println(New balance = + balance);
}
}
This example uses real numbers rather than whole numbers. A real number in Java is called a double
(or a float). These will be explained properly in Chapter 2. The user is asked to type in a balance and an
interest rate (as a decimal fraction, e.g 15% should by typed as 0.15). The balance is then incremented
by the interest rate and the new balance is printed out. Note the statement:
balance = balance + (rate * balance);
The = sign performs assignment and has the effect of changing the variable on the left. This will be
explained in more detail in Chapter 2. Compile and run the program to see how it works.
Now try Exercises 1.5 and 1.6.
1.5 Comments
A comment is a remark in a program which is meant to clarify something for the reader. It is ignored
by the compiler. There are two ways to indicate comments in Java:
29. 12 Essential Java for Scientists and Engineers
• Anything after a double slash (//) up to the next new line is interpreted as comment. This way of
making a comment is suitable when the comment consists of a single line, or explains a single line
of code. For example:
amt = amt+int*amt; // increment the amount by the interest rate
• Comments may also be enclosed between the symbol pairs /* and */ . This form is suitable
when we want to write a more extended comment, for example:
/* This program models the growth of a rabbit colony over time.
* Assumptions:
* - start with male/female pair of baby rabbits.
* - it takes 2 months for a baby to become an adult.
* - adults produce a male/female pair of rabbits
* every month.
*/
Everything between /* and */ is ignored, so the extra stars are optional, but are a common way of
emphasising that the text is a comment.
These forms of comments may not be ‘nested’, although they may be used to ‘comment out’ sections
of code containing the // comment, e.g.
/*
// This is a comment
...
...
...
*/
1.6 Using objects
Throughout this book, you will be using Java code which has been written by other programmers. This
code is organized into units called classes (this will be explained in more detail in Chapter 3). There are
many classes which are provided as part of the core Java. You have already used one of these classes,
namely the System class for printing out messages to the screen. As you progress through this book,
you will use many more of these classes. In addition, we have provided a number of classes with this
textbook. You have already come across the Keyboard class, and in this section we will show you how
to use another two of these classes.
Using the Turtle class
The Turtle class can be used to draw shapes inside a window on the screen. The shapes that are drawn
are based on commands given by you, the programmer, in Java. A turtle is represented as a triangle in
the window. A turtle has a pen which can be either up or down.
• If the pen is up and the turtle walks, no line is drawn.
• If the pen is down and the turtle walks, a line is drawn (a turtle always starts with its pen down).
Here are some examples of commands that a turtle object understands:
• forward: walk forward a given number of steps;
• right: turn right by a given number of degrees;
30. Getting going 13
• left: turn left by a given number of degrees;
• home: go back to the starting position;
• warp: move directly to a given point;
There can be many turtles drawing in the window at the same time. Compile and run the following
program and see what happens (remember to call your file TurtleDrawing.java):
import essential.*;
public class TurtleDrawing
{
public static void main (String[] args)
{
Turtle fred = new Turtle(); // create a Turtle called fred
fred.forward(50); // tell fred to move forward 50 paces
fred.right(90); // tell fred to turn right 90 degrees
fred.forward(50); // tell fred to move forward 50 paces
fred.home(); // tell fred to go back to the origin
}
}
Figure 1.4 shows what you should see on your screen. The turtle drawing area is a square of 200 by
200 units, with the origin in the middle. The top left of the window is the point (−100, 100), whereas
the bottom right corner is point (100, −100). When you create a Turtle object, it always starts at the
origin facing North. If you tell a turtle to go forward, it will walk in the direction in which it is facing.
We will now explain the program:
• First notice that the program starts off with the statement: import essential.*;. You have to
put this statement in your program if you want to use any of the classes which are provided with
the textbook (such as Keyboard or Turtle).
• The first statement inside main creates a Turtle object called fred. Before using the Turtle
class, you have to construct (create) a Turtle object using the new keyword in this way. We will
tell you more about constructors in Chapter 3.
• The second statement tells the object fred to move forward by 50 paces. Since Turtle objects
start in the middle of the window and the distance to the edge is 100, this will mean that fred will
move upwards, half way to the edge of the window, drawing a line as it moves forward.
• In the next 2 statements, fred turns right by 90◦ and goes forward another 50 paces. This results
in a horizontal line of 50 units. After going forward, fred is facing East and is in the middle of
the top right quadrant of the window.
• The last statement tells fred to go back home to the starting position, which is in the centre of
the window and facing North. Since by default a turtle’s pen is down, 3 lines are drawn for each
movement of fred: two for the forward statements and one for the home statement.
Instructions that we give to Turtle objects (such as forward, right or home) are called methods.
There are many more methods which you can use with the Turtle class. For a list of these methods,
you need to know how to get help on the essential package.
Help on the essential package
All the classes inside the essential package are documented in help files which you can browse. On
our website you will find a link to essential API. Click on this link and you will see a list of All Classes
in the left-hand frame. Click on the Turtle link. This will bring up a description of the Turtle class in
the right-hand frame. In the table called Method Summary, you will see a list of methods which you
can use with a Turtle object. Notice that the methods forward, home and right are listed. Some
31. 14 Essential Java for Scientists and Engineers
Figure 1.4 Output from running TurtleDrawing.java
of the methods which you can easily try out are: left, penUp, penDown, setAngle and warp. You
will learn more about methods in Chapter 3.
Now try to do Exercises 1.7 to 1.10
Using the Graph class
We will now introduce a further class of the essential package, namely the Graph class. This class
can be used for drawing graphs based on a number of points. Run the following program and see what
happens:
import essential.*;
public class TestGraph
{
public static void main (String[] args)
{
Graph g = new Graph(); // create a Graph object called g
g.addPoint(-2,-4);
32. Getting going 15
Figure 1.5 Output from running TestGraph.java
g.addPoint(0,0);
g.addPoint(1,2);
}
}
The output that you should get is shown in Figure 1.5
When you create a Graph object, using the keyword new, a window is created for displaying the
graph. We call this window Essential Grapher. By default, the axes are set to the ranges −5 to 5 for
both the X and the Y axes. You can change these ranges by using the setAxes method. Try adding
this statement to the TestGraph program, compile and run it and see what happens:
g.setAxes(0,10,0,6);
You can also set some of the properties of the Essential Grapher window using the menu, under Pro-
perties. Try changing some of the properties using the menu and see what happens. Notice also that as
you move the mouse pointer over the Essential Grapher window, the X and Y values are displayed at
the bottom right.
Now try to do Exercises 1.11 and 1.12.
1.7 Java on the WWW (optional)
Every Java program is either an application or an applet. The programs we have been writing until now
have been applications. Applets are very similar to applications, except that they run in a web browser.
Applets are therefore Java programs that run on the WWW. In this book, we will be working with
applications, rather than applets. However, since we know that many of you will be curious to see how
Java works on the web, in this section we will show you a simple example of an applet. The program
below is an applet equivalent to the application FirstProgram that we wrote in Section 1.3.
33. 16 Essential Java for Scientists and Engineers
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet
{
public void paint (Graphics g)
{
String s = Hello, 2 + 3 = + (2 + 3);
g.drawString(s, 25, 50);
g.drawString(Good Bye, 25, 100);
}
}
You compile applets in the same way that you compile applications, but you cannot run them using the
java command. An applet has to be embedded inside HTML, in order to be run. The following is a
very simple HTML page.
html
title This is my first applet /title
body
applet code = FirstApplet.class width=200 height=200
/applet
/body
/html
Notice the chunk in the middle, which is a reference to FirstApplet (the .class file). To run this
applet, you have to save this as a file with an .html extension and then open it with your browser.
There is a Java application called Applet Viewer that enables you to run applets without using a web
browser. You can run the Applet Viewer from the command line using the appletviewer command
followed by the html file that you wish to view. For example, to run the HTML file above (assuming
it is saved as FirstApplet.html), type the following command:
appletviewer FirstApplet.html
This command will create and display a small window with the applet running inside.
Summary
• The set of instructions that a computer can understand is called machine language.
• A compiler is a program that translates programs written in a high-level language (such as Java)
to machine code.
• Java achieves platform independence by compiling down to bytecode, which is interpreted by the
Java Virtual Machine.
• You can compile a Java program using the javac command and run a program using the java
command.
• A Java program must be saved in a file with a .java extension. The name of the file must be
the same name as the class.
• Block markers (curly braces) mark the beginning and end of a block of code.
• Commands for printing to the screen include System.out.print and System.out.
println.
• Every statement in Java is terminated by a semi-colon.
34. Getting going 17
• A string is a sequence of characters enclosed in double quotation marks.
• Input from the keyboard can be made using the Keyboard class, which comes with the essen-
tial package.
• When you use classes from the essential package, you have to import it using the command
import essential.*;
• Comments in a program are meant to assist the human reader and are ignored by the compiler.
• In Java, comments either follow a double slash(//), or are enclosed in the pair of symbols *
and *.
• The Turtle class is part of the essential package and can be used to draw shapes inside a
window.
• The Graph class is also part of the essential package and can be used for drawing graphs
of points.
• Applets are Java programs that run on the web.
Exercises
1.1 Write a Java program which will print out the following:
Stars:
*****
The End
1.2 What would be printed onto the screen if the following Java statements were run?
System.out.println(Here is some output:);
System.out.println(4 + 5);
System.out.print(4 + 5);
System.out.print( = );
System.out.println(9);
1.3 Write a program that asks the user to enter their surname. After that it should ask the user for
their first name. It should then print out the person’s first name followed by a space and their
surname.
1.4 Write a program that asks the user to enter a whole number and then prints out the number
doubled.
1.5 Write a program that asks the user to enter two whole numbers. Your program should then print
out the value of the two numbers multiplied. For example, if the user enters 40 and 10, your
program should print out 400.
1.6 Change your program from the previous exercise to work with real numbers.
1.7 What will be the result from running the following program? Draw the resulting diagram with
a pencil and paper before running the code.
import essential.*;
public class TurtleEx1
{
public static void main (String[] args)
35. 18 Essential Java for Scientists and Engineers
{
Turtle sid = new Turtle(); // create a Turtle called sid
sid.backward(50);
sid.right(90);
sid.forward(50);
sid.penUp();
sid.home();
}
}
1.8 What will be the result from running the following program?
import essential.*;
public class TurtleEx2
{
public static void main (String[] args)
{
Turtle sam = new Turtle(); // create a Turtle called sam
sam.left(45);
sam.forward(50);
sam.left(90);
sam.forward(50);
sam.left(90);
sam.forward(100);
sam.left(90);
sam.forward(100);
sam.left(90);
sam.forward(50);
sam.left(90);
sam.forward(50);
}
}
1.9 What will be the result from running the following program?
import essential.*;
public class TurtleEx3
{
public static void main (String[] args)
{
Turtle t = new Turtle(); // create a Turtle called t
t.penUp();
t.forward(100);
t.right(135);
t.penDown();
t.warp(100,0);
t.warp(0,-100);
t.warp(-100,0);
t.warp(0,100);
}
}
36. Getting going 19
1.10 Write a program, using the Turtle class, to draw a square with sides of length 100, with the
centre of the square positioned at the origin of the window.
1.11 Write a program that uses Essential Grapher to draw a graph of the following points:
(0 , 0 )
(0.5, 3 )
(1 , 4 )
(2 , 4.5)
(5 , 4.8)
In your program, change the axes to suitable values.
1.12 Write a program that uses Essential Grapher to draw a graph of the following equation:
y = 2x - 3;
Hint: calculate two points which are fairly far away from each other and add these as points to
the graph.
37. 2
Java programming basics
Objectives
By the end of this chapter you should be able to write short Java programs which:
• evaluate a variety of formulae;
• make repetitive calculations;
• make simple decisions.
You presumably bought this book because you want to learn how to write your own programs in Java.
In this chapter we will look in detail at how to write short Java programs to solve simple problems
involving basic arithmetic operations, repetition and decisions. There are two essential requirements for
successfully mastering the art of programming:
1. The exact rules for coding instructions must be learnt;
2. A logical plan for solving the problem must be designed.
This chapter is devoted mainly to the first requirement: learning some basic coding rules. Once you are
comfortable with these, we can gradually go on to more substantial problems, and how to solve them
using Java’s object-oriented machinery.
All Java constructs introduced in the text are summarized in Appendix C.
2.1 Compound interest again
In Chapter 1 you ran a program to compute compound interest. The following variation on that program
(which you should also run) highlights some basic concepts which we will discuss below.
public class CompInt
{
public static void main(String[ ] args)
{
double balance, interest, rate;
balance = 1000;
20
38. Java programming basics 21
rate = 0.09;
interest = rate * balance;
balance = balance + interest;
System.out.println( New balance: + balance );
}
}
We saw in Chapter 1 that when you compile a Java program with the javac command the result is a
bytecode file with the extension .class. You subsequently run (execute) the bytecode with the java
command. During compilation, space in the computer’s random access memory (RAM) is allocated for
any numbers (data) which will be generated by the program. This part of the memory may be thought
of as a bank of boxes, or memory locations, each of which can hold only one number at a time (at the
moment). These memory locations are referred to by symbolic names in the program. So, for example,
the statement
balance = 1000
allocates (when it is executed) the number 1000 to the memory location named balance. Since the
contents of balance may be changed during the program it is called a variable.
The statements between the inner block markers { ... } in our program CompInt are interpreted
as follows during the compilation process:
1. Create memory locations for storing three variables of type double
2. Put the number 1000 into memory location balance
3. Put the number 0.09 into memory location rate
4. Multiply the contents of rate by the contents of balance and put the answer in interest
5. Add the contents of balance to the contents of interest and put the answer in balance
6. Print (display) a message followed by the contents of balance
Note that these instructions are not carried out during compilation. All that happens is that they are
translated into bytecode.
When you run (execute) the program, these translated statements are carried out in order from the top
down. Figure 2.1 shows how the memory locations change as each statement is executed. Understanding
the order in which program statements are carried out is very important, particularly if you are used
to spreadsheeting, which is entirely different. Spreadsheet formulae can be calculated in any particular
order; or rather, you don’t usually need to be concerned about the order in which cell formulae are
calculated. However, this is most emphatically not the case when you program in a language like Java.
You have to get the statements into the correct order so that when they are executed in that sequence
they will carry out the required tasks correctly.
After execution of our translated statements, in the order shown, the memory locations used will have
the following values (see Figure 2.1):
balance : 1090
interest : 90
rate : 0.09
Note that the original content of balance is lost.
It is worth lingering over the statement
balance = balance + interest;
since it is an example of a very common programming device to update (increment) a variable
(balance). Java evaluates the expression on the right-hand side of the equals sign, and places the
answer in the variable on the left-hand side (even if the variable appears on both sides). In this way the
old value of balance is replaced by its new value.
39. 22 Essential Java for Scientists and Engineers
Statement
double balance, interest, rate; balance
interest
rate
balance = 1000; balance
interest
rate
rate = 0.09; balance
interest
rate
interest = rate * balance; balance
interest
rate
balance = balance + interest; balance
interest
rate
Memory after statement is
executed
1000
1000
1000
1090
0.09
0.09
90
90
0.09
Figure 2.1 How the memory locations (variables) in CompInt change as each statement is executed
The remaining statements in the program are also very important:
public class CompInt
is a class declaration. Everything inside the block markers that follow is part of the class
declaration—remember to close all opening block markers! We will discuss classes in detail in
Chapter 3.
The name of the file in which the program is saved must be the same as the name of its public
class, i.e. the class CompInt must be saved in CompInt.java.
public static void main(String[ ] args)
is technically a method of the CompInt class.
Methods do things. For the moment just think of main as doing whatever needs to be done, i.e.
whatever follows in the block markers { ... }.
A static method is associated with its class, rather than with an instance of the class— this
distinction will be explained in Chapter 3.
All the variables in a program must be declared with a data type. This is done here by double, which
means they are all double-precision floating point numbers with or without fractional parts.
40. Java programming basics 23
Incidentally, if you are fussy about how many decimal places appear in the output, using the
Math.round method is probably the easiest way of specifying two decimal places, for example:
System.out.println( Math.round(balance*100)/100.0 );
It works as follows. First, balance is multiplied by 100, then the product is rounded to the nearest
integer, and finally the result is divided by 100—leaving two decimal places.
Now try Exercise 2.1 at the end of the chapter.
Before we can write any more complete programs there are some further basic concepts which need
to be introduced.
2.2 Primitive data types
Java has a number of primitive data types, of which int and double are two examples. The different
data types and their properties are summarized in Table 2.1. We will come across most of them in due
course.
Bits and bytes
Before we go any further we need to look briefly at how information is represented in a computer. A
bit is the basic unit of information in a computer. It is something which has only two possible states,
usually described as “on” and “off”. The binary digits 0 and 1 can be used to represent these two states
mathematically (hence the term digital computer). The word “bit” in a contraction of “binary digit”.
Numbers in a computer’s memory must therefore be represented in binary code, where each bit in a
sequence stands for a successively higher power of 2. The binary codes for the decimal numbers 0 to
15, for example, are shown in Table 2.2.
A byte is eight bits long. Since each bit in a byte can be in two possible states, this gives 28, i.e. 256,
different combinations.
Table 2.1 Primitive data types in Java
Type Size (bits) Range
boolean 1 true or false
char 16 Unicode 0 (u0000) to Unicode 216 − 1 (uFFFF)
byte 8 −127 to +127
short 16 −32 768 to +32 767
int 32 −2 147 483 648 to +2 147 483 647
long 64 −9 223 372 036 854 775 808 to +9 223 372 036 854 775 807
float 32 ±3.40282347E+38 to ±1.40239846E−45
double 64 ±1.79769313486231570e+308 to ±4.94065645841246544e−324
void -- --
Table 2.2 Binary and hexadecimal codes
Decimal Binary Hexadecimal Decimal Binary Hexadecimal
0 0000 0 8 1000 8
1 0001 1 9 1001 9
2 0010 2 10 1010 A
3 0011 3 11 1011 B
4 0100 4 12 1100 C
5 0101 5 13 1101 D
6 0110 6 14 1110 E
7 0111 7 15 1111 F
41. 24 Essential Java for Scientists and Engineers
Hexadecimal code (see Table 2.2) is often used because it is more economical than binary. Each
hexadecimal digit stands for an integer power of 16. E.g.
2A = 2 × 161
+ 10 × 160
= 32 + 10 = 42
One byte can be represented by two hex digits.
Octal code is less common than hexadecimal: each digit represents a power of 8.
Computer memory size (and disk capacity) is measured in bytes, so 64K for example means slightly
more than 64 000 bytes (since 1K actually means 1024). Computers are sometimes referred to as 16- or
32-bit machines. This describes the length of the units of information handled by their microprocessors
(chips). The longer these units, the faster the computer.
Numeric constants
A numeric constant is just a number used in a program. For example, in the statement
int num = 400;
num is a variable and 400 is a numeric constant.
An integer numeric constant has no decimal places and may be written with or without a plus or minus
sign.
A floating point numeric constant may be written in two ways. It may be written as a signed or
unsigned string of digits with a decimal point, e.g.
0.09 37. 37.0 .0 0. -.123456
It may also be written in scientific notation with an integer exponent. In this form a decimal point is not
necessary. For example:
2.0e2 (200.0)
2e2 (200.0)
4.12e+2 (412.0)
-7.321e-4 (−0.0007321)
double is default
A floating point constant is of type double by default. It can be coerced into type float if necessary
with the suffix f (or F). The following statement, for example, generates a compiler error which usually
confounds beginners:
float rate = 0.09;
The error occurs because 0.09 is double type by default and Java won’t let you assign a double
type to a float type, because it won’t fit (although it allows the reverse, which is called upcasting).
The remedy is to write
float rate = 0.09f;
Now try Exercises 2.2 and 2.3.
42. Java programming basics 25
2.3 Names
Identifiers
An identifier is the symbolic name used to represent items in a Java program, e.g. rate, println. An
identifier must
• start with a letter, underscore character (_) or dollar symbol;
• consist of only the above characters and digits.
An identifier may be of any length.
Examples:
r2d2 // valid
pay_day // valid
pay-day // invalid
pay day // invalid
2a // invalid
_2a // valid
name$ // valid
Java has special keywords, which are reserved and may not be used as identifiers. They are the obvious
ones, like double, class, int, void, and also some less obvious ones like super and finally.
See Appendix A for a complete list of Java keywords.
Case sensitivity
It may come as a surprise to you, if you are not familiar with Java, that identifiers are case sensitive,
e.g. rate and Rate are different variables.
You need to bear in mind that case sensitivity extends to class and file names. For example, the program
in Section 2.1 must be saved in the file CompInt.java, because the class name is CompInt (and not
Compint or compint).
Many programmers write identifiers representing variables in lowercase except for the first letter of
the second and subsequent words. This style is known as camel caps, the uppercase letters representing
(with a little imagination) a camel’s humps, e.g. camelCaps, milleniumBug, endOfTheMonth.
Variables
A variable is the name given by a program to a storage location. It is helpful to distinguish between two
types of variables in Java:
• a primitive data variable, i.e. the name given to a storage location which will hold a primitive data
type, such as balance, interest and rate in CompInt;
• an object handle, i.e. the name of an object, such as fred (the Turtle object in Chapter 1).
Objects are discussed in detail in Chapter 3.
If you use a variable in a program without initializing it, the compiler generates an error.
Every variable declared should be described in a comment. This makes for good programming style.
Beware: if an integer type (i.e. byte, short, int, long) is increased above its maximum value in
a calculation its value “wraps around” to the minimum and starts again. For example, the code
int n, m;
n = Integer.MAX_VALUE; // largest integer
m = n+1;
System.out.println( m );
43. 26 Essential Java for Scientists and Engineers
results in the output
-2147483648
Try Exercise 2.4.
2.4 Vertical motion under gravity
We will now show you a Java program that uses a well-known physics formula.
If a stone is thrown vertically upward with an initial speed u, its vertical displacement s after a time
t has elapsed is given by the formula s = ut − gt2/2, where g is the acceleration due to gravity. Air
resistance has been ignored. We would like to compute the value of s, given u and t. Note that we are
not concerned here with how to derive the formula, but how to compute its value. The logical preparation
of this program is as follows:
1. Assign values of g, u and t
2. Compute the value of s according to the formula
3. Output the value of s
Drawing up a plan like this may seem trivial and a waste of time. Yet you would be surprised how
many beginners, preferring to dive straight into Java, try to program step 2 before step 1. It is well worth
developing the mental discipline of planning your program first. Type your plan into your text editor in
the form of comments in the main body of the program. Then add the Java statements corresponding to
each comment below the comment.
The program is as follows:
public class Vertical
{
public static void main(String[ ] args)
{
//1. Assign values of g, u and t
double g = 9.8; // acceleration due to gravity
double s; // vertical displacement
double t; // time
double u; // launch velocity
t = 6;
u = 60;
//2. Compute the value of s according to the formula
s = u*t - g/2*t*t;
//3. Output the value of s
System.out.println( s: + s + metres );
}
}
New concepts raised in this program are discussed in the following sections.
44. Java programming basics 27
2.5 Operators, expressions and assignments
Many of the programs that you will be writing will include mathematical expressions, such as
u*t - g/2*t*t
These expressions are evaluated by means of operators when a program runs. Java has a number of
different kinds of operators for evaluating expressions, e.g. arithmetic, increment, decrement, relational,
logical, etc. We are going to look at the first three kinds in this section.
Arithmetic operators
• There are five arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division), and
% (modulus). An operator with two operands is called a binary operator. When it has only one
operand it is called unary. Addition and subtraction can be unary or binary. Here are some examples
of expressions involving these operators:
a + b / c
-a // unary minus
b / (2 * a)
• When both operands in a division are of an integer type, the fractional part is truncated (chopped
off).
• The modulus operation returns the integer remainder after division of its integer operands. The sign
of the remainder is the product of the signs of the operands. For example:
10 / 3 // evaluates to 3 (fractional part is truncated)
10 % 3 // evaluates to 1 (remainder when 10 is divided by 3)
-10 % 3 // evaluates to -1
• Java performs real arithmetic in double precision, so coercion to float may be necessary, as
described in Section 2.2. For example,
float x = 1.68/2;
generates a compiler error, which can be corrected as follows:
float x = 1.68f/2;
• There is no exponentiation (raise to the power) operator.
However, ab, for example, may be computed with a method in the Math class: Math.pow(a, b).
To compute
√
n use Math.sqrt(n).
Precedence
The usual precedence rules of arithmetic are followed: * and / have a higher precedence than + and -.
If you are in doubt you can always use parentheses, which have an even higher precedence. Thus
a + b * c is evaluated by default as a + (b * c).
Where arithmetic operators in an expression have the same precedence the operations are carried out
from left to right. So a / b * c is evaluated as (a / b) * c, and not as a / (b * c).
Try Exercises 2.5 to 2.8.
The precedence levels of all Java operators discussed in this book are shown in Appendix B.
45. 28 Essential Java for Scientists and Engineers
Increment and decrement operators
If you are not familiar with Java (or C, to which Java is related) you will find the increment (++) and
decrement (--) operators intriguing. They provide a shorthand way of increasing or decreasing their
operands by 1. E.g.
c++; // increase c by 1
++c; // increase c by 1
x--; // decrease x by 1
--x; // decrease x by 1
So, for example, c++ is the same as the slightly more long-winded c = c + 1. (Did you realise that
this is where C++ gets its name: one more than C?)
When these operators appear in assignments (i.e. variable = expression) their position is crucial, since
the expression on the right may be incremented or decremented before or after its value is assigned to
the variable on the left. And so we have post-incrementing/decrementing, e.g.
a = x++; // set a to x, then increment x
b = x--; // set b to x, then decrement x
and pre-incrementing/decrementing, e.g.
a = ++x; // increment x, then set a to new value of x
b = --x; // decrement x, then set b to new value of x
The pre means the increment or decrement occurs before the assignment is made.
Note that it does not make sense to have x++ on the left-hand side of an assignment, so it is not
allowed.
The pre-increment and pre-decrement operators both have higher precedence than the arithmetic oper-
ators. So the code
int x = 1;
int y;
y = x + ++x;
sets x to 2 and y to 4. x is first incremented to 2, and then added to its new value to give 4.
Old-time C programmers delighted in writing concise yet obscure code like this. The practice stems
from the days when computer memory was limited, and when execution time was critical; sometimes
the obscure code runs a little faster.
However, with the multi-megabytes of RAM and Pentium power available today you simply can’t use
those excuses any more. Why not say what you mean, and replace the last statement above with:
++x;
y = x + x; // no ambiguity now!
Post-incrementing or decrementing is a little more subtle. The code
int x = 1;
int y;
y = x + x++;
sets y to 2. You can think of the post-incrementing being done in a temporary register, and only being
applied to its operand after the expression is evaluated. Once again, it is better to write clearly what you
mean, i.e.
y = x + x;
x = x + 1;
46. Java programming basics 29
Assignments and assignment operators
Simple assignments
The simple assignment operator is the equal sign (=). We have already seen a few examples of its use.
The most common form of a simple assignment is
var = expr;
The expression expr on the right is evaluated and its value assigned to the variable var on the left, e.g.
x = a + Math.sqrt( b ) + Math.cos( c );
n = n + 1; // increase the value of n by 1 (or n++)
Note the direction of the assignment: from the right-hand side of the equals sign to the left. It is a
common programming error to get the assignment the wrong way around, as in
n + 1 = n; // wrong way! wrong way! wrong way!
Java expects a single variable on the left-hand side and will object if it finds anything else.
More examples
The formulae
F =
GME
r2
,
c =
√
a2 + b2
2a
,
A = P
1 +
r
100
n
may be translated into the following simple assignments:
f = G * m * e / (r * r);
c = Math.sqrt( a * a + b * b ) / (2 * a);
a = p * Math.pow( 1 + r/100, n );
Try Exercises 2.9 to 2.10
Assignment operators
A statement like
sum = sum + x;
occurs so frequently in Java that it may be written more concisely as
sum += x;
The double symbol += is called an assignment operator. (The plus operator must be on the left of the
equals operator, otherwise it would be the unary addition operator.)
There are more assignment operators, such as -=, *=, /= and %=. Each assignment operator reduces
the expression
var = var op expr;
47. 30 Essential Java for Scientists and Engineers
to the shorter form
var op= expr;
Their precedence level in the general scheme of things is shown in Appendix B.
Cast operators
When an integer, for example, is divided by another integer, the decimal part of the result is lost
(truncated) even if it is assigned to a float or double variable. However, the use of a cast operator
can fix this. For example,
x = (float) 10 / 3;
assigns the value of 3.333333 (instead of 3) to x by using the (float) cast operator. Note that the
integer 10 is cast to a float before the division takes place.
Cast operators are available for any data type, and are formed by placing parentheses around the data
type name.
Try Exercises 2.11 to 2.20.
2.6 Repeating with for
So far we have seen how to get data into a Java program, how to temporarily store it in variables, how to
evaluate simple expressions, and how to output the results. In this section we look at a new and powerful
feature: repetition. We start by showing you some examples, which you should run. We will then explain
in detail how the for loop works.
As a very simple introductory example run the following code:
for (int i = 1; i = 10; i++)
{
System.out.print( i + );
}
You should get this output:
1 2 3 4 5 6 7 8 9 10
Can you see what’s going on? Change the print statement to println and see what happens.
Turtle spirals
In Chapter 1 we introduced you briefly to our Turtle class. We would like to use the turtle to draw
more interesting figures, for example, a spiral. To draw a spiral, the turtle has to move forward a certain
amount, change direction slightly, move forward slightly more, change direction again, move forward
slightly more, and so on. If we create a turtle called terry, and variable step,
Turtle terry = new Turtle();
double step = 10;
then the group of three statements
terry.forward(step);
terry.right(30);
step += 5;
48. Java programming basics 31
carry out the basic movement of taking a step, changing direction, and increasing the step. We simply
have to repeat these three statements to draw our spiral. Here’s the obvious way to do it:
import essential.*;
public class MyTurt
{
public static void main(String[] args)
{
Turtle terry = new Turtle();
double step = 10;
terry.forward(step);
terry.right(30);
step += 5;
terry.forward(step);
terry.right(30);
step += 5;
terry.forward(step);
terry.right(30);
step += 5;
terry.forward(step);
terry.right(30);
step += 5;
}
}
This program produces the rather crude attempt at a spiral in Figure 2.2. Clearly we could use cut-and-
paste to paste in as many copies of the three statements as we need. But that would be very tedious; our
program would become very long. What we want is a construction which repeats the three statements
for us. Java has such a device, called a for loop. The following program produces exactly the same
result as MyTurt, by repeating the group of three statements four times:
Figure 2.2 A crude spiral
49. 32 Essential Java for Scientists and Engineers
import essential.*;
public class SmartTurtle
{
public static void main(String[] args)
{
Turtle terry = new Turtle();
double step = 10;
for (int i = 1; i = 4; i++)
{
terry.forward(step);
terry.right(30);
step += 5;
}
}
}
In fact, the for loop is so powerful, we might as well use it to draw the much better looking Spiral of
Archimedes in Figure 2.3 (the steps and angles have been made smaller to get a neater spiral):
import essential.*;
public class ArchSpiral
{
public static void main(String[] args)
{
Turtle terry = new Turtle();
double step = 0.5;
double increment = 0.03;
double degree = 5;
Figure 2.3 The Spiral of Archimedes
50. Java programming basics 33
int numSpirals = 3;
int numLoops = (int)(360/degree) * numSpirals;
for (int i = 1; i = numLoops; i++)
{
terry.forward(step);
step += increment;
terry.right(degree);
}
}
}
The variable numLoops is used here as a counter. It evaluates to 216, which is the number of times the
basic group of three statements is repeated!
Growing an investment
The following program computes the value of an initial investment of $1000 over a period of 10 years
where interest of 12 per cent is compounded annually. Run it and see if you can follow how it works.
public class Invest
{
public static void main( String args[ ] )
{
double bal = 1000; // initial balance
double rate = 0.12; // interest rate
for (int year = 1; year = 10; year++)
{
bal = bal + rate*bal;
System.out.println( year + +
Math.round( 100*bal )/100. );
}
}
}
Output:
1 1120.0
2 1254.4
3 1404.93
4 1573.52
5 1762.34
6 1973.82
7 2210.68
8 2475.96
9 2773.08
10 3105.85
In this example, the for construct is used to repeat the two statements
bal = bal + rate*bal;
System.out.println( year + + ... );
10 times. Such a structure where the number of repetitions is determined by the user in advance (i.e.
10), is sometimes called determinate repetition.
51. 34 Essential Java for Scientists and Engineers
The for statement
The for loop is one of the most powerful constructs in programming. Its most common form is
for (int i = j; i = k; i++)
{
statements
}
Note:
• In this case i (the loop counter, or index) is any integer variable, and j and k may be constants,
variables or expressions.
It is recommended that the counter i be declared int in the for header as above. The effect of this
is that i is defined only in the scope of the block markers following the for header. This device
prevents i from conflicting with a variable of the same name outside the for loop.
• statements are executed repeatedly.
• The values of j and k determine how many repeats are made.
• i starts with the value j, and is incremented at the end of each loop.
• Looping stops once i exceeds the value of k, and execution proceeds in the normal way with the
next statement after the for.
• i will have the value k + 1 after completion of the loop.
More generally, for has the syntax
for (initialization; condition; increment)
{
statements
}
where initialization creates and initializes the loop counter, looping continues while condition is true,
and increment defines how the loop counter is incremented. All three are expressions.
The important thing to note here is that if a group of statements is to be repeated by a for loop the
statements must be enclosed in block markers {...}. Statements thus enclosed are treated syntactically
as a single statement.
It is also important to understand at what stage during the execution of the loop the three phases
initialization, condition and increment occur. Consider the following example,
for (int i = 1; i = 3; i++)
{
System.out.println( i*2 );
}
which has the output
2
4
6
Here is a blow-by-blow account of how the for executes:
1. The counter i is created and initialized to the value 1. This phase (initialization) occurs once only.
2. condition is tested: 1 = 3 is true.
3. Since condition is true, statements are executed: the value of i*2 (2) is printed.
4. increment occurs: the value of i increases to 2.
52. Java programming basics 35
5. condition is tested: 2 = 3 is true.
6. Since condition is true, statements are executed: the value of i*2 (4) is printed.
7. increment occurs: the value of i increases to 3.
8. condition is tested: 3 = 3 is true.
9. Since condition is true, statements are executed: the value of i*2 (6) is printed.
10. increment occurs: the value of i increases to 4.
11. condition is tested: 4 = 3 is false.
12. The loop terminates and control passes to the statement following the for block markers.
A very common error is to end the for clause with a semi-colon:
for (year = 1; year = 10; year++); { ... }
Can you explain what happens if you do this in the Invest program? The semi-colon terminates
the statement to be executed: in this case nothing—except incrementing year. So basically nothing is
repeated 10 times, after which the two statements in the block markers are executed exactly once.
Try Exercises 2.21 to 2.22.
Alternative ways of counting with for
In our examples of for thus far we have started counting at 1, which is a fairly natural thing to do, e.g.
for (int i = 1; i = 10; i++)
Many programmers prefer to start counting at 0 (it depends on how you were brought up), in which case
condition has to be changed subtly in order to secure the correct number of repeats:
for (int i = 0; i 10; i++)
Either way is acceptable; it just depends on whether you prefer counting from 0 or 1. For example, you
could rewrite the for in Invest as
for (int year = 0; year 10; year++)
However, year must then be replaced by (year+1) in the println statement to reflect the correct
year in the output. (Why would year++ be wrong here?)
In this book we will generally start counting at 1 in for loops, except in the case of array subscripts,
which invariably start at 0 (see Chapter 6).
Square rooting with Newton
The square root x of any positive number a may be found using only the arithmetic operations of
addition, subtraction and division, with Newton’s method. This is a neat iterative (repetitive) procedure
that refines an initial guess.
The structure plan of the algorithm to find the square root, and the program with sample output for
a = 2 is as follows:
1. Input a
2. Initialize x to 1 (the initial guess
3. Repeat 6 times (say)
Replace x by (x + a/x)/2
Print x
import essential.*;
53. 36 Essential Java for Scientists and Engineers
public class MySqrt
{
// square-rooting with Newton
public static void main(String args[])
{
double a; // number to be square-rooted
double x = 1; // guess at sqrt(a)
System.out.print( Enter number to be square-rooted: );
a = Keyboard.readDouble();
for (int i = 1; i = 6; i++)
{
x = (x + a/x)/2;
System.out.println( x );
}
System.out.println( Java’s sqrt: + Math.sqrt(a) );
}
}
Output:
Enter number to be square-rooted: 2
1.5
1.4166666666666665
1.4142156862745097
1.4142135623746899
1.414213562373095
1.414213562373095
Java’s sqrt: 1.4142135623730951
The value of x converges to a limit, which is
√
a. Note that it is virtually identical to the value returned
by Java’s Math.sqrt. Most computers and calculators use a similar method internally to compute
square roots and other standard mathematical functions.
Factorials!
Run the following program to generate a list of n and n! (spoken as ‘n factorial’, or ‘n shriek’) where
n! = 1 × 2 × 3 × . . . × (n − 1) × n.
int n;
long fact = 1;
System.out.print( Enter n: );
n = Keyboard.readInt();
System.out.println( n );
for (int k = 1; k = n; k++)
{
fact = k * fact;
System.out.println( k + != + fact );
}
• Change the above program so that only the final answer is printed out, and not all the intermediate
values. For example, if 20 is entered for the value of n, the only output should be
54. Java programming basics 37
20!= 2432902008176640000
• Can you figure out what’s happening when you try to compute n! for n 20?
Limit of a sequence
for loops are ideal for computing successive members of a sequence (as in Newton’s method above).
The following example also highlights a problem that sometimes occurs when computing a limit. Consider
the sequence
xn =
an
n!
, n = 1, 2, 3, . . .
where a is any constant, and n! is the factorial function defined above. The question is: what is the limit
of this sequence as n gets indefinitely large? Let’s take the case a = 10. If we try to compute xn directly
we could get into trouble, because n! gets large very rapidly as n increases, and numerical overflow could
occur. However, the situation is neatly transformed if we spot that xn is related to xn−1 as follows:
xn =
axn−1
n
.
There are no numerical problems now. The following program computes xn for a = 10, and increasing
values of n. Run it.
int k = 30; // number of terms
double a = 10;
double x = 1;
for (int n = 1; n = k; n++)
{
x = a * x / n;
System.out.println( n + + x );
}
Try Exercises 2.23 to 2.25.
Reading data from a text file
Another common use of the for statement is in reading data from files. Suppose you want to compute
the average of some data you have been collecting. As an example, use your text editor to create the
following text (ASCII) file, and save it under the name nums.txt:
10 3.1 7.2 4.5 9.9 6.0 7.9 3.7 9.2 6.5 3.9
The first value (10) is the number of data values to be read; it is followed by your 10 data values. The
following program reads them and prints their average:
import essential.*;
public class ReadNums
{
public static void main(String args[])
{
double n, x, sum, avg;
56. been carried to a ridiculous extent. And as for Jean de Meung's part,
there are plenty of touches in it which show that the writer, though
no heretic, had little sympathy with church matters; and would
certainly not be disposed to spend his time in laboriously concocting
a riddle of twenty thousand lines, the answer to which was to be
found in the Romish creed. And in Guillaume de Lorris himself, it is
difficult to find a word for or against the Church.
He was, no doubt, mindful of the stern lesson read to heretics in the
crusade of Provence, fresh in all men's recollection. But he had been
nurtured and fed on the poetry of the troubadours; the form of his
verse and the turn of his thought were Provençal. Was it likely that
so young a writer should escape the spirit of the literature while he
studied its form? And since in a time of violent religious excitement,
he can find no word of sympathy for a church which persecutes, is it
not probable that his sympathies are, if not with the Church
persecuted, at least with the people? The probability, moreover, of
there being a double allegory in the 'Romance of the Rose,' as
planned originally by Guillaume de Lorris, appears to us to be
strengthened by a further consideration of the Provençal literature
and the line of its development.
Love, in a time when life had few pleasures and distractions to offer
—when these were generally only to be snatched in the intervals of
fighting—became not only the symbol of all life's joy, but grew into a
kind of religion. It had its own ritual, its ceremonies, its sacraments,
its lessons, and its hymns. Aged poets were its bishops, the
guardians of its forms; young poets its priests; instead of the images
of saints, were living women, and instead of the procession and the
chant, were the love song and the dance. It was nothing new to the
Provençal to celebrate the religious worship with a dance. He alone,
among Christians, preserved a custom handed down from old pagan
times, and as late as the sixteenth century, the worthy people of
Marseilles welcomed Christmas in this way.
The other sex would naturally offer few obstacles to a homage
which, though it sometimes destroyed their virtue, always flattered
57. their vanity, and invested them with a power which was beyond that
of kings. Princes, indeed, might make men rich, but women alone
could make men happy. An accurate knowledge of love's ceremonies
became part of the education of a gentleman; these were reduced,
like those of chivalry, to a sort of code; questions of law, so to
speak, arose, which were tried with great solemnity at courts of law
where ladies were judges; appeals from these decisions were often
made to higher courts, and there is every reason to believe that the
Arrêts d'Amour, numerous examples of which are given in the work
of Martial d'Auvergne, were courts as serious and as gravely
disputed in times of peace, as those which decided other differences
of opinion. From being, therefore, the legitimate end of a young
man's hope, the chief solace of his life, love grew gradually to be
surrounded by all sorts of restrictions and ceremonies, and losing its
charm of spontaneity and freedom, was idealized until it lost itself,
and became the mere shadow of a poetic dream. As every idea,
pushed beyond its legitimate limits, provokes some kind of rebellion,
two streams of thought presently diverged from the main channel,
one of them, with which we have nothing to do, satirical, cynical,
earthly and gross; the other, religious. Sexual love is only possible,
or is strongest when life is young and the blood is strong and
hopeful; as years creep on and the end of things approaches, its
insufficiency to satisfy the cravings of the soul must become, even to
its most ardent votary, more and more deeply apparent. The days
when a smile from his mistress made him, according to the rules of
the craft, happy, or a frown miserable, would leave behind them,
when they had passed away, an increased sense of the real
seriousness of life; while at the best of times, the art of love would
not be felt as anything but elegant trifling, and the passion which it
excited, transitory. Women, too, the object of all this homage, were
really, though they might not know it, degraded by what was
intended to do them honour. And let those who lament the
subjection of the sex, own that the extravagant honour paid to ladies
in the Middle Ages has had something, at least, to do with it. From
some such feelings as the above, we believe it came to pass that the
poet began first to imagine, and then to contrive, for his love songs
58. a deeper and a mystical meaning. The sentiment of nearly all the
Provençal poets, as regards women, was delicate, elevating to
themselves, and enthusiastic. Women are to men, in the poet's
imagination, what heaven is to earth; their gentleness contrasts with
man's ferocity, their weakness with his strength, their strength with
his weakness. Love is the principle of all honour and merit, the
mainspring of every noble action; its desires and its pleasures are
only legitimate, inasmuch as they are as a stimulus to the painful
duties of chivalry; the springs of poetry are in love; without love
there is nothing that civilizes, softens, or elevates. But earthly love,
so high, so pure, so separated from the common instincts of the
world, is but a type of that infinitely higher and purer heavenly love.
All the allegories of the poets are to be read in a deeper sense by
those who are initiated into the mysteries, and when a poet sings
songs of love, he is singing songs of a mysterious religion.
That this was the case with all the troubadours, or even with most of
them, we do not affirm; that it was at one time believed to be true
of all of them seems tolerably clear. And no doubt many an honest
bard, quite simply putting down his thoughts about his mistress's
lips, or the tangles of her hair, would have been astonished to hear
that he was preaching the glories of the Virgin, or advocating a free
and Pope-less Church. On the supposition that Guillaume de Lorris
was one of those who had learned from the troubadours the art of
double allegory, and that he conveyed religious teaching under this
disguise, we should expect to find the key to his poem in the
religious difficulties of his time. It is not, at least, difficult to get at
these.
The people of Provence[51] had always mixed freely with the
educated Mahometans of Spain, and the wealthy Jews who lived
among them: their own Christianity sat lightly upon them, as a cloak,
the fashion of which might at any time be altered; theology was held
in universal disesteem, and the priesthood, taken from the lowest
strata of society, were objects of pity and contempt: a widespread
heresy existed, which does not appear to have had much, if anything
59. to do with modern Protestantism, holding 'erroneous views' on
Baptism and the Eucharist, rejecting the Old Testament, denying the
authority and necessity of the priesthood, and even repudiating, in
some cases, marriage itself. It was growing rapidly not only in
Switzerland and Languedoc but also in the Nord, in England, and in
Germany, by means of wandering bards, who scattered their new
doctrines broadcast wherever they went. By local persecutions and
burnings, attempts were made to stop it, but in vain; and Rome saw
with consternation a province the most cultivated, the most richly
endowed with genius, the most wealthy, that from which the
greatest help for the Church was to be expected, a prey to free
thought of the most unbridled kind.
As soon as persecution began, or even suspicion of the truth, the
poets would see the necessity for veiling their thoughts under
carefully-constructed allegories, and while they chanted a
monotonous refrain on one of the many rules of love, secretly
inculcated a code of doctrines more subversive than any the Church
had yet combated. Occasionally we hear a voice which speaks aloud,
and plainly enough, to let us know the kind of thing that was
whispered. Thus Fauriel gives the following from Pierre Cardinal.[52]
He is considering the insoluble problem of suffering and evil, and
cries, with a boldness that has more despair than blasphemy in it
—'At the Last Day I shall say, myself, to God that He fails in His duty
to His children if He thinks to destroy them and plunge them into
Hell.... God ought to use gentleness and to keep His souls from
trespass.'
Voluptuous, loose in morals, satirical, and careless as these poets
were, they yet have the merit of boldly using thought, and carrying
conviction to its logical and legitimate end. They anticipated the
movement of the fifteenth century, without its knowledge and higher
light: their penalty was extermination, thorough and complete. The
land was destroyed; its cities burned; the people massacred; Pope
and kings combined to make a desert, and to call it peace.
60. What could the Church do more? What indeed, could she do less?
For the war was a struggle for existence, and the heresies of
Provence were only the most formidable in a general movement of
free thought which shook the powers of Rome to its very
foundations. But one thing the Church could not do. The flame of
insubordination and opposition could be handed down in secret.
Things that could not be attacked openly, might be attacked secretly.
There were secret societies in the Middle Ages, which had a real and
definite object, the danger and the terror of the Church.[53] And to
this day Rome excommunicates the members of all secret societies,
whether the mild and convivial Freemason or the bloodthirsty
Fenian. The Society of Jesus is the only secret society to which a
Roman Catholic may belong. Guillaume de Lorris belongs to a time
when doctrine was secretly assailed; his successor, Jean de Meung,
to a time when practice was openly assailed. For men very soon left
off attacking their enemies by allegory, and Guillaume de Lorris, if he
was indeed one of that school, was one of its last disciples.
Whether he was, or was not, can never now be satisfactorily
answered. He left his poem unfinished, hardly, perhaps, begun.
Whatever has to be said on the subject of its original plan, must be
necessarily conjectural. We incline, on the whole, to believe that he
did have a religious purpose, which was not understood by Jean de
Meung; that one who bears in mind the religious history of Provence
as well as the character of its situation, may well construct an
interpretation of the work of Guillaume de Lorris far more probable
and consistent than that of Molinet or of Marot.
Jean de Meung, so-called because he was born at the little town of
Meung, in the department of Loiret—
'De Jean de Meung, s'enfle le cours de Loire.'
Jean Clopinel, Limping John, because he was lame, finding himself,
some forty years later, with his head stuffed full of all the learning of
his time, and nearly bursting with sentiments, convictions, and
opinions, on religion, politics, social economy, and science, began,
61. one may suppose, to cast about for some means of getting rid of his
burden. Lighting on the unfinished and half-forgotten work of
Guillaume de Lorris, he conceived the idea of finishing the allegory,
and making it the medium of popularizing his own opinions. He could
hardly have hit upon a readier plan. It was not yet a time for popular
science; there were no treatises in the vernacular on history,
theology, and political economy, and the only way of getting at
people was by means of rhyme. But Jean de Meung was no
allegorist, and no storyteller. He took up the tale, indeed, where his
predecessor left it, and carried it on, it is true, but in so languid a
manner, with so many digressions, turns and twists, that what little
interest was originally in it goes clean out. Nothing can well be more
tedious than those brief portions devoted to the conduct of the story.
It finishes, somehow. Love calls his barons together, is defeated,
sends an embassy to his mother, Venus, who comes to his
assistance; the fortress is taken, Bel Accueil is released, and the
Rose is plucked. In the course of the poem, Malebouche gets his
tongue cut out, Déduit, Doux Regard, Léesce, Doux Penser, and
others drop out of the allegory altogether; the Garden is forgotten;
all the little careful accessories of Guillaume de Lorris, such as the
arrows of Love and his commandments, are contemptuously
ignored. Those that remain are changed, the Friend in the second
part being very different from the Friend in the first, while Richesse
appears with a new function. Every incident is made the peg for a
digression, and every digression leads to a dozen others. The losses
of the old characters are made up by the creation of new ones, and,
in Faux Semblant, the hypocrite and monk, Jean de Meung
anticipates Rabelais and surpasses Erasmus.
Between Guillaume de Lorris and his successor there is a great gulf
hardly represented by the forty years of interval. Men's thoughts had
widely changed. The influence of Provençal poetry was finally and
completely gone, and its literature utterly fallen, to be revived after
many centuries only by the scholar and the antiquarian. More than
this, the thoughts and controversies of men which had turned
formerly upon the foundations of the Christian faith, now turned
62. either on special points of doctrine, or on the foundation and
principles of society.
No writers, so far as we remember, have noticed the entire
separation between the two parts of the romance. They are
independent works. Even the allegory changes form, and the idea of
the trouvère, Guillaume, was lost and forgotten when his successor
professed to carry it on.
In passing from one to the other, the transition is like that from a
clear, cold, mountain stream to a turbid river, whose waters are
stained with factory refuse, and whose banks are lined with busy
towns. The mystic element suddenly disappears. Away from the
woodland and the mountains and among the haunts of men, it
cannot live. The idea of love becomes gross and vulgar. The fair,
clear voice of the poet grows thick and troubled; his gaze drops from
the heavens to the earth. It is no longer a trouvère bent on
developing a hidden meaning, and wrapping mighty secrets of
religious truth in a cold and careful allegory; it is a man, eager and
impetuous, alive to all the troubles and sorrows of humanity, with a
supreme contempt for love, and for woman, the object of love, and a
supreme carelessness for the things that occupied the mind of his
predecessor. We have said that new characters were introduced. The
boundaries of the old allegory were, indeed, too narrow. Jean de
Meung had to build, so to speak, the walls of his own museum. It
was to be a museum which should contain all knowledge of the
time; to hold miscellaneous collections of facts, opinions, legends,
and quotations, than which nothing can be more bewildering,
nothing more unmethodical, nothing more bizarre.
As a poet he is superior, we think, to his predecessor, though
Guillaume de Lorris can only be reckoned as a second-rate versifier.
He is diffuse, apt to repeat himself, generally monotonous, and
sometimes obscure. His imagination is less vivid, and his style less
clear, than those of Guillaume de Lorris. Occasionally, however,
passages of beauty occur. The following, for example, diffuse as it is,
appears to us to possess some of the elements of real poetry. The
63. poet is describing a tempest followed by fair weather. Nature weeps
at the wrath of the winds:—
'The air itself, in truth, appears
To weep for this in flooded tears.
The clouds such tender pity take,
Their very clothing they forsake:
And for the sorrow that they bear,
Put off the ornaments they wear.
'So much they mourn, so much they weep,
Their grief and sorrow are so deep,
They make the rivers overflow,
And war against the meadows low:
Then is the season's promise crossed;
The bread made dear, the harvest lost,
And honest poor who live thereby,
Mourn hopes that only rose to die.
'But when the end arrives at last,
And fair times come, and bad are passed;
When from the sky, displeased and pale,
Fair weather robs its rain and hail,
And when the clouds perceive once more
The thunder gone, the tempest o'er—
Then they rejoice, too, as they may,
And to be comely, bright, and gay,
Put on their glorious robes anew,
Varied with every pleasant hue;
They hang their fleeces out to dry,
Carding and combing as they fly;
Then take to spinning, and their thread
Abroad through all the heavens spread,
With needles white and long, as though
64. Their feathery gauntlets they would sew—
Harness their steeds, and mount and fly
O'er valleys deep and mountains high.'
It is needless, after what has been said, to pursue any further the
story of the romance. There is not much lost by this omission,
because the work has really little or nothing to do with the allegory,
and might simply be called, 'The Opinions of Jean de Meung.' Our
object is to show what actually were the opinions of a scholar of
liberal views in the thirteenth century.
They may be divided into four classes, foremost of which, in his own
mind, stands his hatred of monks. In religion he was not an infidel,
or even a heretic; he was simply in opposition. He writes, not against
sacerdotalism, but against the inversion of recognised order by the
vagabond friars. Order, indeed, he would insist upon as strenuously
as Hooker himself; but order he would subordinate to what he
deems the most essential thing, personal holiness. To decry, deride,
and hurl contempt on the monastic orders: to put into the strongest
possible words the inarticulate popular hatred of these was, we
believe, his leading thought when he began his book.
His second idea was to make an angry, almost furious protest
against the extravagant respect paid to women, and an onslaught on
their follies and vices. It is very curious, and shows how little he was
trammelled by his allegory, that he fails altogether to see how
entirely out of place is such an attack in the 'Romance of the Rose.'
He had two other principal ideas: one to communicate in the
common tongue as much science as the world could boast; and the
other, to circulate certain principles of vague socialism and hesitating
republicanism which were then beginning to take the place of those
religious speculations which occupied men's minds in the early part
of the century.
Jean de Meung's was not the only book of the time which aimed at
being an encyclopædia, but it was by far the best known and the
65. most widely répandu. There were written towards the close of the
thirteenth century certain collections called trésors, which were
designed to contain everything that was to be learned, quicquid
scibile, in mathematics, physics, astronomy, alchemy, music,
speculative philosophy, and theology. They were generally in verse;
one of the best of them being by a monk, called 'Mainfroi,' which
professedly contained the Arabic learning, borrowed from the Moors
in Spain. Probably Jean de Meung had access to this. Readers of old
English literature will also remember that dreariest of dreary books,
Gower's 'Confessio Amantis,' into which the hapless student plunges
without hope, and emerges without profit, having found nothing but
vapid imitation, monotonous repetition, and somnolent platitudes.
The 'Confessio' is a trésor, and designed to contain all the science of
the time. It is adapted, so far as the science goes, from a trésor
called the Secretum Secretorum.
Let us, then, gather some of the opinions of our author, classifying
them according to this fourfold division. It may be premised that the
division was not thought of by the poet, from whom, indeed,
sequence and method are not to be expected.
Liberal thought, in the time of Jean de Meung, did not attack the
domain of doctrine, partly, perhaps, from an unwillingness to meet
the probable consequences of a charge of heresy; indeed, when
doctrine came in its way, it seems to have leaned in the direction of
orthodoxy. Thus we find Jean de Meung siding with Guillaume de St.
Amour in an attack on the 'Eternal Gospel,' that most extraordinary
book, ascribed to Joachim, Abbot of Flora,[54] which was intended to
have the same relation to Christianity which Christianity bears to
Judaism, to be at once its fulfilment and its abolition, which was to
inaugurate the third and last, the perfect age, that of the Holy Spirit.
The mendicants, an ignorant, credulous body, quite incapable of
appreciating cause or consequence of teaching, espoused the cause
of the book; Guillaume de St. Amour arraigned them, not only of the
ordinary vices attributed to them—vices entirely contrary to their
vows—but as preachers of doctrines pernicious, false, and heretical.
66. Probably Jean de Meung was actuated by esprit de corps, Guillaume
de St. Amour being a champion of the University of Paris, as well as
by hatred to the monks, and, in spite of his hard words, was not
moved strongly by any specially inimical feeling towards the book.
Following the instincts of his time, however, he flatly ascribes its
authorship to the Devil, the alleged author of so many theological
books. Partizanship in those days, as in ours, meant, to be effective,
a good, sound, honest hatred, and much command of language. In
his description of hell, Jean anticipates the realistic horrors of Dante.
'What guerdon,' he asks, 'can the wicked man look for, save the cord
which will hang him to the dolorous gibbet of hell? There will he be
rivetted with everlasting fetters before the prince of devils; there will
he be boiled in cauldrons; roasted before and behind; set to revolve,
like Ixion, on cutting wheels turned by the paws of devils; tormented
with hunger and thirst, and mocked with fruit and water, like Tantalus,
or set to roll stones for ever up hill, like Sysyphus.'
One thing seems here worthy of remark. The place of punishment
for the wicked man, in the Middle Ages, was the torture-chamber of
their own criminal courts, intensified by imagination. Their
punishment was through the senses. Of mental agony they had no
conception. Yet, strangely enough, their heaven was never a heaven
of the senses; and it shows how deeply they were penetrated with
the feeling of Christ's holiness that while every temptation seemed
set to make the mass believe in a paradise like that of Mahomet, the
heaven of Christendom has always offered, as its chief charm, the
worship and praise of a present God. 'There, by the fountain of
mercy,' says Jean de Meung, 'shall ye sit.'
'There shall ye taste that spring so fair;
(Bright are its waters, pure and clear),
And never more from death shall shrink,
If only of that fount you drink.
But ever still, untired, prolong
The days with worship, praise, and song.'[55]
67. The poet reserves, however, his chief strength and the main
exposition of his views for his character of Faux Semblant—False
seeming—the hypocrite. There is a dramatic art of the very highest
kind in the way in which Faux Semblant draws and develops his own
character, pronounces, as it were, the apology of hypocrisy. His
painting of the vices of the mendicant orders cannot approach those
of Walter de Mapes, of Erasmus, and of Buchanan, in savage
ferocity; but it is more satirical and more subtly venomous than any
of those, and has the additional bitterness that it is spoken as from
within the body which he attacks. The others, standing outside the
monastic orders, point the finger of scorn at them. Jean de Meung
makes one of themselves, an unblushing priest, with a candour
which almost belongs to an approving conscience, with a chuckling
self-complacency and an entire unconsciousness of the contrast
between his life and his profession, which rises to the very first order
of satirical writing, depict his own life, and take credit for villanies
which he takes care to inform us are common to his order. He has
been compared with Friar John; but the animalism and lusty vigour
of this holy man lead him to a life of jovial sensuality through sheer
ignorance; whereas Faux Semblant, his conscience seared with a hot
iron, sins against the light. We may compare, too, the attacks made
by Jean de Meung's contemporaries and immediate successors. They
never even attempt satire.[56] It was an instrument whose use they
could not comprehend. Their line is invective, as when Rutebeuf
says, in his straightforward way—
'Papelart et Beguin,
Ont le siècle honi.'
or, as Eustache Deschamps attacks the pluralists—
'Prestres et clers qui tenez vos monciaulx
De chapelles, vous autres curiaulx,
Des povres clers ayez compassion:
Repartez leur ces biens ecclesiaulx,
Afin que Dieu vous soit propiciaulx:
68. Vous les tenez à vo dampnacion.'
Faux Semblant, in his sermon, or address, a small part only of which
we consider, begins by telling his hearers that he lives, by
preference, in obscurity, and may, therefore, chiefly be found where
this is most readily obtained, viz., under a religious habit. With the
habit, however, he does not put on the reality of religion. He
attaches himself to powerful patrons; he goes about preaching
poverty, but living on the best of everything; nothing can be more
contrary to his experience than that religion is to be found at all
under the robe of a monk; nor does it follow that men and women
lead bad lives because they wear a worldly garb; very many, indeed,
of the saints have been married, were parents of children, and men
and women of the world.
He tells how he changes his habit from time to time; how, out of the
religious life, he 'takes the grain and leaves the straw;' how he hears
confession and grants absolution, as well as any parish priest; but
how, unlike the parish priest, he will hear the confessions only of the
rich, who can afford to pay; 'let me have the fat sheep, and the
pastors shall have the lean.' So with the poor; he will not help any.
'Let dying beggars cry for aid,
Naked and cold on dunghill laid:
There stands the hospital, with door
Wide open to receive the poor.
Thither let all who please repair,
For help nor money can I spare:
No use for me to save their life:
What can he give who sucks his knife?'
Now, with the rich it is different; and the mendicant, while he takes
the alms of those whose sins he has heard, may glow with conscious
virtue, reflecting that the rich are much more exposed to temptation,
and therefore, as a rule, more grievously weighed down with a sense
of guilt than the poor. When relief can be given, surely it should first
be bestowed on those who need it most. Mendicancy, Faux Semblant
69. acknowledges with an engaging candour, is only right when a man
has not learned and cannot learn a trade. Monks, according to the
teaching of Saint Augustine, ought to earn their bread by labour, and
when we are commanded to give all to the poor, it is not meant that
we should take it back by begging, but that we should work for our
living. But the world, neglecting this among other wholesome rules,
has set itself to rob, plunder, and despoil, every man trying to get
whatever he can from his neighbour. As for himself, his business, and
that of his brethren, is to rob the robber: to spoil the spoiler.
The mendicants keep up their own power by union; if a man does
one of them an injury, they all conspire to effect his ruin: if one
hates, all hate: if one is refused, all are refused, and revenge is
taken: if any man is conspicuous for good deeds, they claim him as
their own disciple, and in order to get the praise of people and
inspire confidence, they ask, wherever they go, for letters which may
testify to their virtue, and make people believe that all goodness
abounds in them.
He says that he leaves others to retire into hermitages and caves,
preferring to be called the Antichrist of robbers and hypocrites: he
proclaims himself a cheat, a rogue, a liar, and a thief: he boasts that
his father, Treachery, and himself rule in every realm, and that in the
security of a religious disguise, where no one is likely to suspect him,
he contrives various means to charm and deceive the world. Set
forth in this bold fashion, the discourse of Faux Semblant loses all its
dramatic force. It is fair, however, to state that this is chiefly found in
detached passages, and that the sermon is entirely spoiled by the
many digressions, notably that on the 'Eternal Gospel,' which are
found in it. Chaucer's rendering of this portion appears to us to be
far less happy than the rest of his work.
Another long and very curious dissertation, into which there is no
space here to enter, is that on Predestination, where he arrives at
the conclusion that the doctrine must be accepted as a dogma in
Christian faith, but that it need not affect the Christian life—
70. 'For every man, except a fool,
May guide himself by virtue's rule.'
A conclusion which seems almost to anticipate the conclusion arrived
at in the Article of the Church of England.
The sum of Jean de Meung's religious teaching is to be found in the
sermon of Genius—
'And, Lords and Ladies, this be sure,
That those who live good lives and pure;
Nor from their work and duty shrink,
Shall of this fountain freely drink.—
To honour Nature never rest,
By labour is she honoured best;
If others goods are in your hands,
Restore them all—so God commands.
From murder let all men abstain;
Spotless keep hands, and mouth keep clean.
Be loyal and compassionate,
So shall ye pass the heavenly gate.'
The one thing insisted on by Jean de Meung is the absolute
necessity of a pure life. A profound sense of the beauty of a pure life
is, indeed, the key-note to all mediæval heresies and religious
excitements.[57] The uncleanness of the clergy was the most terrible
weapon wielded by the heresiarchs. Thus Peter de Brueys compelled
monks to marry. Henry the Deacon taught that the Church could
exist without priests. Tanchelin of Antwerp held that the validity of
the sacraments depended on the holiness of him who administered
them. Peter Waldo sent out his disciples two by two, to preach the
subversive doctrine that every virtuous man was his own priest;
while the Cathari went gladly to the stake in defence of their
principle that absolute personal purity was the one thing acceptable
to God. The more ignorant the age, the wider is religious
71. speculation; but in the most ignorant ages, there rises up from time
to time a figure with a spiritual insight far beyond that of more
learned times. Protestantism in its noblest form has found nothing
more sublime than this conception of a Church where every good
man is a priest; and there is nothing in the history of religious
thought more saddening than these efforts of the people, ever
hopeless, ever renewed, to protest against dogma, creed,
perfunctory and vicarious religion, and to proclaim a religion of
personal holiness alone.
Let us turn to the second division. We find the book teeming with a
misogyny, bitter enough to make us believe that there must have
been some personal cause for it. 'What is love?' he asks. 'It is a
maladie de pensée—the dream of a sick fancy.... There is a far
higher and nobler thing in the friendship of men.' And it is after
narrating the stories of 'Penelope' and 'Lucretia,' that he puts into
the mouth of Jealousy the famous couplet—
'Toutes estes, serez, ou fustes,
De faict ou de voulenté, putes.'
Of course it may be urged that these are the words of jealousy, and
not of the poet; but, unfortunately, there are so many indications of
the author's entire approval of the sentiment, that the plea is hardly
worth much. Take, for instance, the dramatic scene, when the wife
worms out her husband's secret; or that of the old woman's lesson
to Bel Accueil, where, as in the case of Faux Semblant, he puts
woman's condemnation in her own mouth. She teaches him the art
of love almost in Ovid's own words; she prefaces her lesson by a
lament over the past days of youth and beauty; her regrets are not
for a life of sin and deceit, but for the past bad days that can come
no more. She is steeped in wickedness and intrigue; she can see no
happiness, except in love and luxury.
'My days of gladness are no more;
Your joyous time is all before;
Hardly can I, through age and pain,
72. With staff and crutch, my knees sustain.
Almost a child, you hardly know
What thing you have to bear and do.
Yet, well I wot, the torch that all
Burns soon or late, on you will fall;
And in that fount where Venus brings
Her maidens, will you drench love's wings.
But ere you headlong enter, pause,
Listen to one who knows Love's laws.
Perilous are its waters clear;
He risks his life who plunges here
Without a guide. Who follows me
Safe and successful shall he be.'
She tells of her vanished youth and all the pleasant follies of her
young days; how she threw away her affections on a scoundrel, who
only robbed and ill-treated her; how she wasted her money and
neglected her chances; how she grew old, and her old friends
ceased to knock at her door.
'But ah! my child, no one can know
Save him who feels the bitter woe,
What grief and dolour me befell
At losing what I loved so well.
The honeyed words, the soft caress,
The sweet delight, the sweet embrace;
The kisses sweet—so quickly sped,
The joyous time so quickly fled.
Fled! and I left alone to mourn.
Fled! never, never to return.'
The whole passage is full of the truest touches of nature, and is
written with a verve quite extraordinary. Villon has imitated it in his
ballad of the Belle Heaulmière,—
'Avis m'est que j'oy regretter
La belle qui fust Heaulmière;
73. Soy jeune fille souhaiter
Et parler en ceste manière.
Qu'est devenu ce front poly,
Ces cheveulx blonds, sourcils voultiz,
Grant entr'œil, le regard joly,
Dont prenoye les plus subtils;
Ce beau nez ni grand ni petit;
Ces petites joinctes oreilles;
Menton fourchu, cler vis, traictiz
Et ces belles lèvres vermeilles?'
And Béranger sings in the same key,—
'Combien je regrette
Mon bras si dodu,
Ma jambe bien faite,
Et le temps perdu.'
Jean de Meung's old woman is no more reformed than her
successors. And she tells Bel Accueil all that Ovid had to impart.
It is quite possible that in putting an imitation of the 'Art of Love' into
the old woman's mouth, Jean de Meung catered to the lowest tastes
of the age, and courted a popularity from this part of his work which
he might not have obtained from the rest. The same sort of defence
—no defence at all, but another and a worse charge—has been set
up in the cases of Rabelais and Swift. All such offenders we are told,
deferred to popular opinion, and wrote what they inwardly
disapproved. This surely is worse. To be yourself so far depraved as
to take delight in things impure is bad; to deliberately lay yourself
out to please others with things impure is surely infinitely more
wicked. It is possible that Jean de Meung, Rabelais, and Swift, did
this; but we do not think it probable. In the case of the poet whom
we are now considering, there seems every reason to believe that he
had formed the lowest possible ideas of love and women; that from
74. the depths of a corrupted morality, which permitted him the same
pleasure in impurity which the common herd of the vulgar and
illiterate shared, he had eager yearnings for that purity of life which
alone as he felt and preached, could bring one to taste of the
heavenly spring. That a man could at the same time grovel so low
and look so high, that his gaze upwards was so clear and bright,
while his eyes were so often turned earthward, is a singular
phenomenon; but it is not a solitary one. Other great men have been
as degraded as they were exalted. Perhaps when Christiana and her
children saw that vision of the man with the muck-rake, while the
angel, unregarded, held the crown of glory over his head, had they
looked much longer, they might have seen him drop his rake and
gaze upwards, with streaming eyes, upon the proffered glory. Jean
de Meung was the man with the muck-rake who sometimes looked
upwards.
The poet feels it necessary to apologize for his severity against the
sex. 'If,' he says, 'you see anything here against womankind, blame
not the poet.'
'All this was for instruction writ,
Here are no words of idle wit.
No jealousy inspired the song;
No hatred bears the lines along.
Bad are their hearts, if such there live,
Who villainie to women give.
Only, if aught your sense offend,
Think that to know yourself is good,
And that, with this intent, your friend,
I write what else might seem too rude.'
He thinks it right, too, to make a sort of apology for the severity of
his attack on monks.
'I strung my bow: I bent it well;
And though no saint, the truth to tell
I let my random arrows fly,
75. In lowly town and cloister high.
For what cared I where'er they lit?
The folk that Christ called hypocrite,
Who here and there are always found,
Who keep their Lent the whole year round,
But feed on live men's flesh the while
With teeth of envy and of guile,
These were my mark; no other aim
Was mine except to blot their fame.'
Let us pass to what is perhaps the most curious part of the book,
and the richest for the student of mediæval ideas, that in which he
gives us his views on the growth and principles of society. Here are
advanced theories of an audacity and apparent originality which
make one curious to know how far they penetrated into the lower
strata of France; whether they were the speculations of a dreamer,
or the tenets of a school; whether there was any connection—it is
more than possible—between this kind of teaching and the frantic
revolt of the peasantry; whether, in fact, Jean de Meung was a
prophet with a following, or a visionary without disciples. Read, for
instance, his account, somewhat abridged, of the Golden Age:—
'Once on a time, in those old years,
When lived our grandsires and forbears,
(Writers, by whom the tale we know,
And ancient legends, tell us so),
Love was loyal, and true, and good;
The folk was simple; the fare was rude;
They gathered the berries in forest and mead:
For all their meat and all their bread;
They wandered by valley and plain and mountain,
By river and forest and woodland fountain,
Plucking the chestnuts and sweet wild fruits,
Looking for acorns and rustic roots.
76. They rubbed together the ears of wheat;
They gathered the clustering grape to eat;
Rich fare they made when the forest bees
Filled with honey the hollow trees:
Water their drink; and the strong red wine
Was not yet pressed from the autumn vine.
'When sleep came with the shades of night,
They spread no beds of down so light,
But stretched in their cabins on piles of hay,
Fresh gathered grass and leaves they lay.
Or slept without—when the air was mild—
And summer winds were hushed and stilled;
When birds in the early morning grey
Awoke to welcome, each in his way,
The dawn that makes all hearts so gay.
In that glad time when the royal pair,
Flora—Queen of the flowers fair—
And Zephyr, her mate, give timely birth
To flowers of spring, through all the earth.
... 'such splendour give
That you might think the world would strive
With Heaven itself for glory—so bright,
So fair, so proud, with its flowers bedight.
Then in the woods they lay at ease,
Over their heads the branching trees—
Lovers kissed, who lovers were,
And kissed again, and had no fear—
Then they chaunted rounds and lays,
Joyously led their sports and plays:
A simple folk; they had no prayer—
No fond ambition—nor other care
Then just to live a life of joy—
77. And loyal love without annoy.
No king or prince was with them yet
To plunder and wrong, to ravish and fret;
There were no rich, there were no poor,
For no man yet kept his own store:
And well the saying old they knew—
(Wise it is, and is proven true)
Love and Lordship are two—not one:
They cannot abide together, nor mate:
Who wishes to join them is undone,
And who would unite will separate.'
Or, as Dryden, who certainly never read the 'Romance of the Rose,'
unless perhaps in Marot's edition, says:—
'Love either finds equality, or makes it.'
The end of the Golden Age—a thing not generally known—was
accelerated by Jason's voyage, the hero bringing home with him
treasures from Outremer: people begin to get ideas of property: they
amass wealth: they rob and fight for plunder: they go so far as to
divide the land. 'La propriété,' says Proudhon, 'c'est le vol.'
'Even the ground they parcelled out,
And placed the landmarks all about;
And over these, whene'er they met,
Fierce battle raged. What they could get,
They seized and snatched; and everywhere
The strongest got the biggest share.
So that at length, of plunder tired,
Needs must a guardian should be hired.
A sturdy peasant chose they then,
The mightiest of the sons of men;
78. Strongest in battle or in ring,
And him they chose to be their king.'
Voltaire has exactly the same idea:
'Le premier roi fut un soldat heureux.'
This is the origin of royalty. The growth of feudalism, of armies,
taxation, and division into classes is carefully traced from these small
beginnings.
But he deduces the great law of charity and love for our neighbours.
Having this, we have everything; and wanting this, we get wars,
tyranny, and all the miseries of the world.
What is the nature of true gentility? Lineage, he explains, has
nothing to do with it. None are gentle, but those whose virtues make
them so. Ancestors may leave their wealth behind them, but not the
qualities that made them great. Clerks have an advantage over
unlettered persons in knowing what is right. If they are coarse and
rude, they sin against greater light, and incur heavier punishment.
'Let him, who gentleman would be,
From sloth and idleness keep free;
In arms and study be employed,
And coarse rusticity avoid.
Let him, with humble, courteous grace,
Meet every class in every place;
Honour all women, wife or maid,
So that not too much trust be laid
In woman's faith. So may he steer,
Of this great danger wholly clear.
Know all that gentle blood may bring
No benefit, or anything,
Except what each man's worth may give.
Know, also, none of all that live
79. Can ask for honour, praise, or blame
By reason of another's name.'
The idea, of course, is not new. It is found frequently enough in the
Greek and Latin literature. It occurs, we believe, for the first time in
the fragments of Epicharmus,—
ἀγαθὸς δ' ἄνηρ κἂν Αἰθίοψ καὶ δοῦλος, εὐγενὴς ἔφυ.
and afterwards it is found in Euripides, Horace, Juvenal—'Stemmata
quid faciunt?'—and, lastly, in Seneca. Doubtless, Jean de Meung took
it from Seneca. Once started anew, the idea, of course, became
popular, and poet after poet repeated it, until it became a mere
commonplace. But so far as we have been able to discover, Jean de
Meung gave it new life.
A few words only, for our limits press, on the natural science taught
in the 'Romance of the Rose.' The poet, having got rid of this
indignation and wrath that lay at his soul anent the mendicant friars,
and the vices of women, wishes now, it seems, to sit down for a
quiet and comfortable disquisition on universal knowledge, including
alchemy, in which he is a firm believer; indeed, he wants to pass, in
a certain ballad of his, for an adept. This part takes the form of a
confession of Nature to her chaplain Genius (in which Power
afterwards copies him). The confession is long and wearisome, but it
is curious as being the earliest and fullest popular account of
mediæval science.
He fancies Nature to be perpetually at work, fashioning creatures
whom Death continually tries to destroy.
'Nature, who fashions all that holds
The sky beneath its ample folds,
Within her forge meanwhile was found,
And at her work's eternal round,—
Struck out new forms of every race,
Lest life should fail, and types should cease;
She made so many, that Death, who toiled
80. With heavy mace to kill, was foiled.
They fly to save themselves, where'er
Their fate may lead, or feet may bear;
Some to the Church and convent rule,
Some to the dance, some to the school;
Some to their merchandize are turned,
Some to the arts which they have learned.
Another, sworn by Holy Writ,
Puts on the cloak of hypocrite;
And, flying, would his thoughts conceal,
Did not his life the truth reveal.
So, shunning Death, do all men shape
Their diverse ways, his blows to 'scape.'
The scientific discourse follows: observe the good sense of many of
his remarks:—
'God, having made the world out of nothing, having put all things into their proper
places, measured spaces, and allotted courses, handed all over to Nature as his
chambrière. Whatever man can do—and his power is very great—he cannot equal
Nature, the inexhaustible and untiring. By alchemy he can interchange metals; can
restore its pristine purity to everything; can turn quicksilver into gold by subtle
medicines; but he cannot change or create species. This Nature alone is able to
effect, changing the complexions of things, so that they assume new forms and
become new substances; as when in thunderstorms, stones fall from the clouds,
where no stones ever were. 'The heavens turn every day, bearing with them the
stars. They go round from east to west, rejoicing the world. A complete revolution
is made every 26,000 years.
'The moon is different from the planets in being obscure in some places and clear
in others. The reason of this is, that the sun can penetrate through one part of it,
as through glass; the dark part, on which is figured a serpent having a tree on his
back, reflecting the rays.
'In the centre is the sun, like a king. He it is who makes the stars so bright that
they serve as lamps of the night; were we nearer to the sun we should be
81. scorched; were we farther away we should be frozen.
'The comets are not attached to the heavens, but fly about in the air. They do not
last long, and it is a mistake to suppose that they portend disaster. For there is no
man of worth or power sufficient for the heavens to take notice of him.
Nor any prince of so great worth,
That signs from heaven should give to earth,
Notice of death for him alone:
Nor is his body—life once gone—
Worth one jot more than simple squire,
Or clerk, or one who works for hire.
'Foolish people imagine, too, that stars fall like flying dragons from the skies; and
that eclipses are to be taken as portents. Now, no one would be astonished at
these things who understood the causes of things.
'Every student ought to acquire a knowledge of optics, which can be learned by
the aid of geometry, from the books of Aristotle, Albacen, and Hucayen. Here can
be learned the properties of mirrors; how they produce things which appear
miracles; make small things seem great—a grain of sand like a mountain; and
great things small—a mountain like a grain of sand; how glasses can be used to
burn things; how straight lines can be made to look crooked, round things oblong,
upright things reversed; the phantoms which do not exist appear to be moving
about.'
The book from beginning to end is as full of quotations as Burton.
The author quotes from Aristotle, Justinian, Horace, Seneca, St.
Augustine, Ovid, Cicero, Boethius, Lucan, Claudian, Suetonius, and
he has, probably through Cicero, some knowledge of Plato, but all
this in the wildest jumble, with no discrimination and no critical
power whatever. His range of reading was not by any means
contemptible, and though we know of no writer of his time who can
compare with him in this respect, it is evident that since one man
had command of so many books, other men must have enjoyed the
same advantages. There is reason to believe from Jean de Meung
alone that acquaintance with Latin literature was much more
extended than is generally thought, and that the scholarship of the
time was by no means wholly confined to scholastic disputation.
Such, roughly sketched, is the work of Jean de Meung, from which
we have plucked some of the fruits that come readiest to our hand.
82. If not altogether an original or a profound thinker, he has at least the
merit of fearlessness. He taught the folk, in the most popular way
possible, great and valuable lessons. He told them that religion is a
thing apart from, and independent of, religious profession; that la
robe ne faict pas le moyne; he says that most of the saints, men
and women, were decent married people, that marriage is a laudable
and holy custom, that the wealth of monks is a mockery of their
profession and a perjury of their vows, that learned persons ought to
set an example, and what is sheer ignorance and brutality in others
is rank sin with them; he attacks superstition, showing that all
phenomena have natural causes, and have nothing to do with
earthly events and the fortunes of men, because men are equal in
the sight of God; and he teaches in terms as clear as any used by
Carlyle, that labor is noble, and in accordance with the conditions of
our being—that man's welfare is the end and aim of all earthly
provision.
All this is what used to be called the Dark Ages. After six hundred
years, the same questions exercise us which exercised Jean de
Meung. We are still disputing as to whether true nobility is inherited
or not; we have not all made up our minds about the holiness of
marriage; we still think the clergyman, because he wears a surplice,
holier than other men; work has been quite recently and with much
solemnity pronounced noble by a prophet who forgot, while he was
about it, to call it also respectable; men yet live who look upon
scientific men with horror, and quote with fine infelicity, a text of St.
Paul's about 'science falsely so called;' while the lesson of personal
holiness has to be preached again and again, and is generally
forgotten in the war over vestments and creeds.
Jean de Meung wished, as it seems to us, to write a book for the
people, to answer their questions, to warn them of dangers before
them, to instruct their ignorance. On the sapless trunk of a dying
and passionless allegory he grafts a living branch which shall bear
fruit in the years to come. His poem breathes indeed. Its pulses beat
with a warm human life. Its sympathies are with all mankind. The
83. poet has a tear for the poor naked beggars dying on dung-heaps
and in the Hôtel-Dieu, and a lash of scorpions for the Levite who
goes by on the other side; he teaches the loveliness of friendship; he
catches the wordless complaint of the poor, and gives it utterance:
he speaks with a scorn which Voltaire only has equalled, and a
revolutionary fearlessness surpassing that of D'Alembert or Diderot.
And much more than this. It seems to us that his book—absolutely
the only cheerful book of the time—afforded hope that things were
not permanent: evil times may change; times have not been always
evil: there was once a Golden Age: the troubles of the present are
due, not to the innate badness of Nature and the universal unfitness
of things, but to certain definite and ascertainable causes. Now to
discover the cause is to go some way towards curing the disease.
In that uneasy time, strange questions and doubts perplexed men's
minds—questions of religion and politics, affecting the very
foundations of society. They asked themselves why things were so;
and looking about in the dim twilight of dawning knowledge they
could find as yet no answer. There was no rest in the Church or in
the State, and the mind of France—which was the mind of Europe—
was gravitating to a social and religious democracy. An hour before
the dawn, you may hear the birds of the forest twitter in their sleep:
they dream of the day. Europe at the close of the thirteenth century
was dreaming of the glorious Renaissance, the dawn of the second
great day of civilization. Jean de Meung answered the questions of
the times with a clearness and accuracy which satisfied if it did not
entirely explain. Five generations passed away before the full burst
of light, and he taught them all, with that geniality that is his
greatest charm. His book lasted because, confused and without art
as it is, it is full of life and cheerfulness and hope. Not one of the
poets of his own time had his lightness of heart: despondency and
dejection weigh down every one: they alternate between a
monotonous song to a mistress or a complaint for France; and to
Jean de Meung they are as the wood-pigeon to the nightingale. They
all borrowed from him, or studied him. Charles of Orleans, Villon,
84. Clement Marot, Rabelais, La Fontaine, Regnier, Molière, Béranger, all
come down from him in direct line, his literary children and
grandchildren. And in Jean de Meung, to make an end, is the first
manifestation of the true spirit of French literature—the esprit
Gaulois—the legacy, they tell us, of the ancient Gaul.
Art. V.—Letters and Letter Writing.
Gossip about Letters and Letter Writers. By George Seton, Advocate.
Edinburgh. 1870.
We all of us know well, and to our cost, that we can make no
improvement in the management of our affairs, no change for the
better in the arrangements, economical and ethical, of our modes of
life and action without some attendant trial, trouble, or loss coming
ever like a shadow in its train. It is, therefore, not a cause for
wonder that some spirit of evil has cast its shadow in the wake of
the introduction of the penny post, and the still later changes in the
direction of cheapness in the newspaper press. A feeling of regret
arises in our minds that with their introduction the good old-
fashioned long and newsy letter of bygone days has been almost
crushed out of existence. Letter writing is becoming a lost art, and
no correspondence is now carried on as in the olden time; for no one
now lives 'a life of letter writing' as Walpole said he did. The reason
of this is not far to seek, for the hurry and bustle of life has become
too great to allow of anything but the passing thought being
committed to paper, and each writer finds it to be useless to tell
news to a correspondent who has already learned what has
happened from the same source as himself. It is now frequently a
shorter operation to call upon your friend and talk with him than to
write him a long letter; but it is a happy thing for us of this day that
this was not always the case, for the letters of the past which we
85. possess form one of the most charming branches of our lighter
literature.
The value of communication between persons in distant places was
appreciated in very early times; and we find Job exclaiming, 'Now
my days are swifter than a post.' In the days of Hezekiah 'the posts
went with the letters from the king and his princes throughout all
Israel and Judah,' and Ahasuerus sent letters into every province of
his empire by 'the posts that rode upon mules and camels,' and were
'hastened and pressed on by the king's commandment,' to inform his
subjects that it was his imperial will that every man should bear rule
in his own house. Various modes of communication other than
writing have at different times been in use, such as numerically
marked or notched pieces of wood, and the many-coloured cords,
regularly knotted, which were called quipus by the Peruvians.
Herodotus tells us of a cruel practice resorted to, in order to convey
secret intelligence with safety. The head of a trusty messenger was
shaved, and certain writings were impressed upon his skull. After his
hair had grown sufficiently long for the purposes of concealment he
was sent on his mission, and on arriving at his destination was again
shaved, in order that the writing might be revealed. When the
Spaniards visited America they found the postal communication in
Mexico and Peru to be carried out on a most perfect system; and we
learn that the couriers of the Aztecs wore a differently coloured
dress, according as they brought good or bad tidings.
The establishment of a postal system in England is chiefly due to the
sagacity of Richard III., who commanded the expedition against the
Scots, in his brother Edward's reign. During this time, as it was
necessary for the king and his government to know how the war was
carried on, stages of about twenty miles each were established upon
the North road. When Richard came to the throne he did not allow
this system to fall into abeyance. Henry VIII. instituted the office of
'Master of the Postes,' and from his time to the present the Post
Office has increased in importance year by year. Henry Bishop was
appointed Postmaster-General at the Restoration, on his entering
86. Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com