Ffirs.indd Ii 2/11/09 9:12:06 AM

3y ago
20 Views
2 Downloads
3.44 MB
583 Pages
Last View : 1d ago
Last Download : 3m ago
Upload by : Kelvin Chao
Transcription

SCJPSun Certified Programmerfor Java Platform, SE6 Study Guide

SCJPSun Certified Programmerfor Java Platform, SE6 Study GuideRichard F. Raposa

Disclaimer: This eBook does not include ancillary mediathat was packaged with the printed version of the book.Acquisitions Editor: Jeff KellumDevelopment Editor: Jennifer LelandTechnical Editor: James NuzziProduction Editor: Christine O’ConnorCopy Editor: Elizabeth WelchProduction Manager: Tim TateVice President and Executive Group Publisher: Richard SwadleyVice President and Publisher: Neil EddeMedia Project Manager 1: Laura Moss-HollisterMedia Associate Producer: Shawn PatrickMedia Quality Assurance: Angie DennyBook Designer: Judy Fung, Bill GibsonProofreader: Nancy BellIndexer: Robert SwansonProject Coordinator, Cover: Lynsey StanfordCover Designer: Ryan SneedCopyright 2009 by Wiley Publishing, Inc., Indianapolis, IndianaPublished simultaneously in CanadaISBN: 978-0-470-41797-3No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or byany means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted underSections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of thePublisher, 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 Publisherfor permission should be addressed to the Permission Department, John Wiley & Sons, Inc., 111 River Street,Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warrantieswith 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 particular purpose. No warranty may be created orextended by sales or promotional materials. The advice and strategies contained herein may not be suitable forevery 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 competentprofessional person should be sought. Neither the publisher nor the author shall be liable for damages arisingherefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potentialsource of further information does not mean that the author or the publisher endorses the information theorganization or Web site may provide or recommendations it may make. Further, readers should be aware thatInternet Web sites listed in this work may have changed or disappeared between when this work was written andwhen it is read.For general information on our other products and services or to obtain technical support, please contact ourCustomer Care Department within the U.S. at (877) 762-2974, outside the U.S. at (317) 572-3993 or fax (317)572-4002.Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not beavailable in electronic books.Library of Congress Cataloging-in-Publication DataRaposa, Richard F.SCJP Sun certified programmer for Java platform, SE6, study guide / Richard F. Raposa. — 1st ed.p. cm.ISBN 978-0-470-41797-3 (paper/cd-rom)1. Electronic data processing personnel — Certification. 2. Operating systems (Computers) —Examinations — Study guides. 3. Java (Computer program language) — Examinations — Study guides.I. Title.QA76.3.R357 2009005.13'3—dc222008054906TRADEMARKS: Wiley, the Wiley logo, and the Sybex logo are trademarks or registered trademarks of JohnWiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used withoutwritten permission. Java is a registered trademark of Sun Microsystems, Inc. All other trademarks are theproperty of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendormentioned in this book.10 9 8 7 6 5 4 3 2 1

Dear Reader,Thank you for choosing SCJP: Sun Certified Programmer for Java Platform, SE6 StudyGuide. This book is part of a family of premium-quality Sybex books, all of which arewritten by outstanding authors who combine practical experience with a gift for teaching.Sybex was founded in 1976. More than thirty years later, we’re still committed toproducing consistently exceptional books. With each of our titles we’re working hard toset a new standard for the industry. From the paper we print on, to the authors we workwith, our goal is to bring you the best books available.I hope you see all that reflected in these pages. I’d be very interested to hear your commentsand get your feedback on how we’re doing. Feel free to let me know what you thinkabout this or any other Sybex book by sending me an email at nedde@wiley.com, or if youthink you’ve found a technical error in this book, please visit http://sybex.custhelp.com.Customer feedback is critical to our efforts at Sybex.Best regards,Neil EddeVice President and PublisherSybex, an Imprint of Wiley

To Susan, Megan, Ryan, Katelyn, Emma and Sara.

