1. Trang chủ
  2. » Công Nghệ Thông Tin

Sybex java foundations sep 2004 ISBN 0782143733 pdf

363 81 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 363
Dung lượng 5,76 MB

Nội dung

Java FoundationsJava Foundations Todd Greanier San Francisco ◆ London Associate Publisher: Neil Edde Acquisitions and Developmental Editor: Maureen Adams Production Editor: Mae Lum Technical Editor: Jerome Goodman Copyeditor: Pat Coleman Compositor: Maureen Forys, Happenstance Type-O-Rama Graphic Illustrator: Jeff Wilson, Happenstance Type-O-Rama Proofreaders: Laurie O’Connell, Nancy Riddiough Indexer: Ted Laux Book Designer: Judy Fung Cover Designer: Ingalls + Associates Cover Illustrator/Photographer: Jerry Driendl, Taxi Copyright © 2004 SYBEX Inc., 1151 Marina Village Parkway, Alameda, CA 94501 World rights reserved No part of this publication may be stored in a retrieval system, transmitted, or reproduced in any way, including but not limited to photocopy, photograph, magnetic, or other record, without the prior agreement and written permission of the publisher An earlier version of this book was published under the title Java Certification JumpStart © 2003 SYBEX Inc Library of Congress Card Number: 2004109314 ISBN: 0-7821-4373-3 SYBEX and the SYBEX logo are either registered trademarks or trademarks of SYBEX Inc in the United States and/or other countries Screen reproductions produced with FullShot 99 FullShot 99 © 1991-1999 Inbit Incorporated All rights reserved FullShot is a trademark of Inbit Incorporated TRADEMARKS: SYBEX has attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following the capitalization style used by the manufacturer The author and publisher have made their best efforts to prepare this book, and the content is based upon final release software whenever possible Portions of the manuscript may be based upon pre-release versions supplied by software manufacturer(s) The author and the publisher make no representation or warranties of any kind with regard to the completeness or accuracy of the contents herein and accept no liability of any kind including but not limited to performance, merchantability, fitness for any particular purpose, or any losses or damages of any kind caused or alleged to be caused directly or indirectly from this book Manufactured in the United States of America 10 For my son, Maximilian Arthur Acknowledgments Without my wife, Stacey Ann, this book could never have been written Her patience and support are seemingly endless, and I am eternally grateful to her As an author, I have to make certain sacrifices, but as a wife, she has to make those same sacrifices and then some Sore fingers and tired eyes don’t seem such a bother when she walks into the room Other friends also deserve a bit of thanks, including Don Holt, Bill Mulligan, Kelby and Beth Zorgdrager, Sean and Heather Lahman, Randy Bonferraro, Cara Lynch, Paul Eberhardt, Lee and Judy Bruder, Kwai Chang Caine, and Dan Millman Of course, I also want to thank several of the fine folks at Sybex who helped get this book into your hands Maureen Adams first brought the idea to me and helped me get the ball rolling Pat Coleman and Mae Lum helped me to turn the chaos of my thoughts into coherent sentences and made the entire writing process extremely pleasant Thanks also to Maureen Forys of Happenstance Type-O-Rama for the book layout and to Ted Laux for the index Contents Introduction Chapter xiii The History of Java Where Java Technology Came From The Green Project Enter the Web The Features of Java Technology Java Is Simple Java Is Object Oriented Java Is Interpreted Java Is Portable Java Is Robust Java Is Secure Java Is Multithreaded Java Is High Performance Java Saves Time and Money Java Solves Important Problems 10 How Java Compares with Other Languages 10 How to Download and Install Java 11 Downloading the J2SE Software 12 Terms to Know 20 Review Questions 21 Chapter Java Fundamentals 23 Creating a Java Program The HelloWorld Program Writing the HelloWorld Source Code Compiling the HelloWorld Source Code Executing the HelloWorld Program Examining the Source Code Using Comments Using White Space Defining the Class Defining the Method Wrapping Up the HelloWorld Program Working with Arguments in the main() Method The Basic Java Data Types Literal Values The Integer Types 24 24 25 26 27 28 29 31 31 34 38 39 41 42 43 viii Contents Chapter Chapter The Floating Point Types The Character Type The Boolean Type Using the Primitive Types The String Class Primitive Values versus Reference Values Terms to Know Review Questions 45 45 46 46 47 47 51 52 Keywords and Operators 53 Creating Valid Names in Java The Keyword List The Primitive Type Keywords The Flow Control Keywords Modification Keywords Class-Related Keywords Object-Related Keywords Wrapping Up the Keywords The Java Operators The Arithmetic Operators The Assignment Operators The Relational Operators The Conditional Operators Terms to Know Review Questions 54 55 56 56 57 60 69 74 74 75 80 81 83 86 87 Flow Control 89 Application Scope 90 The if Statement 90 Adding the else Statement 92 Testing the Array of Arguments 94 The switch and case Statements 97 The default Statement 100 Deciding between if/else and switch/case 100 Processing a Range of Values 102 The Ternary Operator 104 The for Loop 105 Multiple Increment Steps 107 Beware the Infinite Loop 109 The while Loop 110 Comparing for and while Loops 111 The Statement 113 Contents Chapter Chapter The Branching Statements The break Statement The continue Statement The return Statement Terms to Know Review Questions 114 114 117 121 123 124 Arrays 125 Understanding Arrays Declaring Arrays Creating Arrays Getting the Length of an Array Populating an Array Using Array Initializers An Array Initializer Variation Accessing Array Elements Multidimensional Arrays Two-Dimensional Array Initializers Nonrectangular Arrays The java.util.Arrays Class Filling an Array Sorting an Array Searching an Array Terms to Know Review Questions 126 128 129 130 132 133 134 135 137 140 141 142 142 143 144 145 146 Introduction to Object-Oriented Programming 147 The Object-Oriented Paradigm Real-World Objects Defining a Class Instantiating and Using Objects A Closer Look at a Lamp Object Sharing a Reference Object Messaging: Adding a Lightbulb Passing by Value Passing by Reference The this Keyword Bypassing Local Variables Using this Passing a Reference Using this Static Methods Have No this Reference Constructors Multiple Constructors Constructor Chaining 148 149 150 152 153 155 156 160 162 165 166 168 169 170 173 177 ix x Contents Terms to Know 179 Review Questions 180 Chapter Chapter Chapter Advanced Object-Oriented Programming 181 Claiming Your Inheritance Using the extends Keyword The Rules of Inheritance Reference Types versus Runtime Types Expanding the Subclasses The Class Hierarchy The Reference Type Rule for Methods The instanceof Operator and Object Casting Object Casting Introducing Polymorphism Method Overloading Method Overriding Abstract Classes and Methods Interfaces Terms to Know Review Questions 182 184 185 187 190 193 195 196 197 199 199 201 212 215 219 220 Exception Handling 221 The Method Call Stack Exception Noted The Exception Hierarchy Handling Those Exceptions Using try and catch Using a finally Clause Creating Your Own Exception Type Throwing Exceptions Using the throws Keyword The throw Keyword Terms to Know Review Questions 222 223 224 226 227 232 235 237 238 240 246 247 Common Java API Classes 249 The java.lang.String Class Common String Methods The java.lang.StringBuffer Class The java.lang.Math Class Calculating a Random Number The Wrapper Classes Creating Wrapper Objects 250 251 260 264 266 270 271 decimal points (.) in floating types – Environment Variables window boolean, 46 casting, 78 automatic, 80 downcasting, 79 instanceof operator for, 197–199 upcasting, 78–79 character, 45 floating point, 45 integer, 43–45 literal values, 42–43 primitive types, 42 keywords for, 56 vs reference values, 47–51 testing equality of, 82 working with, 46–47 size of, 42 String class, 47 decimal points (.) in floating types, 45 declarations array, 128–129 in strongly typed languages, 6–7 declare or handle rule, 238–239 decrement operator, 77 default array element values, 129, 132, 135–136 default constructors, 209–210 default modifier, 186 default packages, 64 default statement keyword for, 57 in switch/case, 100 defining classes HelloWorld, 31–34 Lamp, 150–152 methods, 34–38 delegation defined, 320 in invoking methods, 159 delete method, 263 derived classes, 58 device drivers, dim method in HeatLamp, 218 in LightSource, 215 in MyLamp2, 216–217 directories for installation, 14 division, 75 statement, 57, 113 documentation comments, 30–31 DomainRipper class, 258–260 dot-notation defined, 320 for methods, 38 Double class parsing methods for, 275 purpose of, 271 double data type keyword for, 56 size of, 42, 45 upcasting, 79 double quotes (") for arguments, 119 for strings, 49 doubleIt method, 168–169 Doubler class, 168 downcasting, 79 downloading java, 11–13 drivers, E Echo class, 223 Edit System Variable dialog box, 18 editors, 25 elements, array accessing, 135–137 data types for, 126–127 defined, 319 filling, 142–143 initializers for, 133–135 in multidimensional arrays, 137–141 searching for, 144–145 sorting, 143–144 else statement, 57, 92–94 encapsulation benefits of, 150 defined, 320 modifier for, 58 endsWith method, 254–255 EnforcedArg class, 131–132 ensureCapacity method, 288–290 entries method, 304 Entry class, 241–242 environment variables, 16–20 Environment Variables window, 17 333 334 equal signs (=) – floor of numbers equal signs (=) for array elements, 129 for assignment, 80–81 for combination operators, 81 for equality tests, 81–82 for non-equality operator, 83 for relational operator, 82–83 equality operator for, 81–82 of references, 202 of strings, 255–256 equals method in Object, 202–203 in Record, 203–204 in String, 255 for wrapper classes, 273–274 equalsIgnoreCase method, 255 Error class, 225 error objects, 225 errors and error messages compiler, 26–27 defined, 321 exceptions See exception handling printing, 132 event handling, 321 EvenTest class, 92 EvenTest2 class, 93 EvenTest3 class, 94 EvenTest4 class, 96 EvenTestTertiary class, 104 Exception class, 225, 227 exception handling, 7, 221 creating exception types, 235–237 defined, 321 hierarchy in, 224–226 key terms for, 246 messages for, 223–224 method call stacks in, 222–223 review questions in, 247 throwing exceptions, 237 in subclasses, 239–240 throw keyword, 240 throws clauses, 238–240, 326 try/catch blocks, 227–229 finally clauses, 232–235 multiple catch blocks in, 230–232 process flow with, 229–230 exceptions, 321 exclamation points (!) in conditional operator, 85–86 in non-equality operator, 83 exclusive OR operator, 85 executing programs, 24, 27–28 exit method, 96–97 expanding subclasses, 190–193 exponential calculations, 264–265 extends keyword, 60–62, 184–185 extracting substrings, 257–260 F false keyword, 56 false values, 46 features of Java, high performance, in installation, 14 interpreted source code, multithreaded programs, object orientation, 4–5 portability, problem solving, 10 robustness, 6–7 security, 7–8 simplicity, time and money savings, fill method, 142–143 FillArray class, 142–143 filling arrays, 142–143 final classes, 185 final modifier, 59–60 finally clauses, 232–235 first method in ClassWithoutThis, 165 in ClassWithThis, 166 Float class, 99 parsing methods for, 275 purpose of, 271 float data type keyword for, 56 size of, 42, 45 upcasting, 79 floating point data types, 45 floor method, 264–265 floor of numbers, 264–265 flow control – HelloWorld program flow control, 89 break statement, 114–117 continue statement, 117–121 defined, 321 statement, 113 for loops, 105–107 infinite loops from, 109 multiple increment steps in, 107–109 vs while, 111–113 if statement, 90–92 else statement, 92–94 vs switch/case, 100–102 for testing array of arguments, 94–97 key terms for, 123 keywords for, 56–57 return statement, 121–122 review questions for, 124 switch and case statements, 97 default statement, 100 vs if/else, 100–102 ranges of values in, 102–104 ternary operator, 104 while loops, 110–113 for loops, 105–107 infinite loops from, 109 keyword for, 57 multiple increment steps in, 107–109 vs while, 111–113 ForDemo class, 105–106 foreign code, ForTerminationDemo class, 108–109 forward slashes (/) for comments, 30–31 for division, 75 in paths, 66 frameworks collections See collections framework defined, 321 defining, 282 fully qualified names defined, 321 packages in, 64 G garbage collection defined, 321 operation of, 335 get method in Arraylist, 287 in List, 284 in Map, 295, 306 getAcctNum method, 203 getDetails method, 241–242 getFirst method, 241 getLast method, 241 getMessage method in HelloWorldRevisited, 122 in NoSuchEntryException, 235–237 in Throwable, 225, 227, 245 getName method in AbstractMachine, 213 in Machine, 183 in Record, 203 in Robot2, 73 getNumber method in AClass, 155 in Doubler, 168 in Entry, 241 getSum method, 167 getX method, 163 going out of scope, 74 Gosling, James, 2–3 goto reserved word, 55 greater than signs (>) as relational operator, 82–83 Green Project, 2–3 grouping operator, 78 GuessingGame class, 267–270 H HashMap class, 296–298 HashMapDemo class, 296–297 HashSet class, 292–293 HashSetDemo class, 292–293 hasNext method, 299, 301 hasPrevious method, 302, 304 HeatLamp class, 217–219 HeatSource interface, 217 heatUp method in HeatLamp, 218 in HeatSource, 217 in Toaster2, 191–192 HelloWorld.class file, 27–28 HelloWorld program, 24 executing, 27–28 336 HelloWorld2 class – instantiation source code for compiling, 26–27 examining, 28 writing, 25–26 HelloWorld2 class, 39 HelloWorld3 class, 41 HelloWorldRevisited class, 122 hiding information benefits of, 150 modifier for, 58 variables, 186 hierarchies of classes, 193–195 in exception handling, 224–226 high performance in Java, history of Java, 1–3 I I/O classes defined, 321 in java.io, 266–269 if keyword, 57 if statement, 90–92 else statement, 92–94 vs switch/case, 100–102 for testing array of arguments, 94–97 IllegalStateException class, 299 immutable data types arrays, 127 defined, 321 String, 50–51 implements keyword, 63 import keyword, 67–68 importing, 67–68 in variable, 267 increment operator, 76–77 indexes for array elements, 126–127 for multiple arguments, 40 indexOf method in Arraylist, 289–290 in String, 256, 260 in StringBuffer, 261, 263 infinite loops defined, 321 for loops, 109 while loops, 112–113 information hiding benefits of, 150 modifier for, 58 variables, 186 inheritance, 60–61, 182–183 class hierarchy in, 193–195 defined, 321 extends keyword for, 184–185 instanceof operator for, 196–199 multiple, 63, 185 reference type rule for methods, 195 reference types vs runtime types in, 187–190 rules of, 185–187 subclass expansion in, 190–193 initialization expressions defined, 321 in for loops, 105–106 initializers for arrays defined, 319 two-dimensional, 140–141 working with, 133–135 inner classes, 321 input streams defined, 321 purpose of, 267 InputStreamReader class, 267 insert method, 263 installing J2SE on Linux, 18–20 on Windows, 13–18 instance methods, 157 defined, 322 purpose of, 151 instance variables characteristics of, 59 defined, 322 purpose of, 151 InstanceChecker class, 196 instanceof operator, 71, 196–199 instantiation, 32, 152–153 of arrays, 130 defined, 322 Lamp class, 152–153 lazy, 49 in sharing references, 155–156 int data type – java.util.List interface int data type keyword for, 56 size of, 42–43 upcasting, 79 Integer class, 91 parsing methods for, 275 purpose of, 270 integer types, 43–45 interface keyword, 62 interfaces defined, 322 working with, 215–219 interpreted source code, interpreters defined, 322 for HelloWorld, 27–28 purpose of, 24 IntHolder class, 163 IOException class, 269 isDigit method, 277 isEmpty method in Arraylist, 287 in Collection, 283–284 in Map, 295 isLetter method, 277 isLetterOrDigit method, 277 isLit method in ColoredLightBulb, 174 in LightBulb, 157–158, 164 isLowerCase method, 277 isOn method in AbstractMachine, 213 in Machine, 183 isUpperCase method, 277 isWhitespace method, 277 iteration expressions in for loops, 105–106 Iterator interface, 299–301 IteratorDemo class, 300 iterators, 298–299 defined, 322 java.util.Iterator interface, 299–301 java.util.ListIterator interface, 301–304 and maps, 304–306 J J2EE (Java Platform, Enterprise Edition), 11–12 337 J2ME (Java Platform, Micro Edition), 12 J2RE (Java Runtime Environment, Standard Edition), 11 J2SE (Java Platform Standard Edition), 11 downloading, 12–13 installing on Linux, 18–20 on Windows, 13–18 Java API (Java Application Programming Interface), java.awt.event package, 68 java compiler, 65–66 JAVA_HOME environment variable, 19 Java HotSpot Virtual Machine (Java HotSpot VM) defined, 322 for performance, java interpreter, 27–28 java.io package, 266–269 java.lang package, 64 in exception hierarchy, 224–225 importing, 67–68 java.lang.Error class, 225 java.lang.Exception class, 225, 227 java.lang.IllegalStateException class, 299 java.lang.Integer class, 91 java.lang.Math class methods in, 264–266 for random numbers, 266–270 wrapper classes in, 270–278 java.lang.NumberFormatException class, 227–228 java.lang.Object class, 131 in class hierarchy, 194–195 overriding methods in, 202–206 java.lang.RuntimeException class, 226 java.lang.String class, 250–251 methods in, 251–260 package for, 63–64 working with, 47 java.lang.StringBuffer class, 260–264 java.lang.System class, 64–65 java.lang.Throwable class, 225, 227 Java Plug-in, 11 java.util.Arrays class, 142 java.util.Collection interface, 282–284 java.util.HashMap class, 296–298 java.util.HashSet class, 292–293 java.util.Iterator interface, 299–301 java.util.List interface, 284–285 338 java.util.Map interface – literal values java.util.Map interface, 294–295 java.util.Set interface, 291–292 java.util.SortedSet interface, 293 java.util.UnsupportedOperationException class, 284 java.util.Vector class, 288 Java Virtual Machine (JVM), 3, defined, 322 virtual method invocation in, 189, 201 javac compiler, 26 javadoc tool, 30–31 JavaScript language defined, 322 vs Java, 11 JavaServer Web Development Kit (JSWDK), 12 JVM (Java Virtual Machine), 3, defined, 322 virtual method invocation in, 189, 201 K keys, mapping to values, 294 keySet method in HashMap, 297 in Map, 295 keywords class-related, 60 class, 60 extends, 60–62 implements, 63 import, 67–68 interface, 62 package, 63–67 for flow control, 56–57 key terms for, 86 list of, 55–56 for modification, 57–60 for objects, 69 instanceof, 71 new, 69–71 null, 71–72 super, 72 this, 72–74 for primitive types, 56 review questions for, 87 summary, 74 L labels with break, 114–117 with continue, 119–121 defined, 322 Lamp class, 150–154, 184 LampTest class, 152–153, 184–185 LampTest2 class, 187 LampWithBulb class, 158 LampWithBulb2 class, 171–172 LampWithBulb2Test class, 173 LampWithBulb3 class, 175–176 LampWithBulb3Test class, 176 LampWithBulbTest class, 159–160 last-in-first-out (LIFO) stacks, 222 lastIndexOf method in List, 285 in String, 256, 259–260 in StringBuffer, 261 lazy instantiation defined, 322 for memory usage, 49 left braces ({) for class bodies, 33–34 length of arrays, 126–127, 130–132 of strings, 251–252 length method in String, 251–252 in StringBuffer, 261 less than signs (

Ngày đăng: 20/03/2019, 15:00

TỪ KHÓA LIÊN QUAN