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

Java All In One Desk Reference For Dummies 2nd Edition Lowe instant download

The document provides links to various 'All-in-One Desk Reference For Dummies' books, including titles on Java, Linux, Pro Tools, and Money Management. It includes information about the authors, publication details, and a comprehensive table of contents for the Java reference book. Additionally, it emphasizes the availability of instant digital downloads in multiple formats.

Uploaded by

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

Java All In One Desk Reference For Dummies 2nd Edition Lowe instant download

The document provides links to various 'All-in-One Desk Reference For Dummies' books, including titles on Java, Linux, Pro Tools, and Money Management. It includes information about the authors, publication details, and a comprehensive table of contents for the Java reference book. Additionally, it emphasizes the availability of instant digital downloads in multiple formats.

Uploaded by

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

Java All In One Desk Reference For Dummies 2nd

Edition Lowe pdf download

https://ebookname.com/product/java-all-in-one-desk-reference-for-
dummies-2nd-edition-lowe/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Linux All in One Desk Reference For Dummies 2nd Edition


Naba Barkakati

https://ebookname.com/product/linux-all-in-one-desk-reference-
for-dummies-2nd-edition-naba-barkakati/

Pro Tools All in One Desk Reference For Dummies 2nd


Edition Jeff Strong

https://ebookname.com/product/pro-tools-all-in-one-desk-
reference-for-dummies-2nd-edition-jeff-strong/

Money Management All in one desk Reference for


Canadians for Dummies 2nd Edition Heather Ball

https://ebookname.com/product/money-management-all-in-one-desk-
reference-for-canadians-for-dummies-2nd-edition-heather-ball/

Enhancing adult motivation to learn a comprehensive


guide for teaching all adults 3rd Edition Raymond J.
Wlodkowski

https://ebookname.com/product/enhancing-adult-motivation-to-
learn-a-comprehensive-guide-for-teaching-all-adults-3rd-edition-
raymond-j-wlodkowski/
Nahuatl as Written Lessons in Older Written Nahuatl
with Copious Examples and Texts 1st Edition James
Lockhart

https://ebookname.com/product/nahuatl-as-written-lessons-in-
older-written-nahuatl-with-copious-examples-and-texts-1st-
edition-james-lockhart/

Roman Barbarians The Royal Court and Culture in the


Early Medieval West Medieval Culture and Society First
Edition Yitzhak Hen

https://ebookname.com/product/roman-barbarians-the-royal-court-
and-culture-in-the-early-medieval-west-medieval-culture-and-
society-first-edition-yitzhak-hen/

Ableton Live 7 Power the Comprehensive Guide 1st


Edition Jon Margulies

https://ebookname.com/product/ableton-live-7-power-the-
comprehensive-guide-1st-edition-jon-margulies/

Towards Africa Oriented Risk Analysis Models A


Contextual and Methodological Approach 1st Edition
Korwa G. Adar

https://ebookname.com/product/towards-africa-oriented-risk-
analysis-models-a-contextual-and-methodological-approach-1st-
edition-korwa-g-adar/

Boronic Acids in Saccharide Recognition 1st Edition


Tony D. James

https://ebookname.com/product/boronic-acids-in-saccharide-
recognition-1st-edition-tony-d-james/
Discourse Studies A Multidisciplinary Introduction 2nd
Edition Teun A Van Dijk

https://ebookname.com/product/discourse-studies-a-
multidisciplinary-introduction-2nd-edition-teun-a-van-dijk/
Java

ALL-IN-ONE DESK REFERENCE


FOR

DUMmIES

by Doug Lowe
Java

ALL-IN-ONE DESK REFERENCE


FOR

DUMmIES

by Doug Lowe
Java™ All-in-One Desk Reference For Dummies®
Published by
Wiley Publishing, Inc.
111 River Street
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2005 by Wiley Publishing, Inc., Indianapolis, Indiana
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
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-8600.
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-4355, or online at http://
www.wiley.com/go/permissions.
Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the
Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade
dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United
States and other countries, and may not be used without written permission. Java is a trademark of Sun
Microsystems, Inc. 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.

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS
OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND
SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PAR-
TICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE
ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD
WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR
OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT
PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR
DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK
AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR
THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMEN-
DATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK
MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

For general information on our other products and services, 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.
For technical support, please visit www.wiley.com/techsupport.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may
not be available in electronic books.
Library of Congress Control Number: 2005923064
ISBN-13: 978-0-7645-8961-4
ISBN-10: 0-7645-8961-X
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1O/RU/QU/QV/IN
About the Author
Doug Lowe has been writing computer programming books since the guys who
invented Java were still in high school. He’s written books on COBOL, Fortran,
Visual Basic, for IBM mainframe computers, mid-range systems, PCs, Web pro-
gramming, and probably a few he’s forgotten about. He’s the author of more
than 30 For Dummies books, such as Networking For Dummies (7th Edition),
Networking For Dummies All-in-One Desk Reference, PowerPoint 2003 For
Dummies, and Internet Explorer 6 For Dummies. He lives in that sunny All-
American City Fresno, California, where the motto is, “It’s a sunny, All-American
City,” with his wife and the youngest of his three daughters. He’s also one of
those obsessive-compulsive decorating nuts who puts up tens of thousands of
lights at Christmas and creates computer-controlled Halloween decorations
that rival Disney’s Haunted Mansion. Maybe his next book should be Tacky
Holiday Decorations For Dummies.
Dedication
To Debbie, Rebecca, Sarah, and Bethany.

Author’s Acknowledgments
I’d like to thank project editor Kim Darosett, who did a great job of managing
all the editorial work that was required to put this book together in spite of a
short schedule and oft-missed deadlines, and acquisitions editor Katie Feltman
who made the whole project possible. I’d also like to thank John Purdum who
gave the entire manuscript a thorough technical review, tested every line of
code, and offered many excellent suggestions, as well as copy editor Rebecca
Senninger who made sure the i’s were crossed and the t’s were dotted (oops,
reverse that!). And, as always, thanks to all the behind-the-scenes people who
chipped in with help I’m not even aware of.
Publisher’s Acknowledgments
We’re proud of this book; please send us your comments through our online registration form located
at www.dummies.com/register/.
Some of the people who helped bring this book to market include the following:

Acquisitions, Editorial, and Composition Services


Media Development Project Coordinator: Maridee Ennis
Project Editor: Kim Darosett Layout and Graphics: Andrea Dahl,
Acquisitions Editor: Katie Feltman Lauren Goddard, Stephanie D. Jumper,
Copy Editor: Rebecca Senninger Melanee Prendergast, Heather Ryan,
Julie Trippetti
Technical Editor: John Purdum
Proofreaders: John Greenough, Leeann Harney,
Editorial Manager: Leah Cameron Jessica Kramer, Arielle Mennelle,
Media Development Manager: Carl Pierce
Laura VanWinkle Indexer: Ty Koontz
Media Development Supervisor:
Richard Graves
Editorial Assistant: Amanda Foxworth
Cartoons: Rich Tennant (www.the5thwave.com)

Publishing and Editorial for Technology Dummies


Richard Swadley, Vice President and Executive Group Publisher
Andy Cummings, Vice President and Publisher
Mary Bednarek, Executive Acquisitions Director
Mary C. Corder, Editorial Director
Publishing for Consumer Dummies
Diane Graves Steele, Vice President and Publisher
Joyce Pepple, Acquisitions Director
Composition Services
Gerry Fahey, Vice President of Production Services
Debbie Stailey, Director of Composition Services
Contents at a Glance
Introduction .................................................................1
Book I: Java Basics.......................................................7
Chapter 1: Welcome to Java ..............................................................................................9
Chapter 2: Installing and Using Java Tools ...................................................................21
Chapter 3: Working with TextPad...................................................................................35
Chapter 4: Using Eclipse..................................................................................................43

Book II: Programming Basics.......................................63


Chapter 1: Java Programming Basics.............................................................................65
Chapter 2: Working with Variables and Data Types.....................................................83
Chapter 3: Working with Numbers and Expressions .................................................113
Chapter 4: Making Choices............................................................................................141
Chapter 5: Going Around in Circles (Or, Using Loops)..............................................161
Chapter 6: Pulling a Switcheroo ...................................................................................187
Chapter 7: Adding Some Methods to Your Madness .................................................199
Chapter 8: Handling Exceptions ...................................................................................217

Book III: Object-Oriented Programming......................235


Chapter 1: Understanding Object-Oriented Programming........................................237
Chapter 2: Making Your Own Classes ..........................................................................249
Chapter 3: Working with Statics ...................................................................................265
Chapter 4: Using Subclasses and Inheritance.............................................................273
Chapter 5: Using Abstract Classes and Interfaces .....................................................293
Chapter 6: Using the Object and Class Classes ..........................................................305
Chapter 7: Using Inner Classes .....................................................................................329
Chapter 8: Packaging and Documenting Your Classes ..............................................339

Book IV: Strings, Arrays, and Collections....................353


Chapter 1: Working with Strings...................................................................................355
Chapter 2: Using Arrays.................................................................................................371
Chapter 3: Using the ArrayList Class ...........................................................................397
Chapter 4: Using the LinkedList Class .........................................................................409
Chapter 5: Creating Generic Collection Classes .........................................................419
Book V: Programming Techniques ..............................431
Chapter 1: Programming Threads ................................................................................433
Chapter 2: Network Programming................................................................................453
Chapter 3: Using Regular Expressions.........................................................................475
Chapter 4: Using Recursion...........................................................................................491

Book VI: Swing.........................................................505


Chapter 1: Swinging into Swing ....................................................................................507
Chapter 2: Handling Events...........................................................................................521
Chapter 3: Getting Input from the User .......................................................................537
Chapter 4: Choosing from a List ...................................................................................563
Chapter 5: Using Layout Managers ..............................................................................585

Book VII: Web Programming......................................603


Chapter 1: Creating Applets ..........................................................................................605
Chapter 2: Creating Servlets .........................................................................................613
Chapter 3: Using Java Server Pages .............................................................................633
Chapter 4: Using JavaBeans ..........................................................................................647

Book VIII: Files and Databases ..................................663


Chapter 1: Working with Files .......................................................................................665
Chapter 2: Using File Streams .......................................................................................679
Chapter 3: Database for $100, Please...........................................................................703
Chapter 4: Using JDBC to Connect to a Database ......................................................717
Chapter 5: Working with XML .......................................................................................733

Book IX: Fun and Games ...........................................751


Chapter 1: Fun with Fonts and Colors .........................................................................753
Chapter 2: Drawing Shapes ...........................................................................................767
Chapter 3: Using Images and Sound.............................................................................789
Chapter 4: Animation and Game Programming ..........................................................803

Index .......................................................................821
Table of Contents
Introduction ..................................................................1
About This Book...............................................................................................2
How to Use This Book .....................................................................................3
How This Book Is Organized...........................................................................3
Book I: Java Basics .................................................................................3
Book II: Programming Basics ................................................................3
Book III: Object-Oriented Programming ..............................................4
Book IV: Strings, Arrays, and Collections............................................4
Book V: Programming Techniques .......................................................4
Book VI: Swing ........................................................................................4
Book VII: Web Programming .................................................................4
Book VIII: File and Database Programming .........................................4
Book IX: Fun and Games ........................................................................5
This book’s Web site ..............................................................................5
Icons Used in This Book..................................................................................5
Where to Go from Here....................................................................................6

