100% found this document useful (6 votes)
63 views

Download full Beginning Java 2 SDK 1 4 edition Ivor Horton ebook all chapters

Java

Uploaded by

babanhauanmf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
63 views

Download full Beginning Java 2 SDK 1 4 edition Ivor Horton ebook all chapters

Java

Uploaded by

babanhauanmf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Visit https://ebookgate.

com to download the full version and


explore more ebooks

Beginning Java 2 SDK 1 4 edition Ivor Horton

_____ Click the link below to download _____


https://ebookgate.com/product/beginning-
java-2-sdk-1-4-edition-ivor-horton/

Explore and download more ebooks at ebookgate.com


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

Ivor Horton s Beginning Visual C 2010 1st Edition Ivor


Horton

https://ebookgate.com/product/ivor-horton-s-beginning-
visual-c-2010-1st-edition-ivor-horton/

ebookgate.com

Beginning ANSI C The Complete Language 3rd Edition Ivor


Horton

https://ebookgate.com/product/beginning-ansi-c-the-complete-
language-3rd-edition-ivor-horton/

ebookgate.com

Beginning c 4th ed. Edition Horton

https://ebookgate.com/product/beginning-c-4th-ed-edition-horton/

ebookgate.com

Beginning iPhone Development With Swift 2 Exploring the


iOS SDK 2nd Edition David Mark

https://ebookgate.com/product/beginning-iphone-development-with-
swift-2-exploring-the-ios-sdk-2nd-edition-david-mark/

ebookgate.com
Beginning iPhone Development Exploring the iPhone SDK 1st
Edition Jeff Lamarche

https://ebookgate.com/product/beginning-iphone-development-exploring-
the-iphone-sdk-1st-edition-jeff-lamarche/

ebookgate.com

Beginning Cryptography with Java 1st Edition David Hook

https://ebookgate.com/product/beginning-cryptography-with-java-1st-
edition-david-hook/

ebookgate.com

Beginning Rails 4 3rd Edition Adam Gamble

https://ebookgate.com/product/beginning-rails-4-3rd-edition-adam-
gamble-2/

ebookgate.com

Beginning Rails 4 3rd Edition Adam Gamble

https://ebookgate.com/product/beginning-rails-4-3rd-edition-adam-
gamble/

ebookgate.com

Beginning Android 4 1st Edition Grant Allen (Auth.)

https://ebookgate.com/product/beginning-android-4-1st-edition-grant-
allen-auth/

ebookgate.com
Beginning Java™ 2 SDK 1.4 Edition

Ivor Horton
Beginning Java™ 2 SDK 1.4 Edition

Ivor Horton
Ivor Horton’s Beginning Java™ 2 SDK 1.4 Edition
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2003 by Wiley Publishing, Inc., Indianapolis, Indiana


Published simultaneously in Canada
Library of Congress Card Number: 2003107063
ISBN: 0-7645-4365-2
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1B/QW/QW/QT/IN
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permit-
ted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written
permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the
Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8700.
Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing,
Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-Mail:
[email protected].

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE PUBLISHER AND AUTHOR


HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK, THEY MAKE NO REPRESENTA-
TIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CON-
TENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MER-
CHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED
OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ADVICE AND
STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR YOUR SITUATION. YOU SHOULD
CONSULT WITH A PROFESSIONAL WHERE APPROPRIATE. NEITHER THE PUBLISHER NOR
AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAM-
AGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER
DAMAGES.
For general information on our other products and services or to obtain technical support, please contact
our Customer Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax
(317) 572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may
not be available in electronic books.
Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, the Wrox Programmer to Programmer
logo and related trade dress are trademarks or registered trademarks of Wiley in the United States and
other countries, and may not be used without written permission Java is a trademark of Sun Microsystems.
All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated
with any product or vendor mentioned in this book.
Trademark Acknowledgements
Wrox has endeavored to provide trademark information about all the companies and products mentioned
in this book by the appropriate use of capitals. However, Wrox cannot guarantee the accuracy of this
information.

Credits
Author Technical Reviewers
Ivor Horton Steve Baker
Robert Chang
Technical Editors Phil Powers De George
Mankee Cheng Justin Foley
Shivanand Nadkarni David Hudson
Girish Sharangpani Jim MacIntosh
Roberts Shaw Craig McQueen
Andrew Tracey Karen Ritchie
Gavin Smyth
Commissioning Editors John Timney
Louay Fatoohi David Whitney
Chanoch Wiggers

Index Production Coordinator


John Collins Natalie O'Donnell
Andrew Criddle
Illustrations
Project Manager Pippa Wonson
Emma Batch Rachel Taylor

Proof Readers Cover Design


Lisa Stephenson Chris Morris
Fiona Berryman
Agnes Wiggers
Keith Westmooreland

Cover photograph by John Wright Photography, Warwick


A Note from the Author
In all my Beginning… books, my objective is to minimize what, in my judgment, are the three main hurdles
the aspiring programmer must face: getting to grips with the jargon that pervades every programming
language and environment, understanding the use of the language elements (as opposed to what they are),
and appreciating how the language is applied in a practical context.

Jargon is an invaluable and virtually indispensable means of communication for the competent amateur as
well as the expert professional, so it can't be avoided. My approach is to ensure that the beginner
understands what the jargon means and gets comfortable with using it in context. In that way, they can use
the documentation that comes along with most programming products more effectively, and can also feel
competent to read and learn from the literature that surrounds most programming languages.

Comprehending the syntax and effects of the language elements are obviously essential to learning a
language, but I believe illustrating how the language features work and how they are used are equally
important. Rather than just use code fragments, I always try to provide the reader with practical working
examples that show the relationship of each language feature to specific problems. These can then be a
basis for experimentation, to see at first hand the effects of changing the code in various ways.

The practical context needs to go beyond the mechanics of applying individual language elements. To help
the beginner gain the competence and confidence to develop their own applications, I aim to provide them
with an insight into how things work in combination and on a larger scale than a simple example with a few
lines of code. That's why I like to have at least one working example that builds over several chapters. In
that way it's possible to show something of the approach to managing code as well as how language features
can be applied together.

Finally, I know the prospect of working through a book of doorstop proportions can be quite daunting. For
that reason it's important for the beginner to realize three things that are true for most programming
languages. First, there is a lot to it, but this means there will be a greater sense of satisfaction when you've
succeeded. Second, it's great fun, so you really will enjoy it. Third, it's a lot easier than you think, so you
positively will make it.

Ivor Horton
Table of Contents

Introduction 1
Welcome 1
Who is this Book For? 1
What's Covered in this Book 2
What You Need to Use this Book 3
Conventions 3
Tell Us What You Think 4
Errata & Updates 4
p2p.wrox.com 4

Chapter 1: Introducing Java 7


What is Java All About? 7
Features of the Java Language 8

Learning Java 9
Java Programs 9
Learning Java – the Road Ahead 9

The Java Environment 10


Java Program Development 11
Installing the SDK 12
Compiling a Java Program 14
Executing a Java Application 15
Executing an Applet 16
The Hypertext Markup Language 16
Adding an Applet to an HTML Document 17
Making Applets Run in Any Browser 18

Object-Oriented Programming in Java 19


So What Are Objects? 20
What Defines a Class of Objects? 21
Java Program Statements 25
Classes and Data Types 26
Classes and Subclasses 26
Advantages of Using Objects 27
Table of Contents

Java Program Structure 27


Java's Class Library 28
Java Applications 30

Java and Unicode 32


Summary 33
Resources 33

Chapter 2: Programs, Data, Variables, and Calculation 37


Data and Variables 38
Variable Names 38
Variable Names and Unicode 39
Variables and Types 39

Integer Data Types 40


Integer Values 41
Declaring Integer Variables 42

Floating Point Data Types 44


Floating Point Values 44
Declaring Floating Point Variables 45

Arithmetic Calculations 45
Integer Calculations 46
Producing Output 49
Integer Division and Remainders 51
The Increment and Decrement Operators 51
Computation with Shorter Integer Types 52
Errors in Integer Arithmetic 54
Floating Point Calculations 54
Other Floating Point Operators 55
Error Conditions in Floating Point Arithmetic 55

Mixed Arithmetic Expressions 56


Explicit Casting 56
Casting in Assignments 57

The op= Operators 57


Mathematical Functions and Constants 58
Storing Characters 62
Character Escape Sequences 62
Character Arithmetic 63

Bitwise Operations 63
Shift Operations 68

Boolean Variables 70
Operator Precedence 71

ii
Table of Contents

Program Comments 72
Documentation Comments 73

Summary 74
Exercises 74

Chapter 3: Loops and Logic 77


Making Decisions 78
Making Comparisons 78
The if Statement 79
Statement Blocks 80
The else Clause 81
Nested if Statements 82

Logical Operators 85
Boolean AND Operations 86
&& versus & 87
Boolean OR Operations 88
Boolean NOT Operations 89
Character Testing Using Standard Library Methods 90

The Conditional Operator 91


The switch Statement 92
Variable Scope 96
Loops 98
Counting Using Floating Point Values 103
Nested Loops 106
The continue Statement 108
The Labeled continue Statement 108
Using the break Statement in a Loop 109
Breaking Indefinite Loops 111
The Labeled break Statement 112

Assertions 114
Summary 117
Exercises 118

Chapter 4: Arrays and Strings 121