AcknowledgmentsA lot of time and energy goes into a book like this, and my wife and kids will be the fi rstones to attest to that fact! I owe them many thanks for their patience and understandingduring the months that went into this project.I also want to thank Jennifer Leland, the Developmental Editor, for putting up withmy complete inability to learn when to use the appropriate styles. Everyone who readsthis book owes James Nuzzi a big thank you for his meticulous job as Technical Editor.The text and sample questions involve a lot of code, and James did an amazing job fi ndingerrors and typos. Thanks also to Jeff Kellum, Pete Gaughan, Christine O’Connor, andeveryone at John Wiley & Sons, Inc., who helped make this book a reality.And last but not least, I want to thank all of you who are reading this book in hopes oflearning Java and passing the SCJP Exam. I hope all of you fi nd this book informative andindispensable wherever your Java adventures take you. Good luck!About the AuthorRich Raposa runs a Java training fi rm, JLicense, Inc., based out of Rapid City, SD. He isa Sun Certified Java Programmer as well as a Sun Certified Java Instructor, and has spentthe past 11 years delivering Java training courses to businesses across the United States. Hehas written dozens of Java courses ranging from introductory Java to advanced topics likeEnterprise JavaBeans, Java Web development, and Java Web Services. He enjoys playingpoker and playing the guitar (though he does not claim to be good at either).

Contents at a GlanceIntroductionxviiAssessment TestxxivChapter 1FundamentalsChapter 2Declarations, Initialization, and ScopingChapter 3Flow Control187Chapter 4API Contents269Chapter 5Concurrency341Chapter 6Object-Oriented Concepts381Chapter 7Collections and Generics425177Appendix491Glossary495Index507

ContentsIntroductionxviiAssessment TestxxivChapterChapter12Fundamentals1Writing Java ClassesPackagesThe package KeywordThe import KeywordPackage Directory StructureThe CLASSPATH Environment VariableRunning Java ApplicationsThe -classpath FlagJAR FilesCommand-Line ArgumentsReference vs. Primitive TypesPrimitive TypesReference TypesGarbage CollectionThe System.gc MethodThe finalize MethodCall by ValueJava OperatorsThe Assignment OperatorsThe Arithmetic OperatorsThe Relational OperatorsThe instanceof OperatorThe Bitwise and Logical OperatorsThe Conditional OperatorThe Equality OperatorsEquality of ObjectsSummaryExam EssentialsReview QuestionsAnswers to Review 55565861616373Declarations, Initialization, and Scoping77Declaring VariablesScopingInstance VariablesClass VariablesLocal Variables7880808386

xiiContentsDeclaring ArraysArray ReferencesArray ObjectsUsing ArraysMultidimensional ArraysArray InitializersDeclaring ClassesThe Instantiation ProcessConstructorsThe Default ConstructorUsing this in ConstructorsUsing super in ConstructorsInstance InitializersStatic InitializersDeclaring MethodsMethod DeclarationsJavaBeans Naming ConventionInstance MethodsStatic MethodsVariable-Length ArgumentsMethod OverloadingMethod OverridingCovariant Return TypesMethod HidingFinal MethodsDeclaring Abstract ClassesAbstract MethodsDeclaring InterfacesImplementing InterfacesExtending InterfacesDeclaring EnumerationsUsing enumsDeclaring enum MethodsDeclaring enum ConstructorsDeclaring Nested ClassesMember Inner ClassesLocal Inner ClassesAnonymous Inner ClassesStatic Nested ClassesSummaryExam EssentialsReview QuestionsAnswers to Review 0151152152158159162165166168183

ContentsChapterChapter34xiiiFlow Control187Overview of Flow ControlThe if StatementThe switch StatementSwitching on an EnumFinal case ValuesThe for StatementThe Basic for StatementThe Enhanced for StatementThe while StatementThe do StatementThe break StatementThe continue StatementOverview of AssertionsThe assert StatementEnabling AssertionsUsing AssertionsOverview of ExceptionsThe try StatementMultiple catch ClausesThe Handle or Declare RuleThe finally BlockJava API Exceptions and oClassDefFoundErrorSummaryExam EssentialsReview QuestionsAnswers to Review 48249249250251265API ContentsThe Primitive Wrapper ClassesAutoboxing and UnboxingStringsThe String ClassThe StringBuilder and StringBuffer Classes269270272274275278