Book I: Java Basics .......................................................7


Chapter 1: Welcome to Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9
What Is Java, and Why Is It So Great?............................................................9
Platform independence .......................................................................10
Object orientation ................................................................................11
The Java API..........................................................................................12
The Internet...........................................................................................12
Comparing Java to Other Languages...........................................................13
Important Features of the Java Language ...................................................15
Type checking.......................................................................................15
Automatic memory management.......................................................17
Exception handling ..............................................................................17
On the Downside: Java’s Weaknesses .........................................................18
Java Version Insanity .....................................................................................19
What’s in a Name? ..........................................................................................20

Chapter 2: Installing and Using Java Tools . . . . . . . . . . . . . . . . . . . . . .21


Downloading and Installing the Java Development Kit.............................21
Downloading the JDK...........................................................................22
Installing the JDK..................................................................................23
Perusing the JDK folders .....................................................................23
Setting the path ....................................................................................24
x Java All-in-One Desk Reference For Dummies

Using Java’s Command-Line Tools...............................................................25


Compiling a program ...........................................................................26
Compiling more than one file..............................................................26
Using Java compiler options...............................................................27
Running a Java program ......................................................................29
Using the javap command...................................................................31
Other Java command-line tools..........................................................32
Using Java Documentation............................................................................32
JS2E API Docs........................................................................................33
Java Language Specification ...............................................................34

Chapter 3: Working with TextPad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35


Downloading and Installing TextPad ...........................................................35
Editing Source Files........................................................................................36
Compiling a Program .....................................................................................38
Running a Java Program................................................................................40
Running an Applet..........................................................................................41

Chapter 4: Using Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .43


Getting Some Perspective on Eclipse ..........................................................44
Understanding Projects.................................................................................46
Creating a Simple Project ..............................................................................47
Adding a Class File .........................................................................................52
Running a Program ........................................................................................56
Debugging a Java Program............................................................................57
Stepping through your programs .......................................................57
Examining variables .............................................................................59
Setting breakpoints ..............................................................................60
Refactoring Your Code...................................................................................61

Book II: Programming Basics .......................................63


Chapter 1: Java Programming Basics . . . . . . . . . . . . . . . . . . . . . . . . . . .65
Looking At the Infamous Hello, World! Program ........................................65
Dealing with Keywords..................................................................................68
Working with Statements ..............................................................................70
Types of statements.............................................................................71
White space...........................................................................................71
Working with Blocks ......................................................................................72
Creating Identifiers ........................................................................................73
Crafting Comments ........................................................................................74
End-of-line comments ..........................................................................74
Traditional comments..........................................................................75
JavaDoc comments ..............................................................................76
Table of Contents xi

Introducing Object-Oriented Programming ................................................76


Understanding classes and objects ...................................................76
Understanding static methods ...........................................................76
Creating an object from a class ..........................................................77
A program that uses an object ...........................................................78
So what’s the difference?.....................................................................80
Importing Java API Classes ...........................................................................81

Chapter 2: Working with Variables and Data Types . . . . . . . . . . . . . . .83


Declaring Variables ........................................................................................83
Declaring two or more variables in one statement..........................84
Declaring class variables.....................................................................84
Declaring instance variables...............................................................85
Declaring local variables .....................................................................86
Initializing Variables.......................................................................................88
Initializing variables with assignment statements ...........................88
Initializing variables with initializers .................................................89
Using Final Variables (Or Constants)...........................................................89
Working with Primitive Data Types .............................................................90
Integer types .........................................................................................91
Floating-point types .............................................................................93
The char type........................................................................................94
The boolean type..................................................................................95
Wrapper classes ...................................................................................96
Using Reference Types ..................................................................................96
Working with Strings......................................................................................98
Declaring and initializing strings........................................................98
Combining strings ................................................................................99
Converting primitives to strings ........................................................99
Converting strings to primitives ......................................................100
Converting and Casting Numeric Data ......................................................101
Automatic conversions......................................................................101
Type casting ........................................................................................102
Understanding Scope...................................................................................102
Shadowing Variables....................................................................................104
Printing Data with System.out....................................................................105
Standard input and output streams .................................................105
Using System.out and System.err.....................................................107
Getting Input with the Scanner Class ........................................................107
Importing the Scanner class .............................................................108
Declaring and creating a Scanner object.........................................109
Getting input .......................................................................................109
Getting Input with the JOptionPane Class ................................................111
xii Java All-in-One Desk Reference For Dummies

Chapter 3: Working with Numbers and Expressions . . . . . . . . . . . . .113


Working with Arithmetic Operators ..........................................................113
Dividing Integers ..........................................................................................116
Combining Operators ..................................................................................118
Using the Unary Plus and Minus Operators .............................................119
Using Increment and Decrement Operators .............................................120
Using the Assignment Operator .................................................................122
Using Compound Assignment Operators .................................................123
Using the Math Class ...................................................................................124
Constants of the Math class..............................................................125
Mathematical functions .....................................................................126
Creating random numbers ................................................................129
Rounding functions ............................................................................131
Formatting Numbers....................................................................................133
Weird Things about Java Math ...................................................................136
Integer overflow..................................................................................136
Floating-point weirdness ...................................................................137
Dividing by zero..................................................................................138

Chapter 4: Making Choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141


Using Simple Boolean Expressions ............................................................141
Using If Statements ......................................................................................144
Simple if statements...........................................................................144
if-else statements................................................................................146
Nested if statements ..........................................................................147
else-if statements................................................................................151
Mr. Spock’s Favorite Operators (The Logical Ones, of Course).............153
Using the ! operator ...........................................................................153
Using the & and && operators..........................................................154
Using the | and || operators ............................................................155
Using the ^ operator ..........................................................................156
Combining logical operators.............................................................157
Using the Conditional Operator .................................................................159
Comparing Strings........................................................................................159

Chapter 5: Going Around in Circles (Or, Using Loops) . . . . . . . . . . . .161


Your Basic while Loop .................................................................................162
The while statement ..........................................................................162
A counting loop ..................................................................................162
Breaking Out of a Loop................................................................................163
Looping Forever ...........................................................................................164
Letting the user decide when to quit...............................................165
Another way to let the user decide..................................................166
Using the continue Statement ....................................................................167
do-while Loops .............................................................................................168
Validating Input from the User ...................................................................170
Table of Contents xiii

The Famous for Loop...................................................................................173


The formal format of the for loop ....................................................173
Scoping out the counter variable .....................................................176
Counting even numbers ....................................................................177
Counting backwards ..........................................................................177
for loops without bodies ...................................................................178
Ganging up your expressions ...........................................................179
Omitting expressions .........................................................................181
Breaking and continuing your for loops..........................................181
Nesting Your Loops......................................................................................182
A simple nested for loop ...................................................................182
A guessing game .................................................................................183

Chapter 6: Pulling a Switcheroo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .187


else-if Monstrosities.....................................................................................187
A Better Version of the Voter Machine Error Decoder Program ............189
Using the switch Statement ........................................................................190
A Boring Business Example Complete with Flowchart ...........................191
Putting if Statements Inside switch Statements.......................................193
Creating Character Cases............................................................................194
Falling through the Cracks..........................................................................195

Chapter 7: Adding Some Methods to Your Madness . . . . . . . . . . . . . .199


The Joy of Methods .....................................................................................199
The Basics of Making Methods...................................................................200
An example..........................................................................................201
Another example ................................................................................202
Methods That Return Values ......................................................................204
Declaring the method’s return type.................................................205
Using the return statement to return the value..............................205
Using a method that returns a type .................................................206
You gotta have a proper return statement......................................206
Another version of the guessing game program ............................208
Using Methods That Take Parameters ......................................................211
Declaring parameters ........................................................................211
Scoping out parameters ....................................................................212
Understanding pass-by-value............................................................213
Yet another example of the guessing game program.....................214

Chapter 8: Handling Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .217


Understanding Exceptions..........................................................................217
Witnessing an exception....................................................................219
Finding the culprit..............................................................................219
Catching Exceptions ....................................................................................220
A simple example ...............................................................................221
Another example ................................................................................222
xiv Java All-in-One Desk Reference For Dummies

Handling Exceptions with a Pre-emptive Strike .......................................223


Catching All Exceptions at Once ................................................................225
Displaying the Exception Message ............................................................226
Using a finally Block.....................................................................................227
Handling Checked Exceptions ....................................................................229
The catch-or-throw compiler error..................................................229
Catching FileNotFoundException.....................................................230
Throwing the FileNotFoundException.............................................231
Throwing an exception from main ...................................................232
Swallowing exceptions.......................................................................232
Throwing Your Own Exceptions.................................................................233

Book III: Object-Oriented Programming ......................235


Chapter 1: Understanding Object-Oriented Programming . . . . . . . . .237
What Is Object-Oriented Programming? ...................................................237
Understanding Objects................................................................................238
Objects have identity.........................................................................239
Objects have type...............................................................................240
Objects have state..............................................................................240
Objects have behavior.......................................................................241
The Life Cycle of an Object .........................................................................242
Working with Related Classes.....................................................................243
Inheritance ..........................................................................................243
Interfaces.............................................................................................244
Designing a Program with Objects.............................................................244
Diagramming Classes with UML.................................................................245
Drawing classes ..................................................................................246
Drawing arrows...................................................................................248

Chapter 2: Making Your Own Classes . . . . . . . . . . . . . . . . . . . . . . . . . .249


Declaring a Class ..........................................................................................249
Picking class names ...........................................................................250
What goes in the class body .............................................................250
Where classes go ................................................................................251
Working with Members ...............................................................................253
Fields ....................................................................................................253
Methods...............................................................................................253
Understanding visibility ....................................................................254
Getters and Setters ......................................................................................254
Overloading Methods ..................................................................................257
Creating Constructors .................................................................................258
Basic constructors .............................................................................258
Default constructors ..........................................................................259
Calling other constructors ................................................................260
More Uses for this ........................................................................................262
Using Initializers...........................................................................................263
Table of Contents xv

Chapter 3: Working with Statics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .265


Understanding Static Fields and Methods ...............................................265
Working with Static Fields...........................................................................266
Using Static Methods ...................................................................................267
Counting Instances ......................................................................................268
Preventing Instances ...................................................................................271
Using Static Initializers ................................................................................271

Chapter 4: Using Subclasses and Inheritance . . . . . . . . . . . . . . . . . . .273


Introducing Inheritance...............................................................................273
Plains, trains, and automobiles ........................................................274
Playing games .....................................................................................275
A businesslike example .....................................................................276
Inheritance hierarchies......................................................................276
Creating Subclasses .....................................................................................277
Overriding Methods.....................................................................................278
Protecting Your Members ...........................................................................279
Using this and super in Your Subclasses ..................................................280
Inheritance and Constructors ....................................................................281
Using final......................................................................................................283
Final methods .....................................................................................283
Final classes ........................................................................................283
Casting Up and Down ..................................................................................284
Determining an Object’s Type ....................................................................286
Poly What? ....................................................................................................287
Creating Custom Exceptions ......................................................................289
The Throwable hierarchy..................................................................289
Creating an exception class ..............................................................290
Throwing a custom exception ..........................................................291

Chapter 5: Using Abstract Classes and Interfaces . . . . . . . . . . . . . . .293