Arrays 121
Array Variables 122
Defining an Array 122
Accessing Array Elements 123
Reusing Array Variables 124
Initializing Arrays 125
Using Arrays 126

iii
Table of Contents

Array Length 127


Arrays of Arrays 130
Arrays of Arrays of Varying Length 132
Multi-dimensional Arrays 133

Arrays of Characters 134


Strings 134
String Literals 135
Creating String Objects 135
Arrays of Strings 137

Operations on Strings 138


Joining Strings 138
Comparing Strings 142
Comparing Strings for Equality 143
String Interning 146
Checking the Start and End of a String 147
Sequencing Strings 147
Accessing String Characters 149
Extracting String Characters 149
Searching Strings for Characters 151
Searching for Substrings 152
Extracting Substrings 155
Using a String Tokenizer 157
Modified Versions of String Objects 158
Creating Character Arrays from String Objects 159
Creating String Objects from Character Arrays 160

StringBuffer Objects 160


Creating StringBuffer Objects 161
The Capacity of a StringBuffer Object 161
Changing the Length for a StringBuffer Object 163
Adding to a StringBuffer Object 164
Appending a Substring 164
Appending Basic Types 165
Inserting Strings 166
Extracting Characters from a StringBuffer Object 167
Other StringBuffer Operations 167
Creating a String Object from a StringBuffer Object 167

Summary 168
Exercises 169

Chapter 5: Defining Classes 171


What is a Class? 172
Variables in a Class Definition 172
Methods in a Class Definition 174
Accessing Variables and Methods 175

iv
Table of Contents

Defining Classes 176


Defining Methods 177
Running from a Method 178
The Parameter List 178
How Argument Values Are Passed to a Method 179
Final Parameters 180
Defining Class Methods 180
Accessing Class Data Members in a Method 181
The Variable this 182
Initializing Data Members 183
Using Initialization Blocks 184

Constructors 186
The Default Constructor 187
Creating Objects of a Class 188
Passing Objects to a Method 189
The Lifetime of an Object 190

Defining and Using a Class 190


Method Overloading 192
Multiple Constructors 193
Calling a Constructor from a Constructor 195
Duplicating Objects Using a Constructor 195

Using Objects 196


Creating a Point from Two Lines 200

Recursion 203
Understanding Packages 205
Packaging Up Your Classes 206
Packages and the Directory Structure 206
Compiling a Package 207
Accessing a Package 207
Using Extensions 208
Adding Classes from a Package to Your Program 209
Packages and Names in Your Programs 210
Standard Packages 211
Standard Classes Encapsulating the Basic Data Types 212

Controlling Access to Class Members 212


Using Access Attributes 213
Specifying Access Attributes 214
Choosing Access Attributes 216
Using a Package and Access Attributes 216

Nested Classes 221


Static Nested Classes 223
Using a Non-Static Nested Class 226
Using a Nested Class outside the Top-Level Class 228
Local Nested Classes 229

v
Table of Contents

The finalize() Method 230


Native Methods 231
Summary 231
Exercises 232

Chapter 6: Extending Classes and Inheritance 235


Using Existing Classes 235
Class Inheritance 237
Inheriting Data Members 237
Hiding Data Members 239
Inherited Methods 239
Objects of a Derived Class 239
Deriving a Class 240
Derived Class Constructors 241
Calling the Base Class Constructor 242
Overriding a Base Class Method 243

Choosing Base Class Access Attributes 244


Polymorphism 245
Using Polymorphism 247

Multiple Levels of Inheritance 250


Abstract Classes 251
The Universal Superclass 253
The toString() Method 254
Determining the Type of an Object 254
Members of the Class class 255
Copying Objects 257

Casting Objects 261


When to Cast Objects 263
Identifying Objects 264

Designing Classes 265


A Classy Example 266
Designing the PolyLine Class 267
A General-Purpose Linked List 272

Using the final Modifier 276


Interfaces 277
Interfaces Containing Constants 278
Interfaces Declaring Methods 280
A Partial Interface Implementation 281
Extending Interfaces 282
Interfaces and Multiple Inheritance 283
Using Interfaces 283

vi
Table of Contents

Interfaces and Polymorphism 283


Using Multiple Interfaces 289
Nesting Classes in an Interface Definition 290
Interfaces and the Real World 291

Anonymous Classes 291


Summary 292
Exercises 293

Chapter 7: Exceptions 295


The Idea Behind Exceptions 295
Types of Exceptions 296
Error Exceptions 297
RuntimeException Exceptions 297
Other Subclasses of Exception 299

Dealing with Exceptions 300


Specifying the Exceptions a Method Can Throw 300
Handling Exceptions 300
The try Block 301
The catch Block 301
try catch Bonding 303
Multiple catch Blocks 305
The finally Block 306
Structuring a Method 307
Execution Sequence 308
Normal Execution of a Method 311
Execution when an Exception is Thrown 312
Execution when an Exception is not Caught 313
Nested try Blocks 314
Rethrowing Exceptions 315

Exception Objects 315


The Class Throwable 316
Standard Exceptions 318

Defining Your Own Exceptions 318


Defining an Exception Class 319
Throwing Your Own Exception 320
An Exception Handling Strategy 320
An Example of an Exception Class 321

Summary 324
Exercises 325

vii
Table of Contents

Chapter 8: Understanding Streams 327


Streams and the New I/O Capability 327
Understanding Streams 328
Binary and Character Streams 329

The Classes for Input and Output 330


Basic Input Stream Operations 331
Basic Output Stream Operations 334
Stream Readers and Writers 335
Using Readers 335
Using Writers 336

The Standard Streams 338


Getting Data From the Keyboard 338
Tokenizing a Stream 339
Customizing a Stream Tokenizer 341
Writing to the Command Line 346
Overriding print() and println() 347

Summary 351
Exercises 352

Chapter 9: Accessing Files and Directories 355


Working with File Objects 355
Creating File Objects 356
Portable Path Considerations 358
Absolute and Relative Paths 358
Testing and Checking File Objects 360
Querying Files and Directories 362
Filtering a File List 367
Creating and Modifying Files and Directories 370

Creating File Output Streams 372


Ensuring a File Exists 374
Avoiding Overwriting a File 376
FileDescriptor Objects 378

Summary 378
Exercises 379

Chapter 10: Writing Files 381


File I/O Basics 381
File Input and Output 383
Channels 384
Channel Operations 384

viii
Table of Contents

File Channels 386

Buffers 387
Buffer Capacity 388
Buffer Position and Limit 389
Setting the Position and Limit 391
Creating Buffers 392
View Buffers 393
Duplicating and Slicing Buffers 395
Creating Buffers by Wrapping Arrays 396
Marking a Buffer 398
Buffer Data Transfers 398
Transferring Data into a Buffer 399
Using View Buffers 401
Preparing a Buffer for Output to a File 401

Writing to a File 403


File Position 404
Using a View Buffer 409
Writing Varying Length Strings to a File 411
Direct and Indirect Buffers 413
Writing Numerical Data to a File 414
Writing Mixed Data to a File 418
Gathering-Write Operations 424

Summary 428
Exercises 429

Chapter 11: Reading Files 431


File Read Operations 431
Creating File Input Streams 432

File Channel Read Operations 433


Reading a Text File 436
Getting Data from the Buffer 437

Reading Binary Data 439


Reading Mixed Data 444
Copying Files 450
Random Access to a File 456
Read/Write Operations with a Single File Channel 460
Memory-Mapped Files 462
Locking a File 465
Locking Part of a File 466
Practical File Locking Considerations 467

ix
Table of Contents

Summary 470
Exercises 471

Chapter 12: Serializing Objects 473


Storing Objects in a File 473
Writing an Object to a File 474
Writing Basic Data Types to an Object Stream 476
Implementing the Serializable Interface 477
Conditions for Serialization 480
Transient Data Members of a Class 481
Reading an Object from a File 481
Determining the Class of a Deserialized Object 485
Reading Basic Data from an Object Stream 486
Using Object Serialization 486
Serializing Classes Yourself 489
Serialization Problems and Complications 490
Resetting an Object Output Stream 492

Summary 493
Exercises 494

Chapter 13: Collection Classes 497


Understanding the Collection Classes 497
Collections of Objects 498
Sets 498
Sequences 499
Maps 500
Hashing 501

Iterators 501
List Iterators 503

Collection Classes 505


Collection Interfaces 507

Using Vectors 508


Creating a Vector 508
The Capacity and Size of a Vector 510
Storing Objects in a Vector 512
Retrieving Objects from a Vector 513
Accessing Elements in a Vector through an Iterator 513
Extracting All the Elements from a Vector 515
Removing Objects from a Vector 515
Searching a Vector 517
Applying Vectors 518
Sorting 522

x
Table of Contents

Stack Storage 525

Linked Lists 531


Using Maps 532
The Hashing Process 533
Using Your Own Class Objects as Keys 534
Generating Hash Codes 534
Creating a HashMap 535
Storing, Retrieving, and Removing Objects 536
Processing all the Elements in a Map 537
Storing a Map in a File 544

Summary 547
Exercises 548

Chapter 14: A Collection of Useful Classes 551


Utility Methods for Arrays 551
Filling an Array 551
Comparing Arrays 553
Sorting Arrays 554
Searching Arrays 555

Observable and Observer Objects 556


Defining Classes of Observable Objects 556
Observable Class Methods 557

Generating Random Numbers 561


