Essential Java for Scientists and Engineers Essential Java for Scientists and Engineers
Total Page:16
File Type:pdf, Size:1020Kb
Essential Java for Scientists and Engineers 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 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 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 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 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 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 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 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