xivChapterContents5Input and OutputStreams vs. Readers and WritersLow-Level vs. High-Level StreamsFile Input and OutputThe FileReader and FileWriter ClassesThe File ClassThe FileInputStream and FileOutputStream ClassesThe DataInputStream and DataOutputStream ClassesThe PrintWriter ClassThe format and printf MethodsThe Console ClassObject SerializationThe Serializable InterfaceThe ObjectOutputStream ClassThe ObjectInputStream ClassFormatting and Parsing DataFormat and Parse Numbers and CurrencyFormat and Parse DatesRegular ExpressionsThe Pattern and Matcher ClassesThe String.split MethodThe Scanner ClassSummaryExam EssentialsReview QuestionsAnswers to Review 1Overview of ThreadsWriting a ThreadImplementing the Runnable InterfaceExtending the Thread ClassThread StatesNew ThreadsRunnable ThreadsBlocked ThreadsWaiting and Timed-Waiting ThreadsTerminated ThreadsThread SynchronizationThe Monitor LockThe wait, notify, and notifyAll 363368

ContentsExam EssentialsReview QuestionsAnswers to Review d Concepts381Encapsulation, Coupling, and CohesionTight EncapsulationLoose CouplingHigh CohesionOO Design RelationshipsThe “is-a” RelationshipThe “has-a” RelationshipModifiers and InheritanceThe Access ModifiersThe abstract ModifierThe final ModifierPolymorphismUnderstanding PolymorphismCasting Polymorphic ReferencesSummaryExam EssentialsReview QuestionsAnswers to Review 5409410412423Collections and GenericsOverview of CollectionsThe Collections InterfacesThe Comparable InterfaceThe Difference Between and equalsUsing GenericsLimitations of Nongeneric CollectionsListsSetsMapsGeneric Types and MethodsGeneric ClassesGeneric InterfacesGeneric MethodsBounded Generic TypesGeneric WildcardsWorking with ListsSorting ListsSearching 458461461467

ContentsxviWorking with ArraysSorting ArraysSearching ArraysSummaryExam EssentialsReview QuestionsAnswers to Review 95Index507

IntroductionThe Sun Certified Programmer for Java Platform, Standard Edition 6 (Java SE 6)certification exam is for programmers experienced using the Java programming language.Achieving this certification provides clear evidence that a programmer understandsthe basic syntax and structure of the Java programming language and can create Javatechnology applications that run on server and desktop systems using Java SE 6.How Do You Become SCJP Certified?Pass the exam! You need to achieve a 65% (47 of 72 questions) or higher to pass theSCJP exam, and once you pass it, then you are a Sun Certified Java Programmer for theparticular version of the exam that you passed. The latest SCJP exam is for JavaSE 6.0,which is the exam this book covers.The SCJP ExamThe SCJP exam consists of 72 questions and you are given three and one -half hours tocomplete it. You take the exam at an Authorized Worldwide Prometric Testing Center. Youtake the SCJP exam on a computer using the mouse to display questions and answers. Thequestions appear on the screen one at a time, and you can navigate forward and backwardat any time to view any question or modify your answer. Longer questions do not fit onthe screen and require you to click on the scroll bar. You answer a question by clicking theappropriate answer.You are not allowed to bring anything into the exam room, including a pen and paper.Most testing centers do not allow scratch paper and instead provide a small white boardand a dry- erase marker. Most testing centers have security cameras as well, and it is likelythat other people will be in the exam room taking different exams.Types of Exam QuestionsThe SCJP exam consists of the following types of questions:Multiple choice A majority of the questions are multiple choice. The number of answersgiven varies for each question, but typically you are given five to six answers. If a questionhas more than one answer, the question specifically states exactly how many correctanswers there are for the question. For example, a question might have five answers andstate that two of them are correct. The exam software only allows you to select twoanswers for that particular question.Drag and drop About 10 to 15 of the exam questions involve fi lling in the blanks of aquestion. The answers are given in a list or box on the screen, and you drag and drop ananswer into the blank. Some of the drag-and-drop questions have the exact same number ofblanks as answers, and some of them have more answers than blanks.