Random Operations 562

Dates and Times 564


The Date Class 565
Interpreting Date Objects 565
Obtaining a Date Object from a String 569
Gregorian Calendars 570
Setting the Date and Time 571
Getting Date and Time Information 573
Modifying Dates and Times 573
Comparing Calendars 574

Regular Expressions 576


Defining Regular Expressions 577
Creating a Pattern 577
Creating a Matcher 578
Searching a String 579
Matching an Entire String 581
Defining Sets of Characters 582
Matching Boundaries 585
Using Quantifiers 586
Search and Replace Operations 588
Using Capturing Groups 591

xi
Table of Contents

Juggling Captured Text 593

Summary 596
Exercises 597

Chapter 15: Threads 599


Understanding Threads 599
Creating Threads 602
Stopping a Thread 607
Connecting Threads 608
Thread Scheduling 609
Implementing the Runnable Interface 610

Managing Threads 612


Synchronization 612
Synchronized Methods 613
Synchronizing Statement Blocks 624
Deadlocks 630
Communicating between Threads 631
Using wait() and notifyAll() in the Bank Program 633

Thread Priorities 637


Using Thread Priorities 637

Summary 640
Exercises 641

Chapter 16: Creating Windows 643


Graphical User Interfaces in Java 644
Model-View-Controller (MVC) Architecture 644

Creating a Window 646


Components and Containers 649
Window and Frame Components 651
Window Panes 652

Basics of Components 653


Component Attributes 653
The Size and Position of a Component 654
Points and Rectangles 657
Visual Characteristics of a Component 661
Defining Color 662
System Colors 664
Creating Cursors 664
Selecting Fonts 666
Swing Components 670
Buttons 671
Menus 671

xii
Table of Contents

Text Components 672


Other Swing Components 673

Using Containers 674


Adding Components to a Container 675

Container Layout Managers 676


The Flow Layout Manager 677
Using a Border Layout Manager 682
Using a Card Layout Manager 684
Using a Grid Layout Manager 686
Using a BoxLayout Manager 688
Struts and Glue 691
Using a GridBagLayout Manager 695
GridBagConstraints Instance Variables 696
Using a SpringLayout Manager 703
Understanding Constraints 704
Defining Constraints 704
Setting Constraints for a Component 705

Adding a Menu to a Window 710


Creating JMenu and JMenuItem 711
Creating a Menu 711
Adding Items to a Pull-Down Menu 714
Adding an Shortcut for a Menu Item 717

More on Applets 720


Converting an Application to an Applet 721

Summary 723
Exercises 723

Chapter 17: Handling Events 727


Window-based Java Programs 727
Event-driven Programs 728

The Event-handling Process 729


Event Classes 730
Low-level Event Classes 731
Making a Window Handle its Own Events 733
Enabling Other Low-level Events 736
Low-level Event Listeners 737
Using Adapter Classes 742
Semantic Events 744
Semantic Event Listeners 746

Semantic Event Handling in Applets 746


Alternative Event Handling Approaches 755
Handling Low-level and Semantic Events 757

xiii
Table of Contents

Semantic Event Listeners in an Application 758


Listening to Menu Items 758
Fixing the Color Menu Checks 763

Using Actions 764


The Action Interface 764
Using Actions as Menu Items 766
Defining Action Classes 767

Adding a Toolbar 772


Adding Buttons to a Toolbar 773
Adding Icons 775
Fixing the Menus 778
Adding Tooltips 779
Disabling Actions 781

Summary 782
Exercises 783

Chapter 18: Drawing in a Window 785


Using the Model/View Architecture 785
Coordinate Systems in Components 789
Drawing on a Component 790
Graphics Contexts 791
The Drawing Process 794
Rendering Operations 795

Shapes 795
Classes Defining Points 796
Lines and Rectangles 798
Combining Rectangles 800
Testing Rectangles 800
Arcs and Ellipses 803
Curves 806
Complex Paths 814

Filling Shapes 820


Gradient Fill 822

Managing Shapes 825


Storing Shapes in the Document 827
Drawing Shapes 828

Drawing Using the Mouse 829


Handling Mouse Events 830
Handling Mouse Button Press Events 832
Using XOR Mode 833
Handling Mouse Dragging Events 834
Handling Button Release Events 836

xiv
Table of Contents

Defining Our Own Shape Classes 837


Defining Lines 837
Defining Rectangles 840
Defining Circles 842
Drawing Curves 843

Summary 846
Exercises 846

Chapter 19: Extending the GUI 849


Creating a Status Bar 849
Using Dialogs 854
Modal and Non-modal Dialogs 855
A Simple Modal Dialog 856

Instant Dialogs 860


Input Dialogs 862
Using a Dialog to Create Text Elements 864
A Font Selection Dialog 873
Creating the Buttons 875
Adding the Data Pane 877
Implementing the Font List 878
Displaying the Selected Font 880
Using a Split Pane 880
Using a Spinner 882
Using Radio Buttons to Select the Font Style 884
Listening for Radio Buttons 885

Pop-up Menus 888


Displaying a Pop-up Menu 889
Implementing a Context Menu 892
Tracking Mouse Moves 893
Defining the Other Context Menu 896
Deleting Elements 898
Implementing the Send-to-Back Operation 899

Transforming the User Coordinate System 900


The AffineTransform Class 902
Modifying the Transformation for a Graphics Context 904
Creating AffineTransform Objects 905
Translating Lines 907
Translating Rectangles 909
Translating Circles 910
Translating Curves 910
Translating Text 911
Moving an Element 912
Rotating Elements 916

Choosing Custom Colors 921

xv
Table of Contents

Summary 923
Exercises 923

Chapter 20: Filing and Printing Documents 927


Serializing the Sketch 928
Implementing the Serializable Interface 931
Serializing the List of Elements 931
Serializing Lines 932
Serializing Rectangles 933
Serializing Circles 933
Serializing Curves 934
Serializing Text 937

Supporting the File Menu 937


Using a File Chooser 938
File Save Operations 938
Implementing the Save Operation 941
Writing a Sketch to a File 942
Creating a File Filter 944
File Save As Operations 946
File Open Operations 947
Starting a New Sketch 950
How It Works 950
Preventing Data Loss on Close 951

Printing in Java 952


Creating and Using PrinterJob Objects 955
Displaying a Print Dialog 956
Starting the Printing Process 957
Printing Pages 958
The PageFormat Class 959
Printing the Whole Sketch 963
Scaling the Sketch to Fit 966
Printing in Landscape Orientation 968
User Page Setup 971
Using the Java Print Dialog 972
Setting Print Request Attributes Programmatically 974
Multi-Page Document Printing 975
Implementing the Pageable Interface 976
Creating PageFormat Objects 977
Dealing with Paper 978
Printing Using a Book 985
Printing Swing Components 987

Summary 990
Exercises 991

xvi
Table of Contents

Chapter 21: Java and XML 993


XML 994
XML Document Structure 995
Valid XML Documents 997
Elements in an XML Document 998
Rules for Tags 999
Empty Elements 999
Document Comments 1000
Element Names 1000
Defining General Entities 1001
CDATA Sections 1002
Element Attributes 1002
Attributes versus Elements 1003
Whitespace and Readability 1004

Data Structure in XML 1005


Document Type Definitions 1006
Declaring a DTD 1006
Defining a DTD 1007
Defining Elements in DTDs 1008
Defining Element Attributes 1012
Defining Parameter Entities 1014
Other Types of Attribute Value 1014
A DTD for Sketcher 1015

Rules for a Well-Formed Document 1019


XML Namespaces 1019
Namespace Declarations 1020
XML Namespaces and DTDs 1022

Working with XML Documents 1022


SAX Processing 1023
DOM Processing 1024

Accessing Parsers 1025


Using SAX 1026
Using a Different Parser 1029
Updating the Default Parser 1029
Parser Features and Properties 1029
Features of a Parser 1030
Properties of a Parser 1031
Parsing Documents with SAX 1031
Implementing a SAX Handler 1032
Processing a Document with a DTD 1038
Processing a Document with Namespaces 1040
Using Qualified Names 1040
Handling other Parsing Events 1041

xvii
Table of Contents

Summary 1043
Exercises 1044

Chapter 22: Creating and Modifying XML Documents 1047


The Document Object Model (DOM) 1047
Setting DOM Parser Features 1049
Parsing a Document 1050
Navigating a Document Object Tree 1051
Node Types 1058
Accessing Attributes 1059
Accessing the DOCTYPE Declaration 1061
Creating XML Documents 1064
Adding to a Document 1067
Storing a Sketch as XML 1069
Adding Element Nodes 1070
Creating a Document Object for a Complete Sketch 1076
Saving a Sketch as XML 1077
Creating XML for the Document Body 1083
Reading an XML Representation of a Sketch 1085
Creating the Model 1087
Creating Sketch Elements from XML Elements 1088

Summary 1095
Exercises 1096

Appendix A: Keywords 1099

Appendix B: Computer Arithmetic 1103


Binary Numbers 1103
Hexadecimal Numbers 1104
Negative Binary Numbers 1106
Floating Point Numbers 1107

xviii
Table of Contents

xix
Introduction

Welcome
Welcome to the third edition of Beginning Java 2, a comprehensive and easy-to-use tutorial guide to
learning the Java language and the Java 2 platform API. This book provides you with the essential
know-how for developing programs using the SDK 1.3 or later.