Using Abstract Classes ................................................................................293
Using Interfaces............................................................................................296
Creating a basic interface..................................................................296
Implementing an interface ................................................................297
Using an interface as a type ..............................................................298
More Things You Can Do with Interfaces..................................................299
Adding fields to an interface .............................................................299
Extending interfaces ..........................................................................299
Using interfaces for callbacks...........................................................300

Chapter 6: Using the Object and Class Classes . . . . . . . . . . . . . . . . . .305


The Mother of All Classes: Object..............................................................305
Every object is an Object ..................................................................305
Using Object as a type .......................................................................306
Methods of the Object class .............................................................307
Primitives aren’t objects ...................................................................308
xvi Java All-in-One Desk Reference For Dummies

The toString Method....................................................................................309


Using toString .....................................................................................309
Overriding toString ............................................................................310
The equals Method ......................................................................................311
Using equals ........................................................................................312
Overriding the equals method..........................................................313
The clone Method ........................................................................................316
Implementing the clone method ......................................................317
Using clone to create a shallow copy ..............................................320
Creating deep copies .........................................................................321
The Class Class.............................................................................................327

Chapter 7: Using Inner Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .329


Declaring Inner Classes ...............................................................................329
Understanding inner classes.............................................................330
An example..........................................................................................330
Using Static Inner Classes ...........................................................................333
Using Anonymous Inner Classes ................................................................334
Creating an anonymous class ...........................................................335
Tick Tock with an anonymous class ................................................336

Chapter 8: Packaging and Documenting Your Classes . . . . . . . . . . .339


Working with Packages................................................................................339
Importing classes and packages.......................................................339
Creating your own packages.............................................................340
An example..........................................................................................342
Putting Your Classes in a JAR File ..............................................................343
jar command-line options .................................................................344
Archiving a package ...........................................................................345
Adding a jar to your classpath .........................................................346
Running a program directly from an archive..................................346
Using JavaDoc to Document Your Classes................................................347
Adding JavaDoc comments...............................................................347
Using the javadoc command.............................................................350
Viewing JavaDoc pages......................................................................351

Book IV: Strings, Arrays, and Collections ....................353


Chapter 1: Working with Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .355
Reviewing Strings .........................................................................................355
Using the String Class ..................................................................................357
Finding the length of a string ............................................................359
Making simple string modifications.................................................360
Extracting characters from a string .................................................360
Extracting substrings from a string .................................................361
Table of Contents xvii

Splitting up a string ............................................................................363


Replacing parts of a string ................................................................365
Using the StringBuilder and StringBuffer Classes....................................365
Creating a StringBuilder object ........................................................366
Using StringBuilder methods ............................................................367
A StringBuilder example....................................................................369
Using the CharSequence Interface.............................................................369

Chapter 2: Using Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .371


Understanding Arrays .................................................................................371
Creating Arrays.............................................................................................372
Initializing an Array......................................................................................373
Using for Loops with Arrays .......................................................................374
Solving Homework Problems with Arrays ................................................375
Using the Enhanced for Loop .....................................................................377
Using Arrays with Methods ........................................................................378
Using Two-Dimensional Arrays ..................................................................379
Creating a two-dimensional array ....................................................380
Accessing two-dimensional array elements....................................381
Initializing a two-dimensional array.................................................382
Using jagged arrays ............................................................................382
Going beyond two dimensions .........................................................384
A Fun but Complicated Example: A Chess Board ....................................385
Using the Arrays Class.................................................................................392
Filling an array ....................................................................................393
Sorting an array ..................................................................................393
Searching an array..............................................................................394
Comparing arrays...............................................................................394
Converting arrays to strings .............................................................395

Chapter 3: Using the ArrayList Class . . . . . . . . . . . . . . . . . . . . . . . . . . .397


The ArrayList Class......................................................................................398
Creating an ArrayList Object ......................................................................401
Adding Elements ..........................................................................................402
Accessing Elements .....................................................................................403
Printing an ArrayList ...................................................................................403
Using an Iterator...........................................................................................404
Updating Elements .......................................................................................406
Deleting Elements ........................................................................................407

Chapter 4: Using the LinkedList Class . . . . . . . . . . . . . . . . . . . . . . . . . .409


The LinkedList Class....................................................................................409
Creating a LinkedList ...................................................................................413
Adding Items to a LinkedList ......................................................................414
Retrieving Items from a LinkedList ............................................................416
Updating LinkedList Items ..........................................................................417
Removing LinkedList Items.........................................................................417
xviii Java All-in-One Desk Reference For Dummies

Chapter 5: Creating Generic Collection Classes . . . . . . . . . . . . . . . . .419


Why Generics? ..............................................................................................420
Creating a Generic Class .............................................................................421
A Generic Stack Class ..................................................................................422
Using Wildcard Type Parameters...............................................................426
A Generic Queue Class ................................................................................427

Book V: Programming Techniques ...............................431


Chapter 1: Programming Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .433
Understanding Threads...............................................................................433
Creating a Thread.........................................................................................434
Understanding the Thread class ......................................................435
Extending the Thread class...............................................................436
Creating and starting a thread..........................................................437
Implementing the Runnable Interface ......................................................438
Using the Runnable interface............................................................438
Creating a class that implements Runnable....................................439
Using the CountDownApp class .......................................................440
Creating Threads That Work Together......................................................442
Synchronizing Methods...............................................................................446
Threadus Interruptus ..................................................................................447
Finding out if you’ve been interrupted............................................447
Aborting the countdown ...................................................................449

Chapter 2: Network Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . .453


Understanding Network Programming......................................................453
IP addresses and ports ......................................................................454
Host names, DNS, and URLs..............................................................455
Telnet ...................................................................................................455
Getting Information about Internet Hosts.................................................456
The InetAddress class........................................................................456
A program that looks up host names ..............................................458
Creating Network Server Applications......................................................460
The Socket class ................................................................................461
The ServerSocket class......................................................................462
Introducing BART.........................................................................................463
The BartQuote class ..........................................................................464
The BartServer program ...................................................................465
The BartClient program.....................................................................468
BartServer 2.0 ...............................................................................................471
Table of Contents xix

Chapter 3: Using Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . .475


A Program for Experimenting with Regular Expressions........................476
Basic Character Matching...........................................................................478
Matching single characters...............................................................479
Using predefined character classes .................................................479
Using custom character classes.......................................................481
Using ranges........................................................................................482
Using negation ....................................................................................483
Matching multiple characters...........................................................483
Using escapes .....................................................................................485
Using parentheses to group characters ..........................................485
Using the | symbol.............................................................................487
Using Regular Expressions in Java Programs...........................................488
The String problem ............................................................................488
Using regular expressions with the String class.............................489
Using the Pattern and Matcher classes ...........................................489

Chapter 4: Using Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .491


The Classic Factorial Example....................................................................491
The non-recursive solution ...............................................................491
The recursive solution.......................................................................492
Displaying Directories .................................................................................494
Writing Your Own Sorting Routine.............................................................497
Understanding how Quicksort works ..............................................498
The sort method.................................................................................499
The partition method.........................................................................500
Putting it all together .........................................................................502

Book VI: Swing .........................................................505


Chapter 1: Swinging into Swing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .507
Some Important Swing Concepts You Need to Know ..............................507
Understanding what Swing does ......................................................507
The Swing class hierarchy.................................................................508
I’ve Been Framed! .........................................................................................510
Hello, World! in Swing ..................................................................................511
Positioning the Frame On-Screen...............................................................513
Using the JPanel Class .................................................................................514
Using Labels..................................................................................................516
Creating Buttons ..........................................................................................518
A Word about the Layout of Components.................................................520
xx Java All-in-One Desk Reference For Dummies

Chapter 2: Handling Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .521


Examining Events .........................................................................................521
Handling Events............................................................................................524
The ClickMe Program ..................................................................................526
Using Inner Classes to Listen for Events...................................................528
Adding an Exit Button..................................................................................530
Catching the WindowClosing Event...........................................................532
The ClickMe Program Revisited .................................................................534

Chapter 3: Getting Input from the User . . . . . . . . . . . . . . . . . . . . . . . . .537


Using Text Fields ..........................................................................................537
Looking at a sample program ...........................................................539
Using text fields for numeric entry ..................................................541
Creating a validation class ................................................................543
Using Text Areas...........................................................................................544
The JTextArea class ...........................................................................545
The JScrollPane class.........................................................................547
Using Check Boxes.......................................................................................548
Using Radio Buttons ....................................................................................551
Using Borders ...............................................................................................553
Designing a Pizza-Ordering Program .........................................................556
Using Sliders .................................................................................................559

Chapter 4: Choosing from a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .563


Using Combo Boxes .....................................................................................563
Creating combo boxes .......................................................................565
Getting items from a combo box ......................................................566
Handling combo box events .............................................................567
Using Lists.....................................................................................................567
Creating a list ......................................................................................569
Getting items from a list ....................................................................570
Changing list items.............................................................................571
Using Spinners..............................................................................................573
Using Trees ...................................................................................................575
Building a tree.....................................................................................576
Creating a JTree component .............................................................579
Getting the selected node .................................................................580
Putting it all together .........................................................................581

Chapter 5: Using Layout Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . .585


Introducing Layout Managers.....................................................................585
Using Flow Layout........................................................................................587
Using Border Layout ....................................................................................588
Table of Contents xxi

Using Box Layout .........................................................................................590


Using Grid Layout ........................................................................................592
Using GridBag Layout ..................................................................................593
Sketching out a plan...........................................................................594
Adding components to a GridBag ....................................................595
Working with GridBagConstraints....................................................597
A GridBag layout example.................................................................598

Book VII: Web Programming ......................................603


Chapter 1: Creating Applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .605
Understanding Applets................................................................................605
The JApplet Class.........................................................................................606
Looking At a Sample Applet........................................................................607
Creating an HTML Page for an Applet .......................................................611
Testing an Applet .........................................................................................611

Chapter 2: Creating Servlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .613


Understanding Servlets ...............................................................................613
Using Tomcat ................................................................................................614
Installing and configuring Tomcat....................................................615
Starting and stopping Tomcat ..........................................................617
Testing Tomcat ...................................................................................618
Creating a Simple Servlet ............................................................................619
Importing the servlet packages ........................................................619
Extending the HttpServlet class .......................................................619
Printing to a Web page.......................................................................620
Responding with HTML .....................................................................620
Running a Servlet .........................................................................................623
An Improved HelloWorld Servlet ...............................................................623
Getting Input from the User ........................................................................625
Working with forms ............................................................................625
The InputServlet servlet....................................................................626
Using Classes in a Servlet ...........................................................................627

Chapter 3: Using Java Server Pages . . . . . . . . . . . . . . . . . . . . . . . . . . .633


Understanding Java Server Pages..............................................................633
Using Page Directives ..................................................................................635
Using Expressions ........................................................................................636
Using Scriptlets ............................................................................................638
Using Declarations .......................................................................................640
Using Classes ................................................................................................642
xxii Java All-in-One Desk Reference For Dummies

Chapter 4: Using JavaBeans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .647


What Is a JavaBean?.....................................................................................647
Looking Over a Sample Bean ......................................................................648
Using Beans with JSP Pages........................................................................651
Creating bean instances ....................................................................651
Getting property values.....................................................................652
Setting property values .....................................................................653
A JSP page that uses a bean..............................................................654
Scoping Your Beans .....................................................................................656
A shopping cart application..............................................................657
The shopping cart page.....................................................................658
The BookCart JavaBean.....................................................................659