xviiiIntroductionWhen you navigate from one question to the next during the exam, the multiple choicequestions simply appear on the screen. If the question is drag and drop, you do not see theactual question initially when you navigate to the question. Instead, you click a button thatdisplays the question and answers, and when you have fi nished answering the question, youclose the display and return to the navigation screen, where you can continue to the nextquestion.Tips for Taking the SCJP ExamThe most important tip I can give you for passing the exam is to practice answeringquestions. Study all of the sample questions that appear at the end of each chapter, as wellas the bonus exam questions and the Assessment Test later in this Introduction. I tried towrite questions that were indicative of the questions on the exam as far as knowledge anddifficulty level. Between this book and its accompanying CD, you have over 400 questionsto prepare you for the exam. Try to answer the questions to the best of your ability without“cheating” and looking back through the chapters, and practice a group of questions ata time without checking the answers right away. This will help simulate the taking of theactual exam.Some questions on the SCJP exam are easier than others and require less time, whileother questions might take several minutes to answer. You should average about 30questions an hour. This pace will leave you with an hour or so at the end to go back andreview your answers. If you start running out of time, make sure you at least answer everyquestion on the exam, even if you have to guess. There is no penalty for a wrong answer, sodo not leave a question blank.Do not underestimate the exam objectives or try to guess what will or won’t be on theexam. Because the number of objectives outnumbers the exam questions, not every examobjective has a corresponding exam question. Therefore, your best plan of action is tounderstand every exam objective. If you fi nd yourself struggling with a particular topic,then write some code! Writing code and making mistakes along the way are the best way tounderstand any programming topic.Also, expect the newer concepts of the Java language to appear on the exam. Forexample, I can guarantee that you will see a question on generics and enumerations. Theseare newer concepts in the language and they separate the new SCJP exam from the previousversions.One unpleasant issue that I ran into with the drag-and-drop questions is that you cannotreview the answer after you move on to the next question. If you go back to a drag-anddrop question and click the button to display the question and answers, your answer islost and you have to re-answer the question in its entirety. Some of these drag-and-dropquestions took some time to determine the answer, and I found that I did not alwaysremember what my initial answer was, so I had to rethink the question all over again! Ifyou are getting close to the end of your allotted time and you are trying to review all youranswers, you might want to be judicious about whether to rework through a drag-and-dropquestion.

IntroductionxixIf you have to retake the exam, keep in mind that there are several versions of the examand the questions will be different each time you take the exam.Exam RegistrationThe price of the exam in the United State is 300 and you can purchase a voucher onlineat -065.xml. This URL is forthe Java SE 6.0 exam. If you are taking a different version of the exam, you can fi nd thecorresponding registration page at http://www.sun.com/training/catalog/courses/.If you reside outside of the United States, visit http://www.sun.com/training/worldtraining.html to purchase a voucher for the exam.After you purchase your exam voucher, you have up to one year from the date ofpurchase to use it. Each voucher is valid for one exam and can only be used at anAuthorized Prometric Testing Center in the country for which it was purchased. Please beaware that exam vouchers are nonrefundable for any reason.An exam voucher contains a unique number that you provide to Prometric whenscheduling the exam. To schedule the exam, contact Prometric at (800) 795-3926 (UnitedStates and Canada). You can also visit the Prometric Web site at http://www.2test.com.When you arrive at the testing facility to take the exam, you need to bring two formsof identification. One must be a current, government-issued photo ID, such as a validpassport or driver’s license, with a photo that looks like you. Be sure the names on yourID are displayed the same way it is displayed on your exam record, and that both IDs havea current signature that looks like yours. Examples of other pieces of ID are credit cardsand check cashing cards. The test will not be delivered without the appropriate form ofidentification. Prometric Test Center Administrators have the right to refuse seating you forthe exam if they are unable to properly identify you.Do not bring notes, pens, pencils, paper, large purses, or backpacks to the test center.Supplies needed for taking the exam are provided by the testing center. Prometricrecommends that you arrive at the testing center at lea