In this book, as well as teaching you Java, we introduce you to the wide variety of topics that will be
relevant to you as a Java programmer. We've structured the book so that you learn Java programming
in a carefully designed and logical way, and at each stage you will be building on what you have learned
at the previous stage.

Who is this Book For?


Java programming is a huge and rapidly expanding area. Since its release, the growth of Java as the
object-oriented language of choice for Internet programming and teaching has been phenomenal. The
Java 2 platform is a significant maturing in the level of support offered to you, especially for application
development. It is the language of choice of many programmers for major application development,
offering advantages in ease of development and maintenance compared to other languages, as well as
built-in capability to run on a variety of computers and operating systems without code changes. With it
you can do a lot more, more quickly, and more easily.

In this book we aim to provide you with a comprehensive understanding of the language, plus suitable
experience of Java application contexts to give you a solid base in each of these core areas. Every aspect
of Java that is covered in the book is illustrated by fully working program examples that you can and
should create and run for yourself. With an understanding of the topics in this book, you can start to
write fully featured and effective Java programs.
Introduction

The word Beginning in the title refers more to the style of the book's teaching than to your skill level. It
could equally well be called Straight into Java, because the tutorial structure is designed so that, whether
you're a seasoned programmer from another language or a newcomer to programming in general, this
book takes you straight to your floor.

We assume, as a minimum, that you know something about programming, in that you understand at
least the fundamental concepts of how programs work. However, you don't need to have significant
prior programming experience to use the book successfully. The pace of the book is fairly rapid, but
without stinting on any of the necessary explanations of how Java works.

What's Covered in this Book


The book aims to teach you Java programming following a logical format:

❑ First, it covers some of the main terms and concepts that underpin programming in Java.
Without these we'll get nowhere fast.
❑ Second, it provides you with a clear explanation of the features of the Java language – the
basic data types, the control structures that manipulate data, the object-oriented features of the
language, the way runtime errors are handled, and how threads are used. The book doesn't
just explain what the language elements do, but also how you can apply them in practice.
❑ Third, it gives you an extensive introduction to the key packages in the Java class library –
amongst others, the io, nio, util, awt, awt.event, applet, javax.swing, and
javax.xml packages are all covered and illustrated with full working examples. These
packages cover file handling, helper objects, Graphical User Interfaces, Applets, and XML.
❑ Fourth, it guides you through the process of building a substantial application, Sketcher, in
which you apply the Java language capabilities and the Java class library in a realistic context.
Our sketching application will have menus, toolbars, and a status panel, as well as the ability
to draw and manipulate a number of elements, handle text, print, and save sketches –
including saving sketches in XML. This will give you a much better understanding of how you
apply Java in practical projects of your own, something that's hard to appreciate from any
number of more trivial examples.
❑ Lastly, it shows how you can use the various tools that come with the JDK 1.3.

As we progress through these topics, we introduce you to the theory, and then illustrate it with an
appropriate example and a clear explanation. You can learn quickly on a first read, and look back over
things to brush up on all the essential elements when you need to. The small examples in each chapter
are designed mainly to illustrate a class and its methods, or some new piece of theory in action. They
focus specifically on showing you how the particular language feature or method works.

To get the most from the chapters, we strongly recommend that you try out the examples as you read.
Type them in yourself, even if you have downloaded the example source code. It really does make a
difference. The examples also provide a good base for experimentation and will hopefully inspire you to
create programs of your own. It's important to try things out – you will learn as much (if not more) from
your mistakes as you will from the things that work first time.

The source code for all of the example programs in the book is available at http://www.wrox.com.

2
Introduction

What You Need to Use this Book


This book has been tested against the SDK 1.4 release code so you should ideally be using SDK 1.4 or
later. Other requirements for most of the chapters are fairly minimal: a copy of a text editor and a
command line window from which to run the Java tools. Details of the requirements for the book and
how to acquire and install them are provided in Chapter 1.

Conventions
To help you get the most from the text and keep track of what's happening, we've used a number of
conventions throughout the book.

For instance, when discussing code, we have two conventions:

Background is used to hold asides on programming code.

while:

These boxes hold important, not-to-be-forgotten information which is directly relevant


to the surrounding text.

When we introduce important words, we highlight them. We show keyboard strokes as Ctrl-A.

The command line and terminal output is shown as:

C:\> java ShowStyle


When the command line is shown – this will be for you to enter – it's in the above
style, whereas terminal output is in this style.

while text for windowed applications, such as on buttons, is shown as OK and Cancel. Filenames are
shown as MyFile.java.

We present code in four different ways. Firstly, variables, Java keywords, methods, and classes are
referenced in the text using a code style.

Definitions of Java methods and structures are shown in definition boxes. For example:

if(life==aimless) {
DoSomething; // Italics show that words should be replaced
DoSomethingElse; // with something more meaningful
}

Lastly in our code examples, the code foreground style shows new, important,
pertinent code;
while code background shows code that's less important in the present context,
or has been seen before.

3
Introduction

We'll presage example code with a Try It Out, which is used to split the code up where that's helpful, to
highlight the component parts and to show the progression of the application. When it's important, we
also follow the code with a How It Works to explain any salient points of the code in relation to
previous theory. We find these two conventions help break up the more formidable code listings into
more palatable morsels.

Tell Us What You Think


We've worked hard to make this book as useful to you as possible, so we'd like to get a feel for what it is
you want and need to know, and what you think about how we've presented things to you. The positive
feedback we received about the first edition of this book has helped make this new and revised edition
an even better book.

Return the reply card in the back of the book, and you'll register this copy of Beginning Java 2 with
Wrox Press, and be put on our mailing list for information on the latest Wrox products.

If you've anything to say, let us know on:

[email protected]

or at:

http://www.wrox.com

Errata & Updates


We've made every effort to make sure there are no errors in the text or the code. However, to err is human
and as such we recognize the need to keep you informed of any mistakes as they're spotted and amended.

While you're visiting our web site, please make use of our Errata page that's dedicated to fixing any
small errors in the book or offering new ways around a problem and its solution. Errata sheets are
available for all our books – please download them, or take part in the continuous improvement of our
tutorials and upload a 'fix'.

p2p.wrox.com
This book introduces a totally comprehensive and unique support system. Wrox now has a commitment to
supporting you not just while you read the book, but once you start developing applications as well. We
provide you with a forum where you can put your questions to the authors, reviewers, and fellow industry
professionals. You have the choice of how to receive this information; either you can enroll onto one of
several mailing lists, or you can just browse the online forums and newsgroups for an answer.

Go to http://p2p.wrox.com. Here you'll find a link to the Beg_Java forum. If you find something wrong
with this book, or you just think something has been badly explained or is misleading in some way, then
leave your message here. You'll still receive our customary quick reply, but you'll also have the
advantage that every author will be able to see your problem at once and help deal with it.

Enroll now; it's all part of our free support system.

4
Introduction

5
Introducing Java

This chapter will give you an appreciation of what the Java language is all about. Understanding the
details of what we'll discuss in this chapter is not important at this stage; you will see all of them again in
greater depth in later chapters of the book. The intent of this chapter is to introduce you to the general
ideas that underpin what we'll be covering through the rest of the book, as well as the major contexts in
which Java programs can be used and the kind of program that is applicable in each context.

In this chapter you will learn:

❑ The basic characteristics of the Java language.


❑ How Java programs work on your computer.
❑ Why Java programs are portable between different computers.
❑ The basic ideas behind object-oriented programming.
❑ How a simple Java program looks and how you can run it using the Java Development Kit.
❑ What HTML is and how it is used to include a Java program in a web page.

What is Java All About?


Java is an innovative programming language that has become the language of choice for programs that
need to run on a variety of different computer systems. First of all Java enables you to write small
programs called applets. These are programs that you can embed in Internet web pages to provide some
intelligence. Being able to embed executable code in a web page introduces a vast range of exciting
possibilities. Instead of being a passive presentation of text and graphics, a web page can be interactive
in any way that you want. You can include animations, games, interactive transaction processing – the
possibilities are almost unlimited.
Chapter 1

Of course, embedding program code in a web page creates special security requirements. As an Internet
user accessing a page with embedded Java code, you need to be confident that it will not do anything
that might interfere with the operation of your computer, or damage the data you have on your system.
This implies that execution of the embedded code must be controlled in such a way that it will prevent
accidental damage to your computer environment, as well as ensure that any Java code that was created
with malicious intent is effectively inhibited. Java implicitly incorporates measures to minimize the
possibility of such occurrences arising with a Java applet.

Java also allows you to write large-scale application programs that you can run unchanged on any
computer with an operating system environment in which the language is supported. This applies to the
majority of computers in use today. You can even write programs that will work both as ordinary
applications and as applets.

Java has matured immensely in recent years, particularly with the introduction of Java 2. The breadth of
function provided by the standard core Java has grown incredibly. Java provides you with
comprehensive facilities for building application with an interactive GUI, extensive image processing
and graphics programming facilities, as well as support for accessing relational databases and
communicating with remote computers over a network. Release 1.4 of Java added a very important
additional capability, the ability to read and write XML. Just about any kind of application can now be
programmed effectively in Java, with the implicit plus of complete portability.

Features of the Java Language