Book VIII: Files and Databases...................................663


Chapter 1: Working with Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .665
Using the File Class ......................................................................................665
Creating a File object .........................................................................667
Creating a file ......................................................................................668
Getting information about a file .......................................................668
Getting the contents of a directory..................................................669
Renaming files.....................................................................................670
Deleting a file ......................................................................................670
Using Command-Line Parameters..............................................................671
Choosing Files in a Swing Application.......................................................672
Creating an Open dialog box.............................................................674
Getting the selected file.....................................................................675
Using file filters ...................................................................................676

Chapter 2: Using File Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .679


Understanding Streams ...............................................................................679
Reading Character Streams ........................................................................680
Creating a BufferedReader ................................................................682
Reading from a character stream .....................................................682
Reading the movies.txt file................................................................683
Writing Character Streams..........................................................................686
Connecting a PrintWriter to a text file .............................................687
Writing to a character stream...........................................................688
Writing the movies.txt file .................................................................689
Reading Binary Streams ..............................................................................692
Creating a DataInputStream ..............................................................693
Reading from a data input stream ....................................................694
Reading the movies.dat file...............................................................695
Table of Contents xxiii

Writing Binary Streams................................................................................698


Creating a DataOutputStream ...........................................................699
Writing to a binary stream ................................................................700
Writing the movies.dat file ................................................................700

Chapter 3: Database for $100, Please . . . . . . . . . . . . . . . . . . . . . . . . . . .703


What Is a Relational Database? ..................................................................703
What Is SQL, and How Do You Pronounce It?...........................................704
SQL Statements ............................................................................................704
Creating a SQL Database .............................................................................705
Querying a Database....................................................................................707
Using your basic select......................................................................707
Narrowing down the query ...............................................................709
Excluding rows....................................................................................709
Singleton selects.................................................................................709
Sounds like ..........................................................................................710
Column functions ...............................................................................710
Selecting from more than one table .................................................711
Eliminating duplicates .......................................................................713
Updating and Deleting Rows.......................................................................713
The delete statement .........................................................................713
The update statement........................................................................715

Chapter 4: Using JDBC to Connect to a Database . . . . . . . . . . . . . . . .717


Setting Up a Driver .......................................................................................717
Setting up an ODBC data source ......................................................717
Setting up the MySQL JDBC connector ...........................................719
Connecting to a Database ...........................................................................720
Querying a Database....................................................................................721
Executing a select statement ............................................................723
Navigating through the result set.....................................................723
Getting data from a result set ...........................................................723
Putting it all together: A program that reads from a database.....725
Updating SQL Data .......................................................................................728
Using an Updatable RowSet Object ...........................................................729
Deleting a row .....................................................................................730
Updating the value of a row column ................................................731
Inserting a row ....................................................................................732

Chapter 5: Working with XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .733


What Exactly Is XML, Anyway?...................................................................733
Tags ......................................................................................................734
Attributes ............................................................................................735
The movies.xml file ............................................................................735
Using a DTD ..................................................................................................736
Another Random Document on
Scribd Without Any Related Topics
This line of conduct certainly appears uncivil; I must, therefore,
conclude that the emperor is unwilling to admit our intercourse. If
you have any thing further to speak of, say it; but do not go over
yesterday’s conversation again.”
Dep. “Our country wishes to receive and treat you with liberality; but
there is an appearance of secrecy in the letter to the minister, which
requires explanation. Our conduct is in accordance with true
politeness. How say you we are uncivil?”
Envoy. “If, when the ship arrived, the minister of commerce had
immediately reported to the emperor the arrival of a United States’
vessel, with a special envoy on board, bearing a letter from the
President to the emperor, and had requested leave for the mission to
proceed forthwith to the capital, such conduct would have been
open, polite, and becoming. But to profess that he dare not report to
the emperor, and detain the mission here for a long period, refusing
to let it proceed at once to the capital, is, indeed, extremely rude.”
Dep. “Hitherto all envoys bringing letters here, from whatever
country, have stated their contents and the objects of their mission,
through officers deputed, like us, to receive such information. This
has always been necessary before a report could be made. We have
heard of you as a just, polite, and well-demeaned nation; and the
minister, when he heard of your arrival, was much pleased, and
desirous of bringing your business to a satisfactory conclusion, in
order to establish a friendly intercourse with you. [They were here
told that the minister was required to make no such request.] What
answer would he be able to give, should the emperor inquire about
particulars?”
Here they were pointed to Mr. Crawford’s account of his mission to
Siam and Cochin-China, page 269; where he received what
amounted to a reprimand, for having shown to the governor of
Saigon the governor-general’s letter, when the minister of elephants
told him: “It is his majesty’s wish, when the governor-general writes
again, that the letter may be sealed, for this is the custom of Cochin-
China.” And again, “It is not agreeable to the customs of the country,
that any should inspect letters addressed to his majesty, before they
reach his own presence.”
They did not appear, or choose not to appear, acquainted with the
circumstances of Mr. Crawford’s mission, and did not want, they said,
the original letter, but a translation.
Envoy. “If I return, and report to the President that, when I came
here to propose a friendly intercourse between our countries, the
ministers of Cochin-China refused to report my arrival to the
emperor; took upon themselves to treat me rudely, and, after having
detained me a whole month, forced me to leave, without obtaining
admission to the capital; when this is told, what, think you, will be
the world’s opinion of your country? Its opinion will be, that you are
an extremely rude nation. If permission be not soon given for me to
proceed to the capital, I shall be necessitated to leave; for within the
present year I have to go to eight or nine other places.”
The latter part of this reply was intended to remove an error they
seemed to have fallen into, in supposing that the ship had come
from the United States, solely to negotiate a treaty with Cochin-
China.
Dep. “Every thing in our country must be done according to
etiquette. Hitherto all countries, whether far or near, have paid
regard to this rule. The etiquette to be observed by ministers of
government, is to report no business, until they have obtained
complete knowledge of it. We have been desirous to effect for you
the objects of your mission, but you have been obstinate in your
determinations. Pray, what would you think of an envoy from any
other country coming here, and refusing to have any thing done
through the medium of officers deputed, like us, for the purpose of
arranging the business of his mission, and insisting on immediate
admission to the emperor’s presence? If the circumstances be told to
all the world, the right and wrong will then be known. Our country
has always received other nations liberally, without deriving any
advantage from them.
“Before,” they continued, “you said there was no translation of the
President’s letter; now you say there is:—before, you said the vessel
was going to no other place; now you say she is going to nine other
places. What are we to understand by this?”
As not the slightest hint had been given to favour either of these
assertions, they were immediately contradicted. They had never
been told, either that the President’s letter was not translated, or
that the envoy had business in Cochin-China alone.
They now stated they did not want the letter opened; they only
required to know what was desired; whether land to build factories
on, privileges of trade, or what?
Envoy. “No favours or privileges are asked for. Our government does
not build factories. Friendly intercourse alone is desired.”
Dep. “Is commerce desired?”
Envoy. “That is necessarily included in friendly intercourse between
the two countries; which will be for the advantage, not of one, but
of both.”
Dep. “You have now come over an extensive ocean as an envoy. The
minister has acted according to the emperor’s gracious wishes of
tenderness towards foreigners. He wishes to conclude your affairs
happily and satisfactorily; but you persist and determine, of your
own accord, to return unsuccessful. Say not that you were not
received well and liberally. The fault lies with you!”
Envoy. “As you refuse our intercourse, and I cannot obtain
permission to go to Hué, I must leave shortly. The fault lies not with
me, but in the minister’s uncivil treatment. On my return, I shall
have to report, that the minister had the presumption to take the
business of the mission into his own hands, without making any
report to the emperor. How call you such conduct ‘liberal
treatment?’”
Dep. “We too have been sent to bring the business of your mission
to a determinate point; but your obstinacy leaves us at a loss what
to do. We will return in a day or two to the capital, and make a
report of the circumstances.”
This was said by the two who had arrived on the twenty-sixth.
In reply, they were told that the envoy could have nothing to do with
their movements; that when quite ready he would leave; but that,
when he did so, he would write a protest against the manner in
which he had been treated, and would send a copy of such protest
to the emperor, and copies to other princes also. At first, not
seeming to understand what was meant, they desired that it should
be sent to the minister instead of the emperor; but this, they were
told, was out of the question.
January twenty-ninth. Some gentlemen who had been on shore in
the course of yesterday, having been asked when the ship would
sail, Mr. Morrison visited the deputies this morning, with the
following written communication:—
“I hear that you inquired last evening when our ship
would sail. I am directed by the envoy to tell you, that if,
within six days, the imperial permission be not received
for the mission to go to Hué, the vessel will then sail.
“The envoy does not act inconsiderately, as deeming this
an affair of a trivial nature: but he is necessitated to leave,
because the business confided to him, in other places, will
not admit of a long delay.
“Nor does he consider it a thing of small import, that the
minister of commerce, &c., refuses to report his arrival to
the emperor, or to afford him the means of presenting the
letter.”
In reply, the two deputies who had first arrived, (for the other two,
though not yet on their way for Hué, did not appear,) returned to
their former position, that they were desirous of bringing the
business to an amicable and satisfactory conclusion, but were
prevented by the obstinacy of the envoy. If a translation of the
President’s letter, and a complete statement of the objects of the
mission, were delivered to them, then some conclusion might be
come to.
They were told it was useless talking thus, as the determination of
the envoy had already been communicated to them. Should the
envoy go to Hué, on his arrival there, the minister might receive a
copy of the President’s letter, and what explanations he might desire
as to the objects of the mission. Similar conversation was kept up for
a few minutes, during which the deputies received a written paper
from the other two, who were within. They then wrote, that “the
President, being elected and promoted by the people, and not
possessing the actual title of king, it behooved him to write in a
manner properly decorous and respectful; on which account it was
requisite for the translation to be examined, in order to expunge
improper words.”
In reply to this insulting language, they were told that the President
was inferior to no king or emperor, and were then left.
In consequence of the insult thus offered to the
President, Mr. Morrison again went on shore in the DEPUTIES’
FALSEHOODS.
afternoon, in company with Mr. Fowler, for the
purpose either of obtaining an apology, or of handing the deputies,
for the information of the minister, a protest from the envoy against
the adoption of such language. They now withdrew what they had
said in the morning; and, having previously torn up the paper on
which they had written, they denied that they had said what was
attributed to them. “The other day,” said they, “you told us that your
President is elected by the people; we asked, therefore, whether he
was really a king or not: and letters, we said, should be humble and
decorous.”
Had there been any doubt (which there was not) of the real sense of
what they said in the morning, the total incoherency of what they
now advanced would afford strong presumption against its truth; for
who could write in one sentence, the question, “Whether or not the
President is a real king;” and the assertion that “letters should be
humble and decorous,” with other than the insulting views attributed
to them in the morning? But, as they denied having spoken by
command of their master the minister, and wholly disclaimed any
intention of insult, the apology was thought sufficient, and the
envoy’s protest was not handed to them. They were again told that,
though the President did not bear the title of king, yet he was equal
to any king or emperor, and was so acknowledged by all with whom
the United States had intercourse.
This point being set to rest, a list of the refreshments, which had
been received from them at different times, was handed to them,
with a request that they would say whether it was correct or not.
They were then told, that if the business of the mission were to end
unsuccessfully, the refreshments they had sent could not be
accepted as presents, but must be paid for. This they strenuously
resisted, saying, repeatedly, that the things were of small value.
“Nothing,” they were answered, “of the smallest value, could be
accepted, if the mission ended without going to Hué. Should the
mission proceed thither, they would be accepted as tokens of a
friendly disposition between the two countries; but otherwise, no
friendly intercourse being established, every thing must be paid for.”
As the feast, when brought on board, had been represented as
coming from the emperor, it was now asked how that could be the
case, since the emperor was not yet apprized of the vessel’s arrival?
The deputies replied, that it was customary to present such
refreshments to foreign vessels on their arrival; therefore it was
considered as coming from the emperor, although prepared by the
provincial officers, at the direction of the minister.
They were then asked what the minister’s object was in thus
delaying the business of the mission, and refusing to report to the
emperor. They replied, as usual, that their wish was to expedite, not
to retard the business of the mission; which was hindered, they said,
only by the envoy’s refusal to act according to their advice. It was
argued, that if any one had business with them, he would not stay
to explain his business to their servants, but would require to speak
with themselves at once. Arguments, however, proved useless. They
either could or would not comprehend them. The two deputies, who
were returning to Hué, had not left, but were to start the same
evening.
January thirtieth. The deputies appearing to act
under specific orders, from which they could not ENVOY’S LETTER.
deviate in the least, the envoy now addressed a
letter to the minister of commerce, specifying the objects of the
mission, and enclosing a copy of the President’s letter, with a
Chinese translation of it. The following are copies of the
documents:—
Letter from Edmund Roberts, Esq., special envoy from the
United States of America, to the Cochin-Chinese minister
of foreign affairs, commerce, &c.:—
“Edmund Roberts, special envoy from the United States of
America, desires to inform your excellency, that he wrote,
on the eighteenth of the present month, acquainting your
excellency with the wish entertained by the President of
the United States to open a friendly intercourse with the
emperor of Cochin-China; and with his consequent
appointment of myself to be the bearer of a letter which I
am to present to his majesty; having, at the same time,
full powers to treat, on behalf of the President, for the
important objects which he has in view.
“I have now the pleasure to enclose copies of the original,
and a translation in Chinese, of the President’s letter to
the emperor, for your excellency’s inspection. The
important objects of the President, mentioned in the letter,
are solely to ascertain, if the emperor is willing to admit
the American commercial intercourse on the same terms
as those of the most favoured nations; or on what
conditions he will admit it, and into what ports. No
exclusive privileges are asked for. And the envoy is not
charged with any other matter or thing, excepting to
establish a suitable commercial treaty between the two
nations. These are the only objects of the mission.
“Had your excellency sent a written answer, requesting
the above information, the envoy would have given these
particulars previously; but certain persons inquired the
object of the vessel’s coming, and asked for a copy of the
President’s letter, to whom this information could not be
given, as they could show no document or authority from
your excellency.
“The envoy has already been here some time, and will be
unable to delay much longer. He therefore requests your
excellency to provide the means for himself, and others
who are to accompany him, to proceed to Hué speedily.
For unless, within seven days, permission be received,
from the emperor, to proceed thither at once, the vessel
must go to sea.
“Signed and sealed on board the U. S. ship-of-war
Peacock, in the roadstead of Vung-lam, in the province of
Fooyan, this thirtieth day of January, A. D., 1833, and of
independence, the fifty-seventh.
(Signed,)
“EDMUND ROBERTS.”
“Andrew Jackson, President of the United States of
America, to his majesty the emperor of Cochin-China:—
“Great and good friend—
“This will be delivered to your majesty by Edmund
Roberts, a respectable citizen of these United States, who
has been appointed special agent, on the part of this
government, to transact important business with your
majesty. I pray your majesty to protect him in the exercise
of the duties which are thus confided to him, and to treat
him with kindness and confidence; placing entire reliance
upon what he shall say to you in our behalf, especially
when he shall repeat the assurances of our perfect amity
and good will towards your majesty. I pray God to have
you, great and good friend, under his safe and holy
keeping.
“Written at the city of Washington, the twentieth day of
January, A. D. 1833, and in the fifty-sixth year of
independence.
“Your good and faithful friend,
(Signed)
“ANDREW JACKSON.”
“By the President.
(Signed)
“Edward Livingston, Sec’ry of State.”
“The foregoing is a true copy of the original now in my
possession.
(Signed)
“Edmund Roberts.”
These documents being completed, the packet was INCREASING
sealed up, and taken on shore by Mr. Morrison; but DEMANDS.
now a new and unexpected difficulty arose. The
letter (which, they were told, though addressed to the minister, was
intended to be seen by the emperor) must be opened, submitted to
their inspection, and corrected entirely according to their taste, ere
they would receive or forward it.
This unheard-of and arrogant requisition was strongly objected to.
“What is the cause,” they were asked, “of such behaviour? Here are
four officers of whose names and rank we are equally ignorant. (For
their rank they had evaded telling, when asked, and their names,
though told by two of them, were not suffered to be written down.)
These officers require full information, respecting the objects of our
mission, and refuse to forward our official letters. In no other
country, we have been to, is an envoy thus treated.”
With the deputies, however, nothing that could be said was of any
use. They acted apparently on specific and peremptory orders, and
evinced a total disregard for every thing but a complete concession
to all their demands. On the present occasion they refused to write
an answer to what was said to them. Through the interpreter they
repeated the same language they had before so often used,
respecting their own and the minister’s anxiety to conclude the
business of the mission satisfactorily; the necessity of conforming to
the customs and etiquette of the country, and the obstinacy of the
envoy, &c.
“Were a letter,” they were asked, “sent to you, would a copy be first
shown to your servants?”
“No,” they replied, “but the case is not parallel. Your envoy is like
one standing at the door of a house.”
“Admitting that, suppose me coming to the door of your house, on
business with you, should I have to inform your servants what my
business was before I could enter?”
The quick little interpreter, Miguel, said that this was agreeable to
reason, a point which the deputies were less ready to admit. They
could not allow the comparison. “Such,” said they, “are our laws.
They must be implicitly obeyed.”
“Had there been an imperial order,” it was resumed, “or a written
answer from the minister, then the business of the mission might be
communicated to you; but how can it be communicated to persons
of whose names and rank we are ignorant? The objects of the
mission have, therefore, been stated in the letter, which it will be
well for you to forward. This obstinacy in requiring to know our
objects is insulting.”
Mr. Morrison was now pressed to return to the ship, to receive the
envoy’s permission for them to see the contents of the packet, and
correct the phraseology of the letters. Finding them determined not
to receive it as it was, he accordingly left, after having repeated the
necessity of paying for their presents, should their continual
opposition cause the failure of the mission. They appeared
personally desirous of conciliation, though their national vanity and
prejudices would not suffer them to see any thing absurd or
improper in the conduct which their orders obliged them to adopt.
In the evening Mr. Morrison again went on shore, with Chinese
copies of the President’s letter to the emperor, and the envoy’s letter
to the minister. Having required that the crowd of attendants, who
usually stood round, listening to the conversation, should be
dismissed, the envoy’s letter was shown to the deputies. They
immediately proceeded to criticise every word and sentence, making
several alterations and corrections, which, though of small
importance, and generally unobjectionable, occupied considerable
time. During the conversation, which the remarks, made on various
parts of the letter, occasioned, the interpreter Miguel, apparently of
his own accord, though probably prompted by his employers,
remarked, that the President was equal to a king; but that the
emperor was superior to a king. The natural inference, that the
emperor of Cochin-China is superior to the President of the United
States, he left to be deduced by others. The remark arose from an
endeavour, on the part of the deputies, to have the President’s title
placed lower than that of the emperor; not, they would have it
believed, from an idea of inequality, but on account of the humbler
style, which they insisted, the writing party must adopt in speaking
of themselves. The envoy, it was answered, had taken that station,
which courtesy to the person he addressed, required; but to place
the President lower than the emperor, was a point of a different
nature—a point which courtesy did not require, and which, the
President and emperor being in every respect equal in rank, could
never be complied with. Having at length concluded with the letter
to the minister, every correction which could be considered
derogatory or mean having been rejected, the deputies now desired
to see a copy of the President’s letter. This was for some time
objected to; and the impropriety of the demand, as well as the
unpleasantness of compliance pointed out. They were resolved,
however, to see it, and at length it was shown to them; but as they
were proceeding to make alterations in it also, they were stopped,
and told that the President’s letter could not be altered. Without
making alterations in it, they insisted that the letter could not be
forwarded; nor would they consent to receive it at all, unless, after
seeing every correction made in both letters that they wished, the
packet should be sealed before their eyes. They were told this want
of confidence was offensive, and required a similar discredit of their
authority, as their names and rank were unknown, and they had
shown no credentials. They thereupon stated their names and rank,
said they had no credentials; and argued that they too had been
shown no credentials by the envoy. The envoy, it was replied, would
show his powers to the proper individuals in fit time and place.
They still insisted on correcting the President’s letter. Mr. Morrison
therefore returned, about nine, P. M., leaving the sealed package,
addressed to the minister, in charge of the deputies.
January thirty-first. Mr. Morrison, having made a
copy of the envoy’s letter to the minister, with the REMONSTRANCE.
corrections which were last night agreed to, as
being immaterial, repaired on shore, in the forenoon, with authority
to make such trivial alterations, in the translation of the President’s
letter, as the deputies might desire. He first inquired if the packet
that was left on shore had been sent to the minister; and was
answered, that, not being corrected, it could not be forwarded. The
deputies then repeated their unchanging expressions of a desire, on
the part of the minister who had sent them, to arrange matters
speedily, and on a friendly footing. Such conversation being little
likely to lead to any good result, it was avoided; and they were
requested, as they would not forward the packet, to return it. This
was accordingly done; and the envelope being removed, the
translation of the President’s letter was laid before them,
accompanied with a remonstrance against their conduct, in insisting
that it should be altered before they would forward it. About two
hours were now spent in objecting to particular words and
sentences, either as being improper and contrary to etiquette, or as
being unintelligible. They also made particular inquiries respecting
the original letter, whether it was sealed or not, and whether the
Chinese translation was signed by the President. They put some
questions, also, respecting the signature of the Secretary of State,
what was his rank, &c.; and asked if the original letter was kept on
board; and if the one shown to them was only a copy. When told,
“of course,” they said, “that is right.”
Among other points, they professed not to understand the
expression, “Great and good friend;” and they interpreted it
according to their preconceived ideas, as a “request for a friendly
intercourse.” The expression was explained to them, and shown to
be perfectly intelligible, (for it was only their astonishment at such
familiar language, that prevented their understanding it.) But still
they considered it quite inadmissible; the common word yew, a
friend, was unsuitable and improper between two great powers. The
only thing that would satisfy such hairbreadth distinguishers, was to
say, “Your country and mine have amicable intercourse.” Wherever
the simple and common word I (wo) occurred, it became necessary
to substitute some other word, having a similar meaning, (as pun.)
And for he or him, (ta,) referring to the envoy, they required in
substitution of kae-yuen, “the said officer.” Where the President says,
“I pray your majesty to protect him, and to treat him with kindness
and confidence,” they wished to introduce a request for “deep
condescension” on the part of the emperor, which was rejected; and,
to satisfy them, a slight change was made in the phraseology of the
translation, but without permitting any thing servile. The President’s
letter concludes with this expression:—“I pray God to have you
always, great and good friend, under his safe and holy keeping.”
This they wished to change into a prayer to “imperial heaven, for the
continual peace of your majesty’s sacred person.” In opposition to
this proposed change, which would present the President in the light
of an idolater, the Christian notion of the Deity, as “one God, the
Supreme Ruler of heaven and earth, of the nations and their
sovereigns,” was explained to them; and the divinity of heaven and
earth, believed by the Chinese and Cochin-Chinese, was denied.
They then proposed, by another change of the term used to express
the Deity, to make the President pray to the “Gods of heaven.” But
this point they were obliged also to give up.
Having thus gone over the whole letter, without the admission of any
degrading terms, though some expressions which they wished to
have adopted were still of a doubtful nature, they were informed,
that if, after consideration, it should appear right to make the
proposed alterations, a copy would be taken on shore in the
evening. As they insisted on having the packet closed before their
eyes, it was agreed that the despatch should then be sealed up, and
given them to forward to the minister. But they were not yet
satisfied. After suffering the letter to the minister to pass muster,
(which they did with some reluctance,) they re-examined the
President’s letter, and pointed out how much the words, emperor,
Cochin-China, &c., should, as indicative of respect, be elevated
above the head margin of the page; and finally, they decided that it
would be very improper for the President to address his letter simply
to the emperor, (te che;) it must, they said, be transmitted either
with silent awe, (suh te,) or with uplifted hands, (fung, or te shang)
—terms in frequent use among the Chinese, and their humble
imitators, the Cochin-Chinese, in addresses from subjects to their
sovereigns. These expressions were, therefore, rejected, and Mr.
Morrison returned on board, to consider the other expressions, and
explain them to the envoy. They were told that a translation must be
faithful to the original. They said it should give the sense without
adhering to the words of the original. This was admitted; but if a
different tone were adopted, they were told, the sense could not be
preserved.
Shortly after Mr. Morrison had reached the ship, he
was followed by one of the deputies, the other FRESH
INTERROGATORI
being kept back probably by his liability to sea- ES.
sickness. The former came furnished with written
directions, to which he at times referred, having neglected to gain
satisfactory knowledge of two important points, viz.:—whether there
were any presents for the emperor, “as a token of sincerity;” and
whether the envoy was prepared to submit to the etiquette of the
court, at an audience of the emperor—this point being rendered very
doubtful by the previous resistance shown to their numerous
requisitions.
In reply to the first question, the deputy was told, that as the
subject was not mentioned in the letter from the President, it was
unnecessary to refer to it, before the conclusion of a treaty. Should
the emperor desire any thing particular, it might be sent at his
request.
Deputy. “The emperor’s coffers are full and overflowing, well
provided with every thing curious and valuable; how can he desire
any thing from you? But you have come to seek trade and
intercourse. Although the emperor is tender and kind to strangers,
and willing to admit them—yet, consider, if it appears well to come
without presents and empty handed.”
Envoy. “My country asks no favours or ‘tenderness’ from any; but I
desire to know how the emperor is willing to admit our merchants to
trade; whether on the same footing as the Chinese, &c., or not. Our
ships are found every where, but we seek favours from none.”
Dep. “I have heard that it is customary among the nations of the
west, to send presents, when seeking intercourse with the
dominions of others. On this account I ask the question, not because
the emperor wants any thing.”
Envoy. “As the emperor does not want presents, why do you speak
of them? Should a treaty be concluded, this is a minor matter, which
can then be spoken of; but which does not require any previous
attention.” To this the deputy assented.
The ceremony of presentation was easily dismissed, by informing the
deputy, that nothing beyond a bow, as to the President, would be
performed. The ceremony of the country was then asked. He said,
that it was to make five prostrations, touching the ground with the
forehead; and asked if five distinct bows would be acceded to
without the prostrations. To this the envoy replied, yes; he would
make five, ten, or as many bows as they desired; but the kneeling
posture is becoming only in the worship of the Creator.
The deputy now urged the necessity of proper
regard being paid to the elevation of the words FARTHER DELAYS.
emperor, Cochin-China, &c., and to the use of
“humble and decorous expressions.” To this advice he endeavoured
to give greater force, by saying, that in the correspondence held by
the kings of An-nam, before the assumption of the present title of
emperor, such humble phraseology was made use of. This argument
would imply inferiority in the President, to one who bears the high
title of emperor, and was, therefore, instantly repelled as insulting.
The deputy denied its being insulting, maintained the propriety of his
argument, and insisted on the use, at the commencement of the
President’s letter, of one or other of the derogatory terms already
mentioned, viz.: that the letter was sent with “silent awe,” or that it
was presented with “uplifted hands.” He was admonished not to
repeat so insulting a demand; for that the President stands on a
footing of perfect equality with the highest emperor, and cannot,
therefore, use any term that may make him appear in the light of
one inferior to the emperor of Cochin-China. The same term, it was
added, will be used as it is used in the letter from the envoy to the
minster, which term implies equality, without any disrespectful
arrogation of it. Such demands, he was told, far from being
amicable, were of a very unfriendly nature.
In reply, he said, that unless this requisition was complied with, he
and his fellow-officers dare not forward the despatch, enclosing the
copy of the President’s letter, nor dare they, he added, forward the
letter to the minister, without the President’s letter, although the
mention made in it of the latter should be erased. As this
determination left no alternative, but complete failure or
dishonourable concessions, he was required to repeat the refusal,
which he did more than once, and then returned to the shore.
CHAPTER XV.
SUSPENSION OF INTERCOURSE—FAILURE OF MISSION—
DEPARTURE OF EMBASSY FROM VUNG-LAM BAY—
ENVOY’S TITLES—MODE OF HUSKING RICE—TOMBS OF
THE DEAD—FISHING BOATS—ABSENCE OF PRIESTS AND
TEMPLES—SUPERSTITIONS—WILD ANIMALS—
MANDARINS’ HOUSE—MODE OF TAKING LEAVE—
GOVERNMENT OF COCHIN-CHINA—GRADES OF RANK.
Two days having elapsed, on the third of February, without any
official intercourse with the shore, the junior deputy again appeared;
his colleague still remaining on shore on account of sickness. The
professed object of his coming, was a mere visit; the real one, to
propose another word to be used at the commencement of the
President’s letter, if the words previously suggested would not be
adopted. This word was kin, implying reverence, solemnity, and
veneration, &c., not differing materially from that which had before
been proposed: it was also rejected. The expression as it already
stood, contained, he was told, nothing disrespectful, and was a plain
and simple version of the original. He was determined, however, that
without the adoption of some derogatory expression, the letter
should not be sent on to Hué; so that the business of the mission
remained at a stand.
The deputy now shifted his position, as indeed none of his fellows
scrupled to do when needful, by adopting a false assertion: “While
on shore,” he said, “every word was assented to; why is the use of
these words now refused?” This shows the convenient deafness or
forgetfulness, which these little-minded politicians can assume, when
occasion requires; for it had been specifically stated, that not a word
would be altered without farther consideration, and the permission
of the envoy.
Thus baffled, he said that the obstinate determination of the envoy
left him at a loss in what way to act.
“There is but one way,” he was answered, “in which you can act.
Take the President’s letter without these alterations. If you insist on
them, the business of the mission is at an end. The vessel will,
however, stay the time already mentioned, till she is quite ready to
leave. But you must not suppose she can wait to receive farther
refusals to fresh applications for permission to go to Hué.”
When leaving, it was carelessly said to him, that as he had said
American vessels were at liberty to trade, he should give a copy of
the regulations of commerce. This he refused.
The next day, some similar questions respecting commerce, which
were asked during a short complimentary visit, were received
uncourteously, and answered by the deputies with professions of
ignorance.
February seventh. Eight days having now elapsed
since the return of the deputies to Hué, and FAILURE OF
MISSION.
nothing having been heard relative to the mission,
the two remaining deputies were informed, that the vessel would go
to sea on the morrow; and Mr. Morrison was about to pay a farewell
visit, and urge the receipt of payment for the refreshments, at
different times sent off, when the younger deputy came on board.
After a few compliments had passed, he was told, that if the wind
were favourable, the ship would go to sea in the morning. He was
asked, also, if there was any news.
The native Christian, Miguel, before interpreting what was said,
asked if the ship would not wait till something was heard from Hué.
But the deputy, who was more cautious of expressing his feelings,
simply replied, that he had no news. Had he heard from Hué, he
would immediately have come to report the news. He requested that
no offence would be taken, nor any unpleasant feeling be
entertained, on account of the manner in which the mission left; as
the failure was entirely owing to the difference of custom in the two
countries. He hoped that all unfriendliness would be dismissed, and
that American vessels would frequent the Cochin-Chinese harbours,
as much as if the mission had succeeded.
In reply to what he said respecting the difference of customs, he
was told, that it could not be the custom of the country to exact
professions of inferiority from other countries, as the minister had
endeavoured to do in the present instance. The emperor, he said,
would have used the same phraseology, as that proposed to be used
in the letter, if addressing, by his envoy, the President of the United
States. This, he was told, would not be desired in the United States;
and, on the contrary, would only be subject to ridicule. He replied:
“Though you might not require it, our customs would!” It was
rejoined: “Since you would adhere to your own customs, if on a
mission to the United States, it stands to reason that the envoy of
the United States should adhere to his customs here.”
He now shifted his ground, and, while admitting that the expression
proposed was a strong one, maintained, nevertheless, that it was
not indicative of inferiority. Its use, by inferiors in addressing their
superiors, was pointed out to him; and he was asked, why, as the
word first used was far from disrespectful, he should wish it to be
changed? being, at the same time, again assured, that the words he
had suggested, should not be adopted. “If you have so determined,”
he rejoined, “I cannot receive this letter. But though the mission fail,
that will not prevent your vessels coming to trade.”
“The trade,” it was replied, “is on so bad a footing, the regulations
being unknown, and the government-charges and duties
unascertained, that vessels cannot come here.”
“All nations that come here,” he answered, “for instance, the English
and French, are on the same footing with you. They do not inquire
about the laws; and none dare extort from them more than the
regular charges.”
“This,” he was told, “is not true; for the Chinese are on a different
footing, being able to go to many places where the English and
French cannot go. England and France have endeavoured to form
treaties, but without success. We know the regulations of the English
and French trade, but do not know any for the American trade:
hence our mission.”
Being thus driven from one untenable position to another, he at
length pleaded ignorance. Admitting the fact, that the Chinese are
allowed to trade in Tonquin and other places, he however knew only
the regulations of Hué and Turan, and knew nothing of the laws in
other places.
“The mission,” it was answered, “is not sent to you, but to the
emperor. He knows what the regulations are in every place.”
“The minister,” he replied, “would know all, if the letter were sent to
Hué: but without the change of phraseology already pointed out, it
could not be sent. The envoys of Burmah and Siam have used the
same expressions as those proposed to you.”
“This,” he was answered, “can be of no avail with the envoy of the
United States. If the envoys of Burmah and Siam have assented,
either ignorantly or with full knowledge, to adopt expressions of a
servile nature, that can have no influence on this mission.”
“Without the letter,” repeated the deputy, “the minister cannot report
to the emperor.”
Envoy. “If he will, he can.”
Dep. “As I have not received any notice from Hué, I cannot say what
he has done.”
Envoy. “Eight days have elapsed since the two deputies have
returned to the capital.”
Dep. “Only five days have elapsed since your last letter to the
minister was shown us.”
The deputy was now requested to receive payment for the
refreshments sent to the envoy and the ship, as it was unpleasant to
accept any thing in the form of presents, the envoy not having
obtained the objects of his mission. He was urged not to refuse
payment, and assured that the envoy was sorry he was obliged to
leave, without having brought about a friendly intercourse between
the two nations. He refused, however, all payment as strenuously as
it was urged upon him. The things, he said, were mere trifles, and
he could not accept any thing for them. Nor in this did he say
wrong; for they probably cost the government very much less than
their real value, small as that was.
Before leaving, the deputy drank the health of the President; and the
health of the emperor of Cochin-China was drunk in return. He then
took leave, wishing us health and a pleasant voyage, and a speedy
return. He was thanked and told that he must not expect to see us
again.
The next morning, the ship got under weigh; and though all day
slowly beating out of the harbour, nothing more was seen of the
Cochin-Chinese.
During the discussion with the Mandarins relative
to the letter which was to be written to the TITLES OF
ENVOY.
minister, I refused to consider him in any other
light than my equal in rank, as they were so strongly disposed to
exalt him, and debase me if possible. The deputies expressed some
surprise at this observation, and demanded upon what ground I
claimed an equality with them; they were answered, as the
representative of an independent power. They then asked what were
my titles; if they were of as much importance as the minister’s, and
if they were as numerous. They were told that there was no order of
nobility in the United States, and so they had been previously
informed; still they insisted that there must be something equivalent
to it, and that, as I held an important office under the government, I
should not be without titles of some sort. Finding the gentlemen
were so extremely desirous that I should have an appendage to my
name, and as they would not be satisfied with a denial, I at once
concluded to humour them. I replied that I would comply with their
wishes, and furnish them with the greatest abundance of titles. As
they had been extremely unwilling to give the titles of the emperor
or the minister, or their own, they probably concluded that I was
actuated by the same motives as themselves in withholding mine,
whatever they were. The gentlemen belonging to the ship who were
in the cabin, looked very much astonished at this reply, wondering
how I was to extricate myself from this seeming difficulty; but they
were speedily relieved. The principal deputy having prepared his
Chinese pencil and half a sheet of paper, sat down to write. I
immediately observed to him, that it was necessary to commence
with a whole sheet, at which he expressed some surprise, and said
that the minister’s titles would not occupy one fourth of it. Having
determined to give them, in the first place, the names of all the
counties, and the two hundred and odd towns in my native state, as
well as the mountains, rivers, and lakes, which would supply the
places of titles, and then, if they were not satisfied, to proceed in
the same manner with all the other states in the Union, which, by
giving first the names of the several states, then the counties,
towns, &c., would probably occupy them for some days, if they had
had sufficient perseverance to proceed to the end of what I intended
should be endless. I then commenced as follows, Mr. Morrison acting
as interpreter and frequently translator:
Edmund Roberts, a special envoy from the United States, and a
citizen of Portsmouth, in the state of New Hampshire. I then
proceeded with the counties of Rockingham, Strafford, Merrimack,
Hillsborough, Grafton, Cheshire, Sullivan, and Coos. When he had
written thus far, which occupied much time, owing to the almost
insurmountable difficulties in rendering them into Chinese, he
expressed strong signs of impatience and asked if there were any
more; I requested him not to be impatient, as I was very desirous
that not one should be omitted, as it was a matter of primary
importance in all governments where titles were used. He remarked,
that already they were greater in number than were possessed by
any prince of the empire. However, he dipped his pencil in the ink,
and recommenced as follows: I first took Gosport, in the Isles of
Shoals, being farthest at sea, and then went on with the towns on
the seacoast; with Hampton and Seabrook, Rye and New Castle, and
then Newington, Stratham, and Exeter. Having proceeded thus far,
and finding difficulties succeeding difficulties, at every syllable and at
every word, he laid down his pencil, seemingly exhausted, and asked
if there were any more, as he had then filled a sheet of Chinese
paper. I answered, he had scarcely made a commencement: at this
he said it was unnecessary to record the rest; and that he never
heard or read of any person possessing a like number. He
complained of a headache and sickness, owing to the rolling of the
ship. I then begged he would desist, for that time, and call on board
as early as he could make it convenient on the following morning,
for I was exceedingly anxious he should have them all; then there
would be no hesitation in acknowledging that I was not
presumptuous, when I stated that the prime minister could not be
considered my superior in point of rank, as he did not possess so
many titles. It was now very evident that he began to be alarmed at
the extent of my titles, lest they should totally eclipse those of the
minister, and that I might be desirous of ascending a step higher
than his excellency. He replied that he was fully satisfied that I was
every way equal to him in point of rank. I urged him to proceed, but
without effect, for he refused very firmly, but politely, and therefore
most reluctantly I was obliged to accede to his wishes.
The whole scene was certainly most ludicrous. Some of the
gentlemen could with much difficulty restrain their risible faculties,
while others walked out of the cabin, being utterly unable to refrain
from laughter, while I kept a most imperturbable countenance until
the whole matter was concluded. I renewed the attempt the next
morning, when he came on board, but he looked quite aghast at the
mere request, and thus ended this farcical scene.
It may be thought by those who are for submitting
to every species of degradation, to gain commercial NATIONAL
USAGES.
advantages, that I was unnecessarily fastidious in
the course I adopted in the negotiation with Cochin-China; but when
it is known that there is no end to the doctrine of submission with
the ultra-Gangetic nations; and all past negotiations of European
powers will fully confirm what I now state, that neither privileges,
nor immunities, nor advantages of any kind, are to be gained by
submission, condescension, conciliation, or by flattery, (they despise
the former as a proof of weakness—the latter as arguing a want of
spirit;) that threats and aggressions are neither justifiable nor
necessary, a dignified, yet unassuming conduct, jealous of its own
honour, open and disinterested, seeking its own advantage, but
willing to promote that of others, will doubtless effect much with
nations of this stamp and character, and must in the end be able to
accomplish the object desired.
Previous to visiting Cochin-China, I had laid down certain rules of
conduct, which I had resolved to adopt towards these people, as
well as the Siamese. In the first place, I had determined to adhere
most strictly to the truth, however detrimental it might be to the
interest of our commerce at present, or however unpalatable it
might be to either of the nations. I had further resolved, not to
submit to any degrading ceremonies, by performing the Ko-tow,
uncovering the feet, &c., &c. My answer to such requisitions would
be: We do not come here to change the customs of your court with
its own statesmen, but we come as independent people, for a short
interview. Let your statesmen preserve their customs, and we will
preserve ours. Still, it may be answered: You come to us, we do not
go to you: my reply then would be: When you come to us, you shall
be allowed your own customs, in the mode of presentation to the
President. Reasoning with these people, must not be founded on the
ground of lord and vassal, but reciprocity. National usages should be
avoided as much as possible, and natural reason, common sense,
the reciprocal rights of men, be taken as the foundation of
intercourse. There is no end to the doctrine of submission to law,
where every worthless justice of peace tells you with a bare-faced lie
in his mouth, that his will and present declaration are the law of the
land. Seeing the gross impositions practised, by apparently friendly
nations, with other negotiators, I had further determined never to
repose any confidence in their advice, but to let my own judgment
be the guide of what was just and right. Furthermore, to be kind and
courteous to all; but after some little formalities, to reveal as little to
inferior officers as possible; and lastly, to use some state and show,
as they are useful auxiliaries in making an impression upon the
uncivilized mind.
I deem it best, here to remark, that in my negotiations with Asiatics,
all apparent acknowledgments of inferiority, which precedes
signatures to letters, as “your humble servant,” &c., are always
construed literally, and of course have an injurious effect upon a
conceited and arrogant people; and great nicety should be observed
in preparing documents on parchment, to which should be attached
a large seal, incased in a gold box, having the envelope of rich
yellow silk or satin, or otherwise it will give offence.
To all outward appearance the country surrounding this noble bay is
in a highly flourishing condition, but on a more close examination
this beautiful vision is not realized. The inhabitants are without
exception the most filthy people in the world. As soon as the boat
touches the strand, out rush from their palm-leaf huts, men and
women, and naked children and dogs, all having a mangy
appearance; being covered with some scorbutic disease, the itch or
small-pox, and frequently with white leprous spots. The teeth, even
of the children who are seven or eight years old, are of a coal black,
their lips and gums are deeply stained with chewing areca, &c., their
faces are nasty, their hands unwashed, and their whole persons
most offensive to the sight and smell; for the most part the comb
has never touched the children’s heads, and a whole village may be
seen scratching at the same time from head to foot. They are
apparently brought up in utter idleness; not a school is to be found,
and they are seen playing all day long at hide-and-go-seek under the
boats, lounging among the palm-trees, or sleeping on the bare
ground in the shade or sun, as they find it most convenient. The
dress of the men and women is nearly the same, being a wide long
shirt, buttoned generally on the right side, with a pair of short simple
trousers, made of cotton. Those who are able, wear a turban of
black crape, and every man who makes any pretensions to gentility,
has a pair of reticules or broad-mouthed purses, in which he puts
areca and tobacco: these are thrown over the shoulders, and are
generally neatly made; some are wrought extensively in gold, some
embroidered with silk; others are of plain silk or satin, and generally
of their favourite colour, blue: those of an ordinary kind are worn
about the waist, or carried in the hand. But the dress of nineteen
twentieths of the inhabitants is merely a waist-cloth, which is kept in
a most filthy condition.
In the course of a whole month, the period of our
residence here, I have not seen a person bathe, PRODUCTS.
although beaches abound every where: the Cochin-
Chinese appear to have an utter aversion to cleanliness, and one
would be apt to infer that they all had a touch of the hydrophobia,
from their aversion to water. From the highly flourishing appearance
of the land, the immense number of fishing and coasting boats
constantly employed, it would be reasonable to conclude that great
quantities of sugar, coffee, cotton and fish were exported, and that
provisions of all kinds could be had in abundance; but such is not
the fact: from one to three small miserable junks, from the island of
Hainan, visit here annually, bringing coarse tea and some paper, and
take in return, ground-nut-oil, a small quantity of wax, and some
colambac, here called kinam; being a resinous aromatic concretion,
and generally said to be taken from the heart of the aloe wood.
Sapan wood is occasionally to be bought. The terrace culture is
resorted to, in raising upland rice. In fact, not enough rice is raised
for the use of the inhabitants, and they are obliged to import part of
this necessary article of food from Nhiatrang, and other parts of the
kingdom.
Their mode of freeing rice from the husk, is by means of a long
beam having a pestle at one extremity; the beam plays on a pivot
secured between two parallel upright posts, a large mortar being
firmly fixed in the ground; the beam is elevated by the operator
placing his foot upon the other end; this is a primitive, and a very
slow method of freeing the husk from the kernel, and it causes it to
be much broken. Indian corn appears to thrive well, but they obtain
but a scanty supply: if more attention was paid to agriculture, and a
less number of people were employed in fishing, exports to a large
amount might be made within a few years; they import rice and tea,
when they might raise both in abundance, as well as coffee.
Elephants appear to be used here for domestic purposes; they are
said to be found in great numbers. Buffaloes, having a hump
between the fore shoulders, are used in the plough as well as the
common ox; the price given for the former for the use of the ship,
has been from ten to fifteen dollars. A small fleet horse, or rather
pony, is here much used, the price being about twenty quans, equal
to eleven dollars. Fowls, ducks and pigs, are by no means plentiful,
and are only bought at high prices; they will offer two, three or four
of the two former for a Spanish dollar or for a couple of common
jackknives, which they much prefer. The fruits which have been thus
far offered for sale, are the custard-apple and the jack, limes,
oranges, pomegranates, watermelons, lemons of immense size, and
a great variety of the plantain and banana, in one kind of which I
found a great many seeds; they were disposed of in horizontal layers
in six compartments, having a small pith running through them;
there are about fifty seeds in each, of an irregular shape, pointed
slightly, and white at the apex; immediately beneath them was a
black ring, extending about one fourth of the way down. Never
having seen any seed-bearing plantain, I am induced to note it;
when ripe, the outside is of a reddish yellow, and the fruit pleasant
to the taste. The vegetables are few in number, and all we have yet
seen, are beans, the egg-plant, and the sweet potato.
Great care appears to be taken of the remains of the dead—some
are placed in tombs of stone, neatly built and plastered, having a
small wicker-work house placed in the centre—others are deposited
in a common grave, having a basket-work roof which is placed there
to protect them from wild beasts. The inhabitants are civil, but
sometimes troublesome in approaching too near—they seem
desirous of handling every part of the dress—but the sad condition
they are in, makes it necessary frequently to use coercive measures
to keep them at a wholesome distance. The naval button, with an
eagle and an anchor on it, demands universal admiration. A few
small junks are built of wood and many are repaired at Vunglam.
Fishing occupies a large portion of the time of the
inhabitants, and from one hundred to one hundred FISHING-BOATS.
and fifty boats are seen issuing out of the bay
every morning at sunrise from the various villages. Some of them
carry lug sails, and others are of a triangular shape, &c., &c., and
some have two masts and others three; the largest mast being
stepped in the centre, the next being equi-distant between that and
the smallest one, which is stepped as near to the bows as possible;
the sail on the middle mast is less than one half the size of the
mainmast, and the forward one about half the size of the second.
They are built very sharp forward; the bottom is of basket-work,
very closely woven, and stretched on a frame, and dammer or pitch
is used freely both within and without; the upper works are of wood,
and oil is frequently applied to the bottom. There are a few built
entirely of wood and very little iron, being generally tree-nailed on to
the timbers. The sails are of matting, neatly woven, and generally
well cut in a seamanlike manner. The cables are of cocoa-nut fibres,
and the anchors of a species of very heavy wood. Chunam is used
on the vessels, having wooden bottoms; and the upper works are
blacked with a substance resembling lacquer. The largest class may
carry forty or fifty tons.
Trees of a large growth are very scarce, being cut away to the tops
of the highest hills; they are therefore obliged to resort further
inland for ship-timber; a few planks of forty feet in length and about
four inches in thickness, of a very hard wood, were seen in the ship-
yards, sawed out quite roughly. Temples or houses for religious
worship and priests, there are none; they are said to be prone to
superstitious rites—this assertion has been fully confirmed in many
instances.
In passing along between the village of Vunglam and the beach, I
saw a shed erected, having within it some characters written on a
board resembling the Chinese, but being blended so much together,
they could not be understood; the picture of a frightful object was
also there. A Chinese, who was with us, said it was placed there to
guard against evil spirits, which greatly infested that place. In
another part of the village was erected a similar shed, under which
was a board, on which was inscribed in Chinese characters, only the
word God, it therefore reminded me at once of what St. Paul found
written on an altar at Athens, “To the unknown God.” I suppose
those more refined barbarians and these poor Cochin-Chinese, are
alike ignorant of Him who made and governs all things. Traversing
the beach near Vung-chow, we saw a small cell erected on posts, in
the middle of a grove of trees; looking into it, we found two chalk-
fish painted green, suspended from the roof, and some pots
containing half-burnt joss-sticks. When they wish for success in
fishing, offerings are made to the presiding Deity. Great quantities of
sea-shells were scattered about the place, and fires were evidently
frequently made; thus they present the essence of their feasts only
to the Neptunian Deity, while the pious devotee devours the
substance. In another similar place about four miles from thence, we
found another cell or box erected on posts, but it was more neatly
constructed—in it were two paintings in water colours, evidently
Chinese, each having one large and two small female figures; before
them were half-burnt incense rods and on one side a horse’s head
wrapped in a cloth, which, on opening, we found filled with
maggots: a great number of small green glazed pots were scattered
about.
Tigers abound throughout the country: a few nights since one came
into the village of Vunglam, and carried off into the jungle a good-
sized pig. The woods abound with wild hogs, goats, deer, peacocks,
&c., &c., and the wild elephant is also abundant in the forests. About
two miles from hence is a large barrack, containing a number of
soldiers: the only arm I have yet seen them to possess is a very long
spear, having a small flag or tassel attached to it. I was introduced
to an old man, the commander of two thousand, the other day;
himself and attendants were on horses of a small size, or rather
ponies; they sat on saddles of a peculiar construction, the hinder
part being the lowest; the saddle-cloth being fancifully painted, a
rope used instead of a bit and bridle, and a string of small
ornamented bells placed around the neck: the commander was
dressed in a long robe of blue satin, and wore a black crape turban.
He endeavoured to show every civility by dismounting and walking.
It has been heretofore stated, that, after repeated
requests, we returned the ceremonious calls of two MANDARINS’
HOUSE.
of the mandarins. On approaching the house,
towards the outer gate, we found twelve long spears, bearing small
flags, placed perpendicularly in the ground, in two lines. A wattled
fence separated the dwelling from the beach: in passing through the
outward entrance, we found a short neat avenue, of the graceful
areca-palm, intertwined with the piper-betel leaf. We then passed
through the inner entrance to the court-yard, which was in neat
order. The mandarins received us with much politeness: a temporary
arbour had been erected, and a table spread, having on it rice-wine,
cakes, sweetmeats, fruits—tea being also served. At each end of the
arbour, were suspended, from the roof, two elegantly embroidered
cloths, having silk tassels and worked lappels: Chinese characters
were wrought on them, the purport of which could not be
ascertained, as they were so much blended together. Two brass
tripods, for burning incense, were placed on the table, ornamented
with a lion couchant, from the mouth of which and the open-work
cover, issued the grateful perfume of the kinnam or calembac, which
was kept well replenished. Paper cigars, pipes, and areca, completed
the regale. The house was of brick, with a neat tiled roof. Flowers, in
pots, were neatly arranged around the court-yard.
Many of the natives stood looking on, and behaved with perfect
propriety. The mandarin, or chief of the village of Vung-lam, who
paid us the first visit on our arrival, was in attendance, standing at
my left hand, and served us, in common with the interpreters. The
mandarins were dressed in their robes of ceremony. Three houses
occupied as many sides of the court-yard. The mandarins and
guards attended us to our boats.
When the discussion was going on relative to the letter to the
minister, which occupied many hours, they finally approved of every
sentence, and every word, except “friendly,” which they thought was
rather too familiar a word to be used between nations; and therefore
they proposed substituting the word “neighbourly,” which would
read, “neighbourly intercourse.” Seeing that I was rather amused at
the proposed alteration, they were desirous of knowing the cause.
Being told, that, as we lived some twenty thousand miles apart, we
could not hold a very neighbourly intercourse, they were much
amused by the gross blunder committed by their ignorance, and
replied, it was very true, and therefore they would be satisfied with
the word friendly, as proposed by me. They were not aware,
however, of the distance between the two countries, neither did they
know the situation of North America, but supposed it to be in
Europe, as we afterward ascertained.
When they take leave, they always place our right hand between
theirs, bow their heads very slowly, and as low down as possible.
The government of Cochin-China is thoroughly despotic, being
framed in close imitation of that of China. The sovereign, who, till
lately, bore the title of king, and who still pays a nominal tribute to
China under that title, assumes, among his own subjects, and with
all foreign countries, except China, the Chinese title of hwang-te, (or
emperor,) with the peculiar attribute, “sacred,” “divine,” &c.,
commonly used by the court of Peking. The name, or epithet, by
which the present monarch is designated, (which name was taken
by the monarch himself, at his accession to the throne,) is ming-
ming; it signifies, “emperor appointed by the brilliant decree of
heaven.”
According to the account of the deputies, who visited the ship at
Vung-lam, the administration is also formed in imitation of the
Chinese—consisting of a council of four principal, and two secondary
ministers. The chief of these, (whom Mr. Crawford, the British envoy,
calls the minister of elephants, or of strangers,) was said to be the
minister of commerce, navigation, &c.
The provincial government is also formed in imitation of the Chinese.
Two or more provinces are governed by a toung-tuh, (tsong-dok,) or
governor; under whom, the principal officers, in each province, are
two, viz.: a pooching-sze, (bo-chang-sze,) or treasurer and land-
officer: and an anchasze, or judge. Subordinate to these, are
magistrates, called che-foos, che-keens, &c., presiding over the
districts into which each province is divided. In Cochin-China, as in
China, there are nine grades of rank, each of which is divided into a
principal and secondary class. Every officer, employed in the
government, is of one of these grades: thus, the ministers of the
council are of the first grade, principal class; and the governors of
provinces, are of the first grade, secondary class.
This is all the information respecting the government of Cochin-
China, that could be obtained from the natives.
CHAPTER XVI.
PASSAGE FROM COCHIN-CHINA TO THE GULF OF SIAM—
ARRIVAL AT THE MOUTH OF THE RIVER MENAM—
PACKNAM—PROCESSION TO THE GOVERNMENT-HOUSE—
RECEPTION—GOVERNOR—SIAMESE TEMPLES—
INTERVIEW WITH THE SIAMESE FOREIGN MINISTER—
PRIMA DONNA—FEATS OF STRENGTH—SIAMESE
FEMALES—FIRE AT BANG-KOK—WHITE ELEPHANTS—
EMBALMING—SHAVING-HEAD CEREMONY AND FEAST—
FOX-BATS.
We weighed anchor on the eighth of February, for the gulf of Siam;
light winds and calms detained us nearly two days, within sight of
the bay, in which lies Vunglam, &c., &c. We kept near to the coast,
and found it bold and free from dangers; the land was hilly and
frequently broken into mountains, more particularly between that
bold promontory, called Cape Varela, and Cape Padaran. We passed
the latter within three miles; from thence the land gradually
dwindled into a gently undulating country, and then into low land.
We finally lost sight of it off the numerous mouths of the great river,
Kamboja. On the same afternoon, being the twelfth, we passed
Padaran, and saw Pulo Cica de Terre and Lagan point. At meridian,
on the following day, Pulo Condore was in sight, and the islands to
the westward, called the Brothers. At daylight, the next morning, we
beheld Pulo Ubi, or Yam island, which lies to the southward of cape
Camboja. On the fourteenth, the islands and islets called Pulo
Panjang, and ascertained their correct position to be in latitude 9°
north, by a meridian observation, and by the chronometers, in 104°
32′, east longitude. At daylight, on the following morning, we found
ourselves in the midst of a group of islands, lying so peacefully amid
the glassy surface of the gulf, that Dana’s beautiful description of
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!

ebookname.com

You might also like