ffirs.indd ii 2/11/09 9:12:06 AM. SCJP Sun Certified Programmer . ffirs.indd vii 2/11/09 9:12:08 AM. ffirs.indd viii 2/11/09 9:12:08 AM. Contents at a Glance Introduction xvii Assessment Test xxiv Chapter 1 Fundamentals 1 Chapter 2 Declarations, Initialization, and Scoping 77

Related Documents:

FFIRS.indd ii 6/2/11 12:34:44 PM. Corporate Governance FFIRS.indd i 6/2/11 12:34:44 PM. FFIRS.indd ii 6/2/11 12:34:44 PM. Corporate Governance Fifth Edition Robert A. G. Monks and Nell Minow FFIRS.indd iii 6/2/11 12:34:44 PM. This edition fi rst published in 2011

ffirs.indd i 11/12/12 12:25 PM. ffirs.indd ii 11/12/12 12:25 PM. LPIC-1 Linux Professional Institute Certification Study Guide Third Edition Roderick W. Smith John Wiley & Sons, Inc. ffirs.indd iii 11/12/12 12:25 PM. Senior Acquisitions Editor: Jeff Kellum Development Editor: Alexa Murphy

ffirs.indd i 11/12/12 12:25 PM. ffirs.indd ii 11/12/12 12:25 PM. LPIC-1 Linux Professional Institute Certification Study Guide Third Edition Roderick W. Smith John Wiley & Sons, Inc. ffirs.indd iii 11/12/12 12:25 PM. Senior Acquisitions Editor: Jeff Kellum Development Editor: Alexa Murphy

ffirs.indd ii 8/9/12 2:02 PM. . ffirs.indd xi 8/9/12 2:02 PM. ffirs.indd xii 8/9/12 2:02 PM. . Understanding the Structure of perldoc 11 Getting Started with perldoc 11 Using Tutorials and FAQs 12 Using the perldoc -f function 14 Using a Terminal Window 14 Using the Command Line 15 Creating a Work Directory 16

ffirs.indd ii 7/24/09 8:52:41 PM. ffirs.indd vi 7/24/09 8:52:44 PM. vii Contents . Chapter 11 Mr. Outside versus Mr. Inside versus the SEC 145 ftoc.indd vii 7/24/09 8:52:58 PM. viii CONTENTS Chapter 12 Life inside the Madoff Piggy Bank, Flashing the Plastic, and Losing the Farm 159 Chapter 13 A Family (and Sometimes an Offi ce) .

ffirs.indd ii 29/12/11 2:41 PM. Pass port to Profi ts fffirs.indd ifirs.indd i 119/01/12 2:38 PM9/01/12 2:38 PM. fffirs.indd iifirs.indd ii 119/01/12 2:38 PM9/01/12 2:38 PM. Passport to Profi ts Why the Next Investment Windfalls Will Be Found Abroad and How to Grab Your Share Revised and Updated .

ffirs.indd ii 1/6/11 10:36:33 AM. For my wife— a heroic woman whose patience and wisdom are without equal. ffirs.indd iii 1/6/11 10:36:34 AM. ffirs.indd iv 1/6/11 10:36:34 AM. v Contents Preface vii Experience Level Rating System (EL) ix Chapter 1 The Big Business of Penny Stocks 1

from The Adventures of Tom Sawyer MARK TWAIN In this famous selection from The Adventures of Tom Sawyer (1876), written by Mark Twain (born Samuel Langhorne Clemens, 1835–1910), Tom, burdened with the chore to whitewash his Aunt Polly’s fence as punishment for his having played hooky from school, comes up with an ingenious way to get out of his work: He convinces his friends that it’s .