The most important characteristic of Java is that it was designed from the outset to be machine
independent. Java programs can run unchanged on any operating system that supports Java. Of course
there is still the slim possibility of the odd glitch as you are ultimately dependent on the implementation
of Java on any particular machine, but Java programs are intrinsically more portable than programs
written in other languages. An application written in Java will only require a single set of sourcecode,
regardless of the number of different computer platforms on which it is run. In any other programming
language, the application will frequently require the sourcecode to be tailored to accommodate different
computer environments, particularly if there is an extensive graphical user interface involved. Java
offers substantial savings in time and resources in developing, supporting, and maintaining major
applications on several different hardware platforms and operating systems.

Possibly the next most important characteristic of Java is that it is object oriented. The object-oriented
approach to programming is also an implicit feature of all Java programs, so we will be looking at what this
implies later in this chapter. Object-oriented programs are easier to understand, and less time-consuming to
maintain and extend than programs that have been written without the benefit of using objects.

Not only is Java object oriented, but it also manages to avoid many of the difficulties and complications
that are inherent in some other object-oriented languages, making it easy to learn and very
straightforward to use. It lacks the traps and 'gotchas' that arise in some other programming languages.
This makes the learning cycle shorter and you need less real-world coding experience to gain
competence and confidence. It also makes Java code easier to test.

Java has a built-in ability to support national character sets. You can write Java programs as easily for
Greece or Japan, as you can for English speaking countries always assuming you are familiar with the
national languages involved, of course. You can even build programs from the outset to support several
different national languages with automatic adaptation to the environment in which the code executes.

8
Introducing Java

Learning Java
Java is not difficult, but there is a great deal to it. The language itself is fairly compact, but very
powerful. To be able to program effectively in Java, however, you also need to understand the libraries
that go with the language, and these are very extensive. In this book, the sequence in which you learn
how the language works, and how you apply it, has been carefully structured so that you can gain
expertise and confidence with programming in Java through a relatively easy and painless process. As
far as possible, each chapter avoids the use of things you haven't learned about already. A consequence,
though, is that you won't be writing Java applications with a graphical user interface right away. While it
may be an appealing idea, this would be a bit like learning to swim by jumping in the pool at the deep
end. Generally speaking, there is good evidence that by starting in the shallow end of the pool and
learning how to float before you try to swim, the chance of drowning is minimized, and there is a high
expectation that you will end up a competent swimmer.

Java Programs
As we have already noted, there are two kinds of programs you can write in Java. Programs that are to be
embedded in a web page are called Java applets, and normal standalone programs are called Java
applications. You can further subdivide Java applications into console applications, which only support
character output to your computer screen (to the command line on a PC under Windows, for example), and
windowed Java applications that can create and manage multiple windows. The latter use the typical
graphical user interface (GUI) mechanisms of window-based programs – menus, toolbars, dialogs and so on.

While we are learning the Java language basics, we will be using console applications as examples to illustrate
how things work. These are application that use simple command line input and output. With this approach
we can concentrate on understanding the specifics of the language, without worrying about any of the
complexity involved in creating and managing windows. Once we are comfortable with using all the features
of the Java language, we'll move on to windowed applications and applet examples.

Learning Java – the Road Ahead


Before starting out, it is always helpful to have an idea of where you are heading and what route you
should take, so let's take a look at a brief road map of where you will be going with Java. There are five
broad stages you will progress through in learning Java using this book:

1. The first stage is this chapter. It sets out some fundamental ideas about the structure of Java
programs and how they work. This includes such things as what object-oriented programming is all
about, and how an executable program is created from a Java source file. Getting these concepts
straight at the outset will make learning to write Java programs that much easier for you.

2. Next you will learn how statements are put together, what facilities you have for storing basic
data in a program, how you perform calculations and how you make decisions based on the
results of them. These are the nuts and bolts you need for the next stages.

3. In the third stage you will learn about classes – how you define them and how you can use
them. This is where you learn the object-oriented characteristics of the language. By the time
you are through this stage you will have learned all the basics of how the Java language works
so you will be ready to progress further into how you can use it.

9
Chapter 1

4. In the fourth stage, you will learn how you can segment the activities that your programs carry out
into separate tasks that can execute concurrently. This is particularly important for when you want
to include several applets in a web page, and you don't want one applet to have to wait for another
to finish executing before it can start. You may want a fancy animation to continue running while
you play a game, for example, with both programs sitting in the same web page.

5. In the fifth stage you will learn in detail how you implement an application or an applet with a
graphical user interface, and how you handle interactions with the user in this context. This
amounts to applying the capabilities provided by the Java class libraries. When you finish this stage
you will be equipped to write your own fully-fledged applications and applets in Java. At the end of
the book, you should be a knowledgeable Java programmer. The rest is down to experience.

Throughout this book we will be using complete examples to explore how Java works. You should
create and run all of the examples, even the simplest, preferably by typing them in yourself. Don't be
afraid to experiment with them. If there is anything you are not quite clear on, try changing an example
around to see what happens, or better still – write an example of your own. If you are uncertain how
some aspect of Java that you have already covered works, don't look it up right away – try it out.
Making mistakes is a great way to learn.

The Java Environment


You can run Java programs on a wide variety of computers using a range of operating systems. Your
Java programs will run just as well on a PC running Windows 95/98/NT/2000/XP as it will on Linux or
a Sun Solaris workstation. This is possible because a Java program does not execute directly on your
computer. It runs on a standardized hypothetical computer that is called the Java virtual machine or
JVM, which is emulated inside your computer by a program.

Java Java
Java
Source Compiler
Object
Code Code

Object code is
verified and loaded into
the Java virtual machine

Java virtual machine


The program is executed
by the interpreter Java interpreter

The interpreter handles all


communication with the
operating system for the
real machine.

Computer Operating System

10
Introducing Java

A Java compiler converts the Java sourcecode that you write into a binary program consisting of byte
codes. Byte codes are machine instructions for the Java virtual machine. When you execute a Java
program, a program called the Java interpreter inspects and deciphers the byte codes for it, checks it
out to ensure that it has not been tampered with and is safe to execute, and then executes the actions
that the byte codes specify within the Java virtual machine. A Java interpreter can run standalone, or it
can be part of a web browser such as Netscape Navigator or Microsoft Internet Explorer where it can be
invoked automatically to run applets in a web page.

Because your Java program consists of byte codes rather than native machine instructions, it is
completely insulated from the particular hardware on which it is run. Any computer that has the Java
environment implemented will handle your program as well as any other, and because the Java
interpreter sits between your program and the physical machine, it can prevent unauthorized actions in
the program from being executed.

In the past there has been a penalty for all this flexibility and protection in the speed of execution of
your Java programs. An interpreted Java program would typically run at only one tenth of the speed of
an equivalent program using native machine instructions. With present Java machine implementations,
much of the performance penalty has been eliminated, and in programs that are not computation
intensive – which is usually the case with the sort of program you would want to include in a web page,
for example – you really wouldn't notice this anyway. With the JVM that is supplied with the current
Java 2 System Development Kit (SDK) available from the Sun web site, there are very few
circumstances where you will notice any appreciable degradation in performance compared to a
program compiled to native machine code.

Java Program Development


There are a number of excellent professional Java program development environments available,
including products from Sun, Borland and Symantec. These all provide very friendly environments for
creating and editing your sourcecode, and compiling and debugging your programs. These are powerful
tools for the experienced programmer, but for learning Java using this book, I recommend that you
resist the temptation to use any of these, especially if you are relatively new to programming. Instead,
stick to using the Java 2 SDK from Sun together with a suitable simple editor for creating your
sourcecode. The professional development systems tend to hide a lot of things you need to understand,
and also introduce complexity that you really are better off without while you are learning. These
products are intended primarily for knowledgeable and experienced programmers, so start with one
when you get to the end of the book.

You can download the SDK from Sun for a variety of hardware platforms and operating systems, either
directly from the Sun Java web site at http://java.sun.com (for Windows, Solaris, and Linux operating
systems), or from sites that you can link to from there. The SDK we are going to use is available from
http://java.sun.com/j2se/1.4. For instance a version of the SDK for Mac OS is available from
http://devworld.apple.com/java/.

There is one aspect of terminology that sometimes causes confusion – the SDK used to be known as the
JDK – the Java Development kit. If you see JDK this generally means the same as SDK. When you
install the Java 2 SDK, you will see the old terminology survives in the name of the root directory where
the SDK is installed, currently /jdk1.4.

11
Chapter 1

I would urge you to install the SDK even if you do use one or other of the interactive development
environments that are available. The SDK provides an excellent reference environment that you can use to
check out problems that may arise. Not only that, your programs will only consist of the code that you write
plus the classes from the Java libraries that you use. Virtually all commercial Java development systems
provide pre-built facilities of their own to speed development. While this is very helpful for production
program development, it really does get in the way when you are trying to learn Java.

A further consideration is that the version of Java supported by a commercial Java product is not always
the most recent. This means that some features of the latest version of Java just won't work. If you really
do prefer to work with a commercial Java development system for whatever reason, and you have
problems with running a particular example from the book, try it out with the SDK. The chances are it
will work OK.

To make use of the SDK you will need a plain text editor. Any editor will do as long as it does not
introduce formatting codes into the contents of a file. There are quite a number of shareware and
freeware editors around that are suitable, some of which are specific to Java, and you should have no
trouble locating one. I find the JCreator editor is particularly good. There's a free version and a fee
version with more functionality but the free version is perfectly adequate for learning. You can
download a free copy from http://www.jcreator.com. A good place to start looking if you want to
explore what is available is the http://www.download.com web site.

