Essential Java for Scientists and Engineers

  • View

  • Download

Embed Size (px)


iska baap


Essential Java for Scientists and EngineersEssential JavaforScientists and EngineersBrian D. HahnDepartment of Mathematics & Applied MathematicsUniversity of Cape TownRondeboschSouth AfricaKatherine M. MalanDepartment of Computer ScienceUniversity of Cape TownRondeboschSouth AfricaOXFORD AMSTERDAM BOSTON LONDON NEW YORK PARISSAN DIEGO SAN FRANCISCO SINGAPORE SYDNEY TOKYOButterworth-HeinemannAn imprint of Elsevier ScienceLinacre House, Jordan Hill, Oxford OX2 8DP225 Wildwood Avenue, Woburn, MA 01801-2041First published 2002Copyright c 2002 Brian D. Hahn and Katherine M. Malan. All rights reservedThe right of Brian D. Hahn and Katherine M. Malan to be identiedas the authors of this work has been asserted in accordance withthe Copyright, Designs and Patents Act 1988All rights reserved. No part of this publicationmay be reproduced in any material form (includingphotocopying or storing in any medium by electronicmeans and whether or not transiently or incidentallyto some other use of this publication) without thewritten permission of the copyright holder exceptin accordance with the provisions of the Copyright,Designs and Patents Act 1988 or under the terms of alicence issued by the Copyright Licensing Agency Ltd,90 Tottenham Court Road, London, England W1T 4LP.Applications for the copyright holders written permissionto reproduce any part of this publication should be addressedto the publishersBritish Library Cataloguing in Publication DataA catalogue record for this book is available from the British LibraryLibrary of Congress Cataloguing in Publication DataA catalogue record for this book is available from the Library of CongressISBN 0 7506 5422 8For information on all Butterworth-Heinemann publications visit our website at by Laserwords Private Limited, Chennai, India.Printed and bound in Martins the Printers of Berwick Upon TweedContentsPreface xiiiAcknowledgements xviPart I Essentials 11 Getting going 31.1 Introduction to programming 3Java as a programming language 31.2 Setting up your computer for programming in Java 4Installing Java 2 4Jikes as an alternative compiler 5Installing the essential package 61.3 Writing your rst Java program 6What happens when a program is compiled? 7Understanding FirstProgram 7Commands for printing to the screen 81.4 Input and output 9How input from the keyboard works 10Reading in numbers from the keyboard 10Input without the Keyboard class (optional) 10Example: calculating compound interest 111.5 Comments 111.6 Using objects 12Using the Turtle class 12Help on the essential package 13Using the Graph class 141.7 Java on the WWW (optional) 152 Java programming basics 202.1 Compound interest again 202.2 Primitive data types 23Bits and bytes 23vvi ContentsNumeric constants 24double is default 242.3 Names 25Identiers 25Case sensitivity 25Variables 252.4 Vertical motion under gravity 262.5 Operators, expressions and assignments 27Arithmetic operators 27Precedence 27Increment and decrement operators 28Assignments and assignment operators 29Cast operators 302.6 Repeating with for 30Turtle spirals 30Growing an investment 33The for statement 34Alternative ways of counting with for 35Square rooting with Newton 35Factorials! 36Limit of a sequence 37Reading data from a text le 372.7 Deciding with if 38The if-else statement 40The if-else-if statement 40The if-else-if ladder 40for and if: counting passes 41Rolling dice 41Logical operators 42Boolean variables 43Nested ifs 44The switch statement 442.8 Characters 45Escape sequences 452.9 Math methods 462.10 Programming style 463 Solving a problem in Java 553.1 Introduction 553.2 The class provider, class user and end user 563.3 What are objects and classes? 56Looking at the Turtle class in more depth 573.4 Writing and using a simple class 583.5 How memory works 59What is memory? 59How objects and primitives are stored in memory 60The null keyword 603.6 The String class 62Equality testing of strings 633.7 Understanding methods 63Method arguments 63Return types 64Signature of a method 64Contents viiConstructors 64More on the import statement 653.8 Example: simulating a rabbit colony 66Data members of RabbitColony 66Methods of RabbitColony 66Using the RabbitColony class 67Dening the grow() method 68Dening the grow(int n) method 68Dening the getNumRabbits() method 68Tracing UseRabbitColony 693.9 Access modiers 70The public and private keywords 70Other access modiers 703.10 Example: simulating the growth of trees 71Data members for the Tree class 71Methods of the Tree class 71A main method to test the class 72Writing the methods 72When to dene a default constructor 73The this keyword 743.11 Scope 743.12 More on object handles 75Passing objects to methods 75Object handles and assignment 783.13 The static keyword 80Understanding static 80Constants 81Static methods 81The main method revisited 833.14 Naming conventions 833.15 Using the Java API 843.16 Making your own package (optional) 844 More on loops 894.1 Determinate repetition with for 89Binomial coefcient 89for loops with non-unit increments 90Plotting a projectile trajectory with Essential Grapher 91Update processes 93The nested for loop 964.2 Indeterminate repetition with while 98Rolling a dice for a six 98The while statement 99A guessing game 100Prime numbers 101Projectile trajectory 102Reading an unknown amount of data 103The do-while statement 104while versus do-while 1055 Debugging 1145.1 Compilation errors 1145.2 Run-time errors 117viii Contents5.3 Errors in logic 119Debugging logical errors 1195.4 Rounding errors 1196 Arrays and matrices 1236.1 Introduction 123Why bother with arrays? 1236.2 The basics of arrays 125Declaring and initializing an array 125Indexing elements of an array 125Looping through an array 1266.3 Passing arrays to methods 1286.4 Frequency distributions: a simple bar chart 1286.5 Multi-dimensional arrays 129A concrete example 130Matrix multiplication 1316.6 Arrays of objects 1336.7 Sorting an array 134Part II More advanced topics 1417 Inheritance 1437.1 Introduction 143What is inheritance? 143Generalization and specialization 1447.2 Inheritance in Java 145Reusing code through specialization 146Overriding methods 148The protected keyword 1507.3 Constructors and inheritance 150Default constructors 151The super keyword 151Parameterized constructors 1527.4 The Object class 152The toString method 1537.5 Abstract classes and interfaces 154Why bother with abstract classes? 155Interfaces 1558 Graphical user interfaces (GUIs) 1608.1 Introduction 160GUIs in Java 160Understanding events 1618.2 Building a Swing application 161A rst version 161Shutting down the application properly 161Components and containers 162Adding a button to the application 162Organizing the code in a better way 163Adding a label 164Getting the button to do something 165Listeners as nested classes 165Contents ix8.3 Arranging components 167The FlowLayout manager 167The BorderLayout manager 168Adding borders to components 1698.4 A colour chooser application 170Planning the GUI 170Dening the colour 170Adding the components 170Adding the sliders and labels 172Programming the behaviour 1738.5 Painting 174PacMan and the Blocks 1768.6 Drawing mathematical graphs 1858.7 Fractals 189The Julia set 189The Mandelbrot set 1929 Input/output 1979.1 Introduction 1979.2 Input through command line parameters 1989.3 Input from the keyboard without the essential package 1989.4 Streams 199Output redirection 199The System class 200The InputStream and InputStreamReader classes 200The BufferedReader class 201Reading in numbers 2019.5 File input/output 201Types of les 202File handling 202Reading in from a text le 203Writing to les 2039.6 Manipulating data 204Tokenizing strings 2049.7 Streams and the Internet 20510 Exceptions 20910.1 Introduction 20910.2 Exceptions in Java 209Exception classes 21010.3 Throwing exceptions 211When to specify the throws clause in a method header 21310.4 Handling exceptions 214Example: nding averages 214Catching an exception 215What happens when an exception is thrown 21710.5 Exceptions and le input 217Groups of exceptions 218Forcing the exceptions 218Catching FileNotFoundException andEOFException 219Looping while le not found 220The finally statement 221x ContentsPart III Some applications 22511 Simulation 22711.1 Random number generation 227The Math.random method 227Seeding the random number generator 228The Random class 228Normal (Gaussian) random numbers 22911.2 Spinning coins 22911.3 Rolling dice 23011.4 Bacteria division 23011.5 Radioactive decay 230Estimation of half-life 23211.6 A random walk 23311.7 Trafc ow 23612 Modelling with matrices 24212.1 Using the Matrix class 242The identity matrix 24412.2 Networks 244A spy ring 244The reachability matrix 24612.3 Leslie matrices: population growth 24812.4 Markov processes 252A random walk 25312.5 Linear equations 256Limitations of the invert method of Matrix 258The residual 258Ill-conditioned systems 25813 Introduction to numerical methods 26213.1 Equations 262Newtons method 262A Function class 263Dening a new exception 266Complex roots 267The Bisection method 26913.2 Numerical differentiation 270