Installing the SDK


You can obtain detailed instructions on how to install the SDK for your particular operating system
from the Sun web site, so I won't go into all the variations for different systems here. However, there are
a few things to watch out for that may not leap out from the pages of the installation documentation.

First of all, the SDK and the documentation are separate and you install them separately. The SDK for
Windows is distributed as a .exe file that you just execute to start installation. The documentation for
the SDK consists of a large number of HTML files structured in a hierarchy that are distributed in a ZIP
archive. You will find it easier to install the SDK first, followed by the documentation. If you install the
SDK to drive C: under Windows, the directory structure shown in the diagram will be created.

12
Introducing Java

Root directory
Contains a jar file jdk 1.4
containing source

bin demo include include-old jre lib

Compiler Subdirectories C header files


Interpreter containing for native
+ demo code code
Executeable for runtime Class libraries
other
executives bin lib

ext
jar files containing
extensions

classic Security

JVM DLL

hotspot applet

Hotspot JVM
DLL

The jdk1.4 directory in the diagram is sometimes referred to as the root directory for Java. In some
contexts it is also referred to as the Java home directory. If you want the documentation installed in the
hierarchy shown above, then you should now extract the documentation from the archive to the
jdk1.4 directory. This corresponds to C:\jdk1.4 if you installed the SDK to your C: drive. This will
create a new subdirectory, docs, to the jdk1.4 root directory, and install the documentation files in
that. To look at the documentation you just open the index.html file that is in the docs subdirectory.

You don't need to worry about the contents of most of these directories, at least not when you get
started, but you should add the path for the jdk1.4\bin directory to the paths defined in your PATH
environment variable. That way you will be able to run the compiler and the interpreter from anywhere
without having to specify supplying the path to it. If you installed the SDK to C:, then you need to add
the path C:\jdk1.4\bin. A word of warning – if you have previously installed a commercial Java
development product, check that it has not modified your PATH environment variable to include the
path to its own Java executables.

If it has, when you try to run the Java compiler or interpreter, you are likely to get the versions supplied
with the commercial product rather that those that came with the SDK. One way to fix this is to remove
the path or paths that cause the problem. If you don't want to remove the paths that were inserted for
the commercial product, you will have to use the full path specification when you want to run the
compiler or interpreter from the SDK. The jre directory contains the Java Runtime facilities that are
used when you execute a Java program. The classes in the Java libraries are stored in the jre\lib
directory. They don't appear individually though. They are all packaged up in the archive, rt.jar.
Leave this alone. The Java Runtime takes care of retrieving what it needs from the archive when your
program executes.

13
Chapter 1

The CLASSPATH environment variable is a frequent source of problems and confusion to newcomers
to Java. The current SDK does NOT require CLASSPATH to be defined, and if it has been defined by
some other Java version or system, it is likely to cause problems. Commercial Java development systems
and versions of the Java Development Kit prior to 1.2 may well define the CLASSPATH environment
variable, so check to see whether CLASSPATH has been defined on your system. If it has and you no
longer have whatever defined it installed, you should delete it. If you have to keep the CLASSPATH
environment variable – maybe because you want to keep the system that defined it or you share the
machine with someone who needs it – you will have to use a command line option to define
CLASSPATH temporarily whenever you compile or execute your Java code. We will see how to do this
a little later in this chapter.

Extracting the Sourcecode for the Class Libraries


The sourcecode for the class libraries is included in the archive src.zip that you will find in the jdk1.4
root directory. Browsing this source can be very educational, and it can also be helpful when you are more
experienced with Java in giving a better understanding of how things works – or when they don't, why they
don't. You can extract the source files from the archive using the Winzip utility or any other utility that will
unpack .zip archives – but be warned – there's a lot of it and it takes a while!

Extracting the contents of src.zip to the root directory \jdk1.4 will create a new subdirectory, src,
and install the sourcecode in subdirectories to this. To look at the sourcecode, just open the .java file
that you are interested in, using any plain text editor.

Compiling a Java Program


Java sourcecode is always stored in files with the extension .java. Once you have created the
sourcecode for a program and saved it in a .java file, you need to process the source using a Java
compiler. Using the compiler that comes with the JDK, you would make the directory that contains
your Java source file the current directory, and then enter the following command:

javac -source 1.4 MyProgram.java

Here, javac is the name of the Java compiler, and MyProgram.java is the name of the program
source file. This command assumes that the current directory contains your source file. If it doesn't the
compiler won't be able to find your source file. The -source command line option with the value 1.4
here tells the compiler that you want the code compiled with the SDK 1.4 language facilities. This
causes the compiler to support a facility called assertions, and we will see what these are later on. If you
leave this option out, the compiler will compile the code with SDK 1.3 capabilities so if the code uses
assertions, these will be flagged as errors.

If you need to override an existing definition of the CLASSPATH environment variable – perhaps
because it has been set by a Java development system you have installed, the command would be:

javac -source 1.4 -classpath . MyProgram.java

The value of CLASSPATH follows the -classpath specification and is just a period. This defines just
the path to the current directory, whatever that happens to be. This means that the compiler will look
for your source file or files in the current directory. If you forget to include the period, the compiler will
not be able to find your source files in the current directory. If you include the -classpath .
command line option in any event, it will do no harm.

14
Introducing Java

Note that you should avoid storing your source files within the directory structure that was created for
the SDK, as this can cause problems. Set up a separate directory of your own to hold the sourcecode for
a program and keep the code for each program in its own directory.

Assuming your program contains no errors, the compiler generates a byte code program that is the
equivalent of your source code. The compiler stores the byte code program in a file with the same name as
the source file, but with the extension .class. Java executable modules are always stored in a file with the
extension .class. By default, the .class file will be stored in the same directory as the source file.

The command line options we have introduced here are by no means all the options you have available
for the compiler. You will be able to compile all of the examples in the book just knowing about the
options we have discussed. There is a comprehensive description of all the options within the
documentation for the SDK. You can also specify the -help command line option to get a summary of
the standard options you can use.

If you are using some other product to develop your Java programs, you will probably be using a much
more user-friendly, graphical interface for compiling your programs that won't involve entering
commands such as that shown above. The file name extensions for your source file and the object file
that results from it will be just the same however.

Executing a Java Application


To execute the byte code program in the .class file with the Java interpreter in the SDK, you make
the directory containing the .class file current, and enter the command:

java -enableassertions MyProgram

Note that we use MyProgram to identify the program, NOT MyProgram.class. It is a common
beginner's mistake to use the latter by analogy with the compile operation. If you put a .class file
extension on MyProgram, your program won't execute and you will get an error message:

Exception in thread "main" java.lang.NoClassDefFoundError: MyProgram/class

While the compiler expects to find the name of your source file, the java interpreter expects the name of
a class, which is MyProgram in this case, not the name of a file. The MyProgram.class file contains
the MyProgram class. We will explain what a class is shortly.

The -enableassertions option is necessary for SDK1.4 programs that use assertions, but since we
will be using assertions once we have learned about them it's a good idea to get into the habit of always
using this option. You can abbreviate the -enableassertions option to -ea if you wish.

If you want to override an existing CLASSPATH definition, the option is the same as with the compiler.
You can also abbreviate -classpath to -cp with the Java interpreter, but strangely, this abbreviation
does not apply to the compiler. Here's how the command would look:

java -ea -cp . MyProgram

15
Chapter 1

To execute your program, the Java interpreter analyzes and then executes the byte code instructions.
The Java virtual machine is identical in all computer environments supporting Java, so you can be sure
your program is completely portable. As we already said, your program will run just as well on a Unix
Java implementation as it will on that for Windows 95/98/NT/2000/XP, for Solaris, Linux, OS/2, or
any other operating system that supports Java. (Beware of variations in the level of Java supported
though. Some environments, such as the Macintosh, tend to lag a little, so implementations for Java 2
will typically be available later than under Windows or Solaris.)

Executing an Applet
Note that the Java compiler in the SDK will compile both applications and applets. However, an applet is not
executed in the same way as an application. You must embed an applet in a web page before it can be run.
You can then execute it either within a Java 2-enabled web browser, or by using the appletviewer, a bare-
bones browser provided as part of the SDK. It is a good idea to use the appletviewer to run applets while
you are learning. This ensures that if your applet doesn't work, it is almost certainly your code that is the
problem, rather than some problem in integration with the browser.

If you have compiled an applet and you have included it in a web page stored as MyApplet.html in
the current directory on your computer, you can execute it by entering the command:

appletviewer MyApplet.html

So how do you put an applet in a web page?

The Hypertext Markup Language


The HyperText Markup Language, or HTML as it is commonly known, is used to define a web page. If
you want a good, compact, reference guide to HTML, I recommend the book Instant HTML
Programmer's Reference (Wrox Press, ISBN 1-861001-56-8). Here we will gather just enough on HTML so
that you can run a Java applet.

When you define a web page as an HTML document, it is stored in a file with the extension .html. An
HTML document consists of a number of elements, and each element is identified by tags. The
document will begin with <html> and end with </html>. These delimiters, <html> and </html>,
are tags, and each element in an HTML document will be enclosed between a similar pair of tags
between angle brackets. All element tags are case insensitive, so you can use uppercase or lowercase, or
even a mixture of the two, but by convention they are capitalized so they stand out from the text. Here
is an example of an HTML document consisting of a title and some other text:

<html>
<head>
<title>This is the title of the document</title>
</head>
<body>
You can put whatever text you like here. The body of a document can contain
all kinds of other HTML elements, including <B>Java applets</B>. Note how each
element always begins with a start tag identifying the element, and ends with
an end tag that is the same as the start tag but with a slash added. The pair
of tags around 'Java applets' in the previous sentence will display the text
as bold.

16
Introducing Java

</body>
</html>

There are two elements that can appear directly within the <html> element, a <head> element and a
<body> element, as in the example above. The <head> element provides information about the
document, and is not strictly part of it. The text enclosed by the <title> element tags that appears
here within the <head> element, will be displayed as the window title when the page is viewed.

Other element tags can appear within the <body> element, and they include tags for headings, lists,
tables, links to other pages and Java applets. There are some elements that do not require an end tag
because they are considered to be empty. An example of this kind of element tag is <hr/>, which
specifies a horizontal rule, a line across the full width of the page. You can use the <hr/> tag to divide
up a page and separate one type of element from another. You will find a comprehensive list of
available HTML tags in the book I mentioned earlier.

Adding an Applet to an HTML Document


For many element tag pairs, you can specify an element attribute in the starting tag that defines
additional or qualifying data about the element. This is how a Java applet is identified in an <applet>
tag. Here is an example of how you might include a Java applet in an HTML document:

<html>
<head>
<title> A Simple Program </title>
</head>
<body>
<hr/>
<applet code = "MyFirstApplet.class" width = 300 height = 200 >
</applet>
<hr/>
</body>
</html>

The two shaded lines between tags for horizontal lines specify that the byte codes for the applet are
contained in the file MyFirstApplet.class. The name of the file containing the byte codes for the
applet is specified as the value for the code attribute in the <applet> tag. The other two attributes,
width and height, define the width and height of the region on the screen that will be used by the
applet when it executes. These always have to be specified to run an applet. There are lots of other
things you can optionally specify, as we will see. Here is the Java sourcecode for a simple applet:

import javax.swing.JApplet;
import java.awt.Graphics;

public class MyFirstApplet extends JApplet {

public void paint(Graphics g) {


g.drawString("To climb a ladder, start at the bottom rung", 20, 90);
}
}

17
Random documents with unrelated
content Scribd suggests to you:
Fig. 690 Plates LVII and LVIII,
prepared by Professor Matas,
afford a synoptic view of the
more useful lines of skin
incision in the principal
amputations of the arm and
shoulder.
—This includes removal not
only of the arm, but of the
scapula and clavicle as well, or
at least its outer portion. It is
not often required, and
inasmuch as the circumstances
which justify it are seldom
duplicated, a suitable method
for each individual case should
be planned, rather than try to
make one set of directions
cover them all. Much will
depend upon whether sufficient
skin can be saved in order to
cover the large defect thus
made. In general, however, an
incision should first be made
along the clavicle, exposing it
and dividing it near its middle.
It is convenient to take out the
middle portion at this time, and
in this way to afford ample
room through which a proximal
ligation of the subclavian
vessels may be made, they
being here carefully dissected
Lines of amputation in lower third of forearm, of out, secured by double ligation,
elbow, and lower third of arm. (Modified from Mignon.) and divided. From the outer
pa
Interscapularthoracic Amputations. Removal of the Entire Upper Extremity.
rt
of the above incision another is carried downward and outward toward the
deltoid groove and then beneath the axilla to its posterior margin. The
posterior flap is then furnished by an incision continuous with the last one,
which terminates below about opposite the lower angle of the scapula, and is
then continued upward along the inner scapular border and over the shoulder
until it reaches the outer end of the incision first made. In this manner will be
furnished a sufficient covering. The balance of the operation consists in the
gradual separation of the entire mass from the outer wall of the thorax. With a
preliminary ligation of the subclavian vessels there will be no hemorrhage
which cannot be easily checked by pressure and forceps.
The above, however, is only a general description, which may need to be
modified in most cases. If the amputation be done for injury all the skin which
is still viable should be utilized, no matter how shaped, while if done for
disease the incisions may have to be modified materially, taking more skin
from one side and less from the other, in order to avoid that involved in the
disease process.
In the majority of cases the result is satisfactory, in spite of the mutilation
thus afforded.
Fig. 691
AMPUTATIONS OF THE
LOWER EXTREMITY.
The most important
physiological purposes of the
foot are those of support and
locomotion, not mere tactile
sensibility nor prehension. Its
purposes being different from
those of the upper extremity,
the tenets previously held
regarding the advantage of
conservatism may be changed
to some degree, for a tender
foot or leg-stump is sometimes
extremely annoying, even
disabling, and it is in the end Esmarch’s elastic constrictor applied and held in
far better to so plan an place by a bandage or a strap (Wyeth’s pins
amputation of this extremity as may also be used to hold the constrictor in
place) in high amputation of the arm. (S. Smith.)
to make the stump most
serviceable, without primary
reference to its exact length. As in the hand, foot-stumps should be covered
with dense plantar (instead of palmar) tissues, and the long flap should,
therefore, be made from the sole. When this is impossible it would be wiser to
shorten the stump. Moreover, as there will be constant friction upon the
resulting cicatrix, this should be placed in the most protected location, on the
dorsum of the foot.
The most important indication, then, in all foot amputations is to furnish a
complete plantar flap and to place the scar on top of the foot.
The Toes.—Amputations of the toes are, by virtue of their shortness, nearly
always disarticulations. The basal row of phalanges should be
preserved when possible, and even here the covering of the stump should be
as far as possible fashioned from the sole.
The big toe may be removed by either internal or oval plantar flaps, which
should be long enough to cover the metatarsal head, otherwise the latter must
be decapitated. These same principles also apply to the little toe. When all or
most of the toes have to be severed it may as well be done by a single dorsal
incision, as seen in Fig. 692, which will permit either their disarticulation or
their removal along with that of the ends of the metatarsals. These methods
are shown in Figs. 692 and 693.
Amputation of a toe with its metatarsal is best effected by a racket incision.
This may extend up to the posterior tarsal joint. Some have recommended to
enucleate the metatarsals subperiosteally, through dorsal incisions, all the soft
parts being scrupulously left behind. With the first and fifth toes the scar
should be so placed as to be removed from the edge of the foot (Fig. 693).
Partial amputations of the foot have been suggested and devised in great
numbers, and the subject has been greatly complicated by the number of
methods that were taught. Modern ideas of conservative surgery have caused
a complete departure from the anatomist’s standard, and it has been shown
that with aseptic technique there is no advantage in disarticulating when it
leaves irregular lines. As Matas says: “As Agnew taught long ago in this
country, and others elsewhere, the skeleton of the foot must be considered a
surgical unity, to be treated by the knife and saw just as the femur and
humerus would be, at the exact point which will yield the longest and most
useful stump to the patient. What is essential in every case is the application
of the principle of plantar flaps—preservation and scar protection.”
Concerning the utility of many of these methods and the usefulness of the
resulting stumps we may learn more from the makers of artificial limbs than
from almost any other source. Thus, Truax, for instance, who has had large
experience as a mechanic, has given this advice, as quoted by Matas: “Avoid
amputation within three inches of the ankle-joint; do not amputate between the
metatarsal bones and the junction of the lower and middle thirds of the tibia.
At other points save all you can, and you will in every case have done the best
for your patient.” Should one be rationally governed by this advice a large
number of amputation methods which cumber most text-books would be
discarded.
Fig. 692

1, simultaneous disarticulation of all the toes; 2, amputation of the toes in their


continuity. (Mignon.)
Fig. 693

1, partial amputations of the third and fifth metatarsals; 2, disarticulation of the


first and fifth metatarsals. (Mignon and Matas.)
Fig. 694

Tracings of intratarsal amputations at various levels (outer side): 1, subastragaloid; 2,


tibiotarsal; 3, tibiocalcaneal; the different lengths of flaps shown in relation to skeleton.
Fig. 695

Tracings of incisions in mediotarsal amputations and total amputation of fifth toe.


(Mignon and Matas.)

For my own part I would advise to save all of a foot that can be saved,
providing a sufficiently long plantar or heel flap can be retained; but if these
are not available, then I would advise amputation, at least three inches above
the ankle.
I would advise, moreover, to discard the complicated rules and technique of
stilted methods and to use the saw whenever it can be made useful, rather
than to go farther back to a row of joints simply because they are joints (Fig.
694).
Figs. 695 and 696 illustrate conservative modern methods, which are
perfectly available for most purposes, and from which departure need be
made only when peculiar circumstances obtain, which so complicate the case
that none of the ordinary rules would apply. A surgeon of judgment and
experience is competent to devise a flap for a given case, whether it complies
with standard methods or not. It seems to me, therefore, worth while to
describe only the so-called mediotarsal disarticulation of Chopart, in which but
the astragalus and calcis remain of the proper bones of the foot. The joint line
extends from just behind the tuberosity of the scaphoid to the outer side of the
body of the calcis, where a tubercle can be usually felt. Across this line an
incision is carried obliquely over the dorsum of the foot. The plantar flap is the
long one, and the line of division is just behind the balls of the toes. Two
lateral incisions can be made to facilitate disarticulation if desirable.
Fig. 696

1, disarticulation at the tarsometatarsal joint, showing length of flaps; 2, disarticulation of the


big toe in continuity. (Mignon.)
This operation sometimes leaves the foot in a bad equinus position;
accordingly it is wise to make tenotomy of the tendo Achillis, as well as to
attach the dorsal or extensor tendons to the stump end. (See Figs. 699 and
700.)
Amputations of the Foot (Tibiotarsal).—The former favorite method of
amputating the foot proper was that
of Syme, illustrated in Fig. 701. This preserved the plantar surface and tip of
the heel, thus forming a cutaneous hood, which was made to cover the lower
ends of the tibia and fibula, whose malleoli were usually removed close to
their terminations. The incision is made directly down to the bone, from the
apex of one malleolus across the sole and up to the other. Then the foot is
forced into extreme flexion and another incision carried directly across the
dorsum, by which the upper ends of the first are joined. This permits opening
the ankle-joint in front, after which the lateral ligaments are divided and the
astragalus dislocated forward. The heel hood is next carefully separated from
the calcis with the knife, and it and all the parts retracted from the ends of the
leg bones, which are divided just above the articular surfaces, or the latter
may be left and the malleoli alone removed. Now the heel hood is raised,
made to cover the end of the leg, and united to the anterior incision, drainage
being made by a small opening on the outer side of the tendo Achillis, as the
plantar surface of the flap should not be opened (Fig. 703).
Fig. 697 Fig. 698 Fig. 699 Fig. 700

Lisfranc’s Stump after same. Classical mediotarsal Stump after Chopart’s


tarsometatarsal amputation (Chopart), amputation.
disarticulation. showing length of (Farabeuf.)
(Farabeuf.) plantar flap.
(Farabeuf.)
Fig. 701

Syme’s tibiotarsal operation, showing part removed and lines of section, before division of
malleoli. (Farabeuf.)

Fig. 702, the complement of Fig. 701, illustrates the appearance of the
stump after the completion of the disarticulation and before the removal of the
malleoli.
Pirogoff introduced a serviceable modification by obliquely dividing the os
calcis in front of the heel, turning up its sawed surfaces without any dissection
of the hood from the heel, and uniting its fresh bone aspect with that made by
removal of the articular ends of the leg bones. This would seem to be
preferable to Syme’s disarticulation, affording a better walking stump. (See
Figs. 704 and 705.)
A reverse of this operation was suggested by Mikulicz and Wladimiroff,
independently, and at about the same time, the heel being excised by an
incision across the sole and then behind the ankle, the calcis being divided
and its posterior end removed, while the articular surfaces of the leg bones
are also removed. The foot is then brought down so that these surfaces can
be brought in contact, it being expected that after their reunion the individual
will walk in the exaggerated equinus position and upon the ends of the
metatarsal bones. The operation is, in effect, an exsection rather than an
amputation, and is applicable to but a very small number of cases, in which,
however, it sometimes gives excellent results. (See Fig. 707).
Fig. 702

Syme’s amputation after disarticulation of the foot at the ankle-joint. The soft parts are being
cleared from the malleoli preparatory to sawing the malleoli and lower articular surface of tibia.
(Farabeuf.)
Fig. 703

S, line of incision for Syme’s operation; P, line of incision for Pirogoff’s operation. (Erichsen.)

Amputations Of the Leg.—Modern prosthetic methods have materially


changed the indications in amputating the leg.
The pressure in artificial limbs is not borne upon the end of the stump, but is
rather circumferential and borne by a conical socket. It is now, therefore, an
object to preserve as much of the limb as practicable, in order to have better
leverage or control of the artificial member. Consequently the point of election
is now the middle of the leg, unless the amputation may be made even below
this point. The objection to a short leg stump is the inevitable flexion which the
hamstring flexors will produce; in such cases the pressure will be borne upon
the knee, while the appearance of the stump is by no means ideal. If,
therefore, one is forced to make a high amputation of the leg it would be far
preferable to make a good knee disarticulation, or, better still, a
supracondyloid amputation, with preservation of the patella, thus furnishing a
stump which affords perhaps the only exception to the general rule, i. e., that
weight cannot be borne upon the stump end.
Fig. 704 Fig. 705

Skeleton of stump after Pirogoff’s Stump after Pirogoff’s operation. The


osteoplastic amputation. The sawed weight of the body must rest upon the
surface of the calcaneum in apposition thick plantar skin of the heel and never on
with divided surface of tibia. (Farabeuf.) the thin skin of the retrocalcaneal surface.
(Farabeuf.)
Fig. 706

Sections of bone in Pirogoff’s amputation and its modifications: 1, oblique section of


calcaneum to correspond with (1) oblique section of tibia. (Gunther.) 2, curvilinear or
concave section of calcaneum to correspond with (2) convex section of tibia. (v.
Bruns.) 3″, horizontal section of calcaneum to correspond with (3) similar section of
tibia. (Pasquier Le Fort.) 3‴, vertical section of calcaneum to correspond with (3)
horizontal section of tibia. (Typical Pirogoff.) (Modified by Matas from Mignon.)
Fig. 707

Osteoplastic excision of foot. (Mikulicz.)

Let us, then, consider but one or two amputations of the leg—that low down
or near the middle and that at the knee. Whatever the method it is most
desirable that the scar be kept off to the side, and especially away from the
front of the shin. This can be best accomplished by a modified circular (Fig.
708) or a bilateral flap method (Fig. 711), or by the oblique method with lateral
incisions, which practically convert it into an anteroposterior operation, while
for certain instances the method of Teale may be preferred, i. e., that with a
long anterior and short posterior flap, or its modification by which the flaps are
made more lateral, or the even long flap method of Bell.
Fig. 708

Modified circular amputation of upper third of leg. (Erichsen.)

Whichever of these be selected, after division of the muscles and exposure


of the bone, it is usually helpful to retract the flaps, whatever their shape, by a
cloth retractor made of a piece of sterile bandage torn into three strips, the
middle of which should be inserted between the bones of the leg, the
interosseous membrane being divided for this purpose; by this they are held
more perfectly out of the way during the act of dividing the bones. The anterior
border of the tibia, which is practically a sharp ridge, should be divided
obliquely (bevelled), either by a small oblique section before the transverse
division is made, or by effecting this later, in order that there shall not remain a
sharp point to project through the skin or be subject to constant irritation. The
tibia is usually divided transversely, with the above exception. The fibula may
be divided slightly obliquely. It is customary, however, to make the division
simultaneously, and to so conduct the sawing process as to divide the fibula
completely before the last strokes of the saw cut through the tibia.
There is greater difficulty in the recognition and securing of vessels in leg
amputations than in any other, especially if they have been divided obliquely.
The principal vessels may be found from their known anatomical location.
They nevertheless sometimes tend to retract and they must be followed up in
order to properly secure them. The accompanying nerve trunks should also be
seized firmly, drawn down, and divided two or three inches above the line of
division of the other tissues, in order that they may retract out of harm’s way.
Every nerve which can be recognized, even in the skin, should be thus
treated. Before closing the wound it is well, unless one is absolutely sure of
his work, to release the tourniquet and ascertain if any vessel which would
otherwise bleed be not yet secured. Oozing may be checked with hot water,
while muscle surfaces which leak too much blood may be lightly enclosed
within catgut sutures inserted with a curved needle.
Providing that these stumps have well-nourished flaps, and that no sharp or
angular bone ends interfere with subsequent comfort, and that the scars be
kept away from their lower surfaces, they serve their purpose admirably.
Supposing, then, that amputation is to be about the middle, the first incision,
made with a stout scalpel, is begun at the anterior border of the tibia and
carried downward along it until it is turned abruptly backward to the posterior
aspect, and then upward until a point is reached opposite that of
commencement. The skin is dissected up for perhaps an inch. Then the flap
on the other side is cut after the same fashion, after which, with a short or long
knife, the muscles are divided transversely or circularly down to the bone.
Much will depend now upon whether the desire is to resort to the more
modern osteoplastic methods or adhere to the old. In the latter case it is well
to separate the flaps for the necessary distance from the bone, with or without
the periosteum, dividing the bones after suitable retraction, as above
suggested. If preference be for an osteoplastic flap it is planned and made at
this time, the bone being divided at the same level as the muscles, and the
amputation being thus practically completed, after which the osteoplastic flap
is arranged, it being now necessary to carefully preserve the periosteal bridge
and to again divide the bone at the base of this periosteal flap, this being the
true end of the bone stump. In this case the fibula is divided at a higher level.
It is perhaps less desirable to preserve periosteum in young children than in
adults, for if bone be permitted to grow too rapidly conical stumps result,
sometimes even with protrusion of bone ends. Ollier and his pupil Mondan
have shown that this so-called atrophic elongation of bone is a consequence
of abnormally rapid growth from the upper epiphyseal direction, permitted by
lack of pressure from below, and that conical stumps will often happen in
children in spite of every precaution. Nevertheless it should not be
encouraged, and for this reason periosteum should not be preserved.
The method of Teale was to cut a long anterior flap, raising the coverings
from the bone with the least possible disturbance, to divide the bone at the
high level, then to double the flap upon itself in such a way as to bring the scar
at a level one inch or more above the stump end. Heine modified this slightly
by raising the periosteum with the rest of the anterior flap. In cases which
permit such a long flap to be formed from one aspect of the leg the method
gives excellent results (Fig. 709).
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookgate.com

You might also like