SCJP
Sun Certified Programmer
for Java®
Platform, SE6
Study Guide
SCJP
Sun Certified Programmer
for Java®
Platform, SE6
Study Guide
Richard F. Raposa
Acquisitions Editor: Jeff Kellum
Development Editor: Jennifer Leland
Technical Editor: James Nuzzi
Production Editor: Chri...
Dear Reader,
Thank you for choosing SCJP: Sun Certified Programmer for Java Platform, SE6 Study
Guide. This book is part of...
To Susan, Megan, Ryan, Katelyn, Emma and Sara.
Acknowledgments
A lot of time and energy goes into a book like this, and my wife and kids will be the first
ones to attest ...
Contents at a Glance
Introduction xvii
Assessment Test xxiv
Chapter 1 Fundamentals 1
Chapter 2 Declarations, Initializatio...
Contents
Introduction xvii
Assessment Test xxiv
Chapter 1 Fundamentals 1
Writing Java Classes 2
Packages 4
The package Key...
xii Contents
Declaring Arrays 88
Array References 89
Array Objects 90
Using Arrays 91
Multidimensional Arrays 93
Array Ini...
Contents xiii
Chapter 3 Flow Control 187
Overview of Flow Control 188
The if Statement 188
The switch Statement 192
Switch...
xiv Contents
Input and Output 281
Streams vs. Readers and Writers 281
Low-Level vs. High-Level Streams 283
File Input and ...
Contents xv
Exam Essentials 369
Review Questions 370
Answers to Review Questions 378
Chapter 6 Object-Oriented Concepts 38...
xvi Contents
Working with Arrays 470
Sorting Arrays 470
Searching Arrays 473
Summary 475
Exam Essentials 476
Review Questi...
Introduction
The Sun Certified Programmer for Java Platform, Standard Edition 6 (Java SE 6)
certification exam is for progra...
xviii Introduction
When you navigate from one question to the next during the exam, the multiple choice
questions simply a...
Introduction xix
If you have to retake the exam, keep in mind that there are several versions of the exam
and the question...
xx Introduction
What’s in the Book?
What makes a Sybex Study Guide the book of choice for hundreds of thousands of SCJPs?
...
Introduction xxi
for the exam. We have also included the complete contents of the Study Guide in electronic
form. The CD’s...
xxii Introduction
Sybex Flashcards for PCs and Handheld Devices The “flashcard” style of question offers
an effective way t...
Introduction xxiii
2. Study each chapter carefully, making sure that you fully understand the information
and the test obj...
Assessment Test
1. The following code appears in a file named Book.java. What is the result of compiling
this source file?...
what is the result of the following statements?
TV a = new TV(“Philips”, “42PFL5603D”);
TV b = new TV(“Philips”, “42PFL560...
D. Compiler error on line 6
E. Compiler error on line 7
5. What is the result of the following program?
1. public class Ve...
7. Given the following Football class definition:
1. package my.sports;
2.
3. public class Football {
4. public static fin...
9. What is the result of the following code?
3. Boolean m = true;
4. int n = 14;
5. do {
6. n = n >> 1;
7. if(n < 4) {
8. ...
12. Suppose you need to write data that consists of char values and String objects to a file
that maintains the format of ...
18. t.start();
19. }
20. }
A. xxxyxxx
B. yxxxxxx
C. Six xs and one y printed in an indeterminate order
D. The code throws ...
A. Object
B. Junior
C. Student
D. String
E. java.io.Serializable
17. What is the result of the following program?
1. publi...
which of the following methods could appear in a child class of Parent? (Select three
answers.)
A. public void doSomething...
A. Compiler error on line 1
B. Compiler error on line 2
C. Compiler error on line 16
D. a string123
E. The code compiles b...
23. What is the result of the following program?
1. public class MathFunctions {
2. public static void addToInt(int x, int...
D. Compiler error on line 4 of Readable.java
E. Compiler error on line 4 of MyReader.java
25. Given the following enum dec...
6. System.out.println(args[0] + args[1]
7. + args[2]);
8. }
9. }
what is the result of the following command line?
java Ec...
30. What state can a NEW thread transition into? (Select all that apply.)
A. WAITING
B. RUNNABLE
C. BLOCKED
D. TIMED_WAITI...
8. b.drink();
9. }
10. }
11.
12. class Coffee extends Beverage {
13. public void drink() {
14. System.out.println(“Coffee”...
Answers to Assessment Test
1. C. The code compiles fine, so D and E are incorrect. The bytecode file for the outer
class Boo...
10. D. The code compiles, so A and B are incorrect. The command line does not enable asser-
tions, so C cannot happen. Lin...
20. D. The compiles and runs fine, so A, B, C, and E are incorrect. The Box class uses a
generic type named T. For one, the...
30. B. A NEW thread can only transition into the RUNNABLE state, so the answer is B. For more
information, see Chapter 5.
...
SCJP: Sun Certified Programmer
for Java Platform, SE6 Study Guide
CX-301-065 Exam Objectives
OBJECTIVE CHAPTER
Section 1: ...
OBJECTIVE CHAPTER
Develop code that makes use of exceptions and exception handling clauses
(try, catch, finally), and decla...
OBJECTIVE CHAPTER
Section 4: Concurrency
Write code to define, instantiate, and start new threads using both java.lang
.Thr...
OBJECTIVE CHAPTER
Use capabilities in the java.util package to write code to manipulate a list by
sorting, performing a bi...
Fundamentals
SCJP EXAM OBJECTIVES COVERED IN
THIS CHAPTER:
Given a code example and a scenario, write code
that uses the a...
Java is an interpretive, object-oriented programming language
that Sun Microsystems developed. A considerable benefit of
wr...
public class Cat {
public String name;
public int weight;
}
Compiled Java code is referred to as bytecode, and the name of...
4 Chapter 1 Fundamentals
Access Specifiers for Top-Level Classes
A top-level class has two options for an access modifier: p...
a Java programmer, you will create your own packages for the classes that you develop.
Packages are often drawn as tabbed ...
6 Chapter 1 Fundamentals
Putting a class in a package has two important side effects that you need to know
for the exam:
1...
The import keyword is used to import a single class or, when used with the wildcard (*),
an entire package. A source file c...
8 Chapter 1 Fundamentals
interfaces of java.lang into every source file, so there is never any need to import types from
ja...
If you ever are in a situation where you need to use two classes with the same name but
in different packages, then using ...
10 Chapter 1 Fundamentals
Suppose we have the following class definition:
package com.sybex.payroll;
public class Employee ...
The CLASSPATH Environment Variable
The exam objectives state that “given a code example and a classpath,” you need to be
a...
12 Chapter 1 Fundamentals
Running Java Applications
The SCJP certification exam tests your knowledge of running a Java prog...
The answers are yes and no. Yes, this class compiles, but no, it does not define main
properly. A static method can access ...
14 Chapter 1 Fundamentals
Specifying the Class Name
The command line for java.exe requires the name of the class that cont...
The source file ColorChanger.java is saved in c:myprojectsrccomsybexevents
and the class is compiled using the following co...
16 Chapter 1 Fundamentals
A typical exam question at this point is to ask what the CLASSPATH needs to be for you to
run th...
Don’t Panic During the Exam!
The purpose of the ColorChanger and TestColors example is to demonstrate running
a Java appli...
18 Chapter 1 Fundamentals
to distribute Java code, and the exam tests your understanding of JAR files and how they
relate t...
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
SCJP SE6
Upcoming SlideShare
Loading in...5
×

SCJP SE6

660

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
660
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
50
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

SCJP SE6

  1. 1. SCJP Sun Certified Programmer for Java® Platform, SE6 Study Guide
  2. 2. SCJP Sun Certified Programmer for Java® Platform, SE6 Study Guide Richard F. Raposa
  3. 3. Acquisitions Editor: Jeff Kellum Development Editor: Jennifer Leland Technical Editor: James Nuzzi Production Editor: Christine O’Connor Copy Editor: Elizabeth Welch Production Manager: Tim Tate Vice President and Executive Group Publisher: Richard Swadley Vice President and Publisher: Neil Edde Media Project Manager 1: Laura Moss-Hollister Media Associate Producer: Shawn Patrick Media Quality Assurance: Angie Denny Book Designer: Judy Fung, Bill Gibson Proofreader: Nancy Bell Indexer: Robert Swanson Project Coordinator, Cover: Lynsey Stanford Cover Designer: Ryan Sneed Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-0-470-41797-3 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 permitted 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 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 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 particular 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 Web site 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 Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites 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 or to obtain technical support, please contact our Customer 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 be available in electronic books. Library of Congress Cataloging-in-Publication Data Raposa, 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 2009 005.13'3—dc22 2008054906 TRADEMARKS: Wiley, the Wiley logo, and the Sybex logo 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 registered 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. 10 9 8 7 6 5 4 3 2 1 Disclaimer: This eBook does not include ancillary media that was packaged with the printed version of the book.
  4. 4. Dear Reader, Thank you for choosing SCJP: Sun Certified Programmer for Java Platform, SE6 Study Guide. This book is part of a family of premium-quality Sybex books, all of which are written 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 to producing consistently exceptional books. With each of our titles we’re working hard to set a new standard for the industry. From the paper we print on, to the authors we work with, 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 comments and get your feedback on how we’re doing. Feel free to let me know what you think about this or any other Sybex book by sending me an email at nedde@wiley.com, or if you think 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 Edde Vice President and Publisher Sybex, an Imprint of Wiley
  5. 5. To Susan, Megan, Ryan, Katelyn, Emma and Sara.
  6. 6. Acknowledgments A lot of time and energy goes into a book like this, and my wife and kids will be the first ones to attest to that fact! I owe them many thanks for their patience and understanding during the months that went into this project. I also want to thank Jennifer Leland, the Developmental Editor, for putting up with my complete inability to learn when to use the appropriate styles. Everyone who reads this 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 finding errors and typos. Thanks also to Jeff Kellum, Pete Gaughan, Christine O’Connor, and everyone 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 of learning Java and passing the SCJP Exam. I hope all of you find this book informative and indispensable wherever your Java adventures take you. Good luck! About the Author Rich Raposa runs a Java training firm, JLicense, Inc., based out of Rapid City, SD. He is a Sun Certified Java Programmer as well as a Sun Certified Java Instructor, and has spent the past 11 years delivering Java training courses to businesses across the United States. He has written dozens of Java courses ranging from introductory Java to advanced topics like Enterprise JavaBeans, Java Web development, and Java Web Services. He enjoys playing poker and playing the guitar (though he does not claim to be good at either).
  7. 7. Contents at a Glance Introduction xvii Assessment Test xxiv Chapter 1 Fundamentals 1 Chapter 2 Declarations, Initialization, and Scoping 77 Chapter 3 Flow Control 187 Chapter 4 API Contents 269 Chapter 5 Concurrency 341 Chapter 6 Object-Oriented Concepts 381 Chapter 7 Collections and Generics 425 Appendix 491 Glossary 495 Index 507
  8. 8. Contents Introduction xvii Assessment Test xxiv Chapter 1 Fundamentals 1 Writing Java Classes 2 Packages 4 The package Keyword 5 The import Keyword 6 Package Directory Structure 9 The CLASSPATH Environment Variable 11 Running Java Applications 12 The -classpath Flag 17 JAR Files 17 Command-Line Arguments 19 Reference vs. Primitive Types 22 Primitive Types 22 Reference Types 23 Garbage Collection 28 The System.gc Method 32 The finalize Method 33 Call by Value 36 Java Operators 43 The Assignment Operators 44 The Arithmetic Operators 46 The Relational Operators 50 The instanceof Operator 51 The Bitwise and Logical Operators 53 The Conditional Operator 55 The Equality Operators 56 Equality of Objects 58 Summary 61 Exam Essentials 61 Review Questions 63 Answers to Review Questions 73 Chapter 2 Declarations, Initialization, and Scoping 77 Declaring Variables 78 Scoping 80 Instance Variables 80 Class Variables 83 Local Variables 86
  9. 9. xii Contents Declaring Arrays 88 Array References 89 Array Objects 90 Using Arrays 91 Multidimensional Arrays 93 Array Initializers 95 Declaring Classes 97 The Instantiation Process 100 Constructors 102 The Default Constructor 104 Using this in Constructors 105 Using super in Constructors 108 Instance Initializers 111 Static Initializers 114 Declaring Methods 116 Method Declarations 116 JavaBeans Naming Convention 118 Instance Methods 121 Static Methods 124 Variable-Length Arguments 126 Method Overloading 128 Method Overriding 131 Covariant Return Types 134 Method Hiding 135 Final Methods 137 Declaring Abstract Classes 138 Abstract Methods 140 Declaring Interfaces 143 Implementing Interfaces 144 Extending Interfaces 147 Declaring Enumerations 147 Using enums 149 Declaring enum Methods 150 Declaring enum Constructors 151 Declaring Nested Classes 152 Member Inner Classes 152 Local Inner Classes 158 Anonymous Inner Classes 159 Static Nested Classes 162 Summary 165 Exam Essentials 166 Review Questions 168 Answers to Review Questions 183
  10. 10. Contents xiii Chapter 3 Flow Control 187 Overview of Flow Control 188 The if Statement 188 The switch Statement 192 Switching on an Enum 194 Final case Values 196 The for Statement 197 The Basic for Statement 197 The Enhanced for Statement 201 The while Statement 206 The do Statement 209 The break Statement 211 The continue Statement 215 Overview of Assertions 218 The assert Statement 219 Enabling Assertions 220 Using Assertions 221 Overview of Exceptions 224 The try Statement 227 Multiple catch Clauses 229 The Handle or Declare Rule 231 The finally Block 238 Java API Exceptions and Errors 242 ArrayIndexOutOfBoundsException 243 ClassCastException 244 IllegalArgumentException 245 IllegalStateException 245 NullPointerException 246 NumberFormatException 246 AssertionError 247 ExceptionInInitializerError 247 StackOverflowError 248 NoClassDefFoundError 249 Summary 249 Exam Essentials 250 Review Questions 251 Answers to Review Questions 265 Chapter 4 API Contents 269 The Primitive Wrapper Classes 270 Autoboxing and Unboxing 272 Strings 274 The String Class 275 The StringBuilder and StringBuffer Classes 278
  11. 11. xiv Contents Input and Output 281 Streams vs. Readers and Writers 281 Low-Level vs. High-Level Streams 283 File Input and Output 285 The FileReader and FileWriter Classes 285 The File Class 287 The FileInputStream and FileOutputStream Classes 289 The DataInputStream and DataOutputStream Classes 291 The PrintWriter Class 294 The format and printf Methods 295 The Console Class 298 Object Serialization 301 The Serializable Interface 301 The ObjectOutputStream Class 303 The ObjectInputStream Class 304 Formatting and Parsing Data 306 Format and Parse Numbers and Currency 306 Format and Parse Dates 312 Regular Expressions 315 The Pattern and Matcher Classes 315 The String.split Method 320 The Scanner Class 322 Summary 324 Exam Essentials 325 Review Questions 326 Answers to Review Questions 337 Chapter 5 Concurrency 341 Overview of Threads 342 Writing a Thread 343 Implementing the Runnable Interface 344 Extending the Thread Class 346 Thread States 349 New Threads 349 Runnable Threads 351 Blocked Threads 353 Waiting and Timed-Waiting Threads 353 Terminated Threads 355 Thread Synchronization 355 The Monitor Lock 358 The wait, notify, and notifyAll Methods 363 Summary 368
  12. 12. Contents xv Exam Essentials 369 Review Questions 370 Answers to Review Questions 378 Chapter 6 Object-Oriented Concepts 381 Encapsulation, Coupling, and Cohesion 382 Tight Encapsulation 382 Loose Coupling 385 High Cohesion 388 OO Design Relationships 390 The “is-a” Relationship 390 The “has-a” Relationship 392 Modifiers and Inheritance 393 The Access Modifiers 393 The abstract Modifier 397 The final Modifier 399 Polymorphism 401 Understanding Polymorphism 402 Casting Polymorphic References 405 Summary 409 Exam Essentials 410 Review Questions 412 Answers to Review Questions 423 Chapter 7 Collections and Generics 425 Overview of Collections 426 The Collections Interfaces 426 The Comparable Interface 432 The Difference Between == and equals 433 Using Generics 436 Limitations of Nongeneric Collections 436 Lists 438 Sets 441 Maps 445 Generic Types and Methods 449 Generic Classes 450 Generic Interfaces 451 Generic Methods 453 Bounded Generic Types 455 Generic Wildcards 458 Working with Lists 461 Sorting Lists 461 Searching Lists 467
  13. 13. xvi Contents Working with Arrays 470 Sorting Arrays 470 Searching Arrays 473 Summary 475 Exam Essentials 476 Review Questions 478 Answers to Review Questions 487 Appendix 491 Glossary 495 Index 507
  14. 14. Introduction The 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 understands the basic syntax and structure of the Java programming language and can create Java technology 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 the SCJP exam, and once you pass it, then you are a Sun Certified Java Programmer for the particular 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 Exam The SCJP exam consists of 72 questions and you are given three and one-half hours to complete it. You take the exam at an Authorized Worldwide Prometric Testing Center. You take the SCJP exam on a computer using the mouse to display questions and answers. The questions appear on the screen one at a time, and you can navigate forward and backward at any time to view any question or modify your answer. Longer questions do not fit on the screen and require you to click on the scroll bar. You answer a question by clicking the appropriate 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 board and a dry-erase marker. Most testing centers have security cameras as well, and it is likely that other people will be in the exam room taking different exams. Types of Exam Questions The SCJP exam consists of the following types of questions: Multiple choice A majority of the questions are multiple choice. The number of answers given varies for each question, but typically you are given five to six answers. If a question has more than one answer, the question specifically states exactly how many correct answers there are for the question. For example, a question might have five answers and state that two of them are correct. The exam software only allows you to select two answers for that particular question. Drag and drop About 10 to 15 of the exam questions involve filling in the blanks of a question. The answers are given in a list or box on the screen, and you drag and drop an answer into the blank. Some of the drag-and-drop questions have the exact same number of blanks as answers, and some of them have more answers than blanks.
  15. 15. xviii Introduction When you navigate from one question to the next during the exam, the multiple choice questions simply appear on the screen. If the question is drag and drop, you do not see the actual question initially when you navigate to the question. Instead, you click a button that displays the question and answers, and when you have finished answering the question, you close the display and return to the navigation screen, where you can continue to the next question. Tips for Taking the SCJP Exam The most important tip I can give you for passing the exam is to practice answering questions. Study all of the sample questions that appear at the end of each chapter, as well as the bonus exam questions and the Assessment Test later in this Introduction. I tried to write questions that were indicative of the questions on the exam as far as knowledge and difficulty level. Between this book and its accompanying CD, you have over 400 questions to 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 at a time without checking the answers right away. This will help simulate the taking of the actual exam. Some questions on the SCJP exam are easier than others and require less time, while other questions might take several minutes to answer. You should average about 30 questions an hour. This pace will leave you with an hour or so at the end to go back and review your answers. If you start running out of time, make sure you at least answer every question on the exam, even if you have to guess. There is no penalty for a wrong answer, so do not leave a question blank. Do not underestimate the exam objectives or try to guess what will or won’t be on the exam. Because the number of objectives outnumbers the exam questions, not every exam objective has a corresponding exam question. Therefore, your best plan of action is to understand every exam objective. If you find yourself struggling with a particular topic, then write some code! Writing code and making mistakes along the way are the best way to understand any programming topic. Also, expect the newer concepts of the Java language to appear on the exam. For example, I can guarantee that you will see a question on generics and enumerations. These are newer concepts in the language and they separate the new SCJP exam from the previous versions. One unpleasant issue that I ran into with the drag-and-drop questions is that you cannot review the answer after you move on to the next question. If you go back to a drag-and- drop question and click the button to display the question and answers, your answer is lost and you have to re-answer the question in its entirety. Some of these drag-and-drop questions took some time to determine the answer, and I found that I did not always remember what my initial answer was, so I had to rethink the question all over again! If you are getting close to the end of your allotted time and you are trying to review all your answers, you might want to be judicious about whether to rework through a drag-and-drop question.
  16. 16. Introduction xix If you have to retake the exam, keep in mind that there are several versions of the exam and the questions will be different each time you take the exam. Exam Registration The price of the exam in the United State is $300 and you can purchase a voucher online at http://www.sun.com/training/catalog/courses/CX-310-065.xml. This URL is for the Java SE 6.0 exam. If you are taking a different version of the exam, you can find the corresponding registration page at http://www.sun.com/training/catalog/courses/. If you reside outside of the United States, visit http://www.sun.com/training/world_ training.html to purchase a voucher for the exam. After you purchase your exam voucher, you have up to one year from the date of purchase to use it. Each voucher is valid for one exam and can only be used at an Authorized Prometric Testing Center in the country for which it was purchased. Please be aware that exam vouchers are nonrefundable for any reason. An exam voucher contains a unique number that you provide to Prometric when scheduling the exam. To schedule the exam, contact Prometric at (800) 795-3926 (United States 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 forms of identification. One must be a current, government-issued photo ID, such as a valid passport or driver’s license, with a photo that looks like you. Be sure the names on your ID are displayed the same way it is displayed on your exam record, and that both IDs have a current signature that looks like yours. Examples of other pieces of ID are credit cards and check cashing cards. The test will not be delivered without the appropriate form of identification. Prometric Test Center Administrators have the right to refuse seating you for the 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. Prometric recommends that you arrive at the testing center at least 30 minutes before the test is scheduled to begin to allow time to complete the sign-in process. Is This Book for You? If you want to become certified as a Java programmer, this book is definitely for you. If you want to acquire a solid foundation in Java and your goal is to prepare for the exam by learning how to program and develop in Java, this book is for you. You’ll find clear explanations of the concepts you need to grasp and plenty of help to achieve the high level of professional competency you need in order to succeed in your chosen field. However, if you just want to attempt to pass the exam without really understanding Java, this study guide is not for you. It is written for people who want to acquire hands-on skills and in-depth knowledge of programming Java.
  17. 17. xx Introduction What’s in the Book? What makes a Sybex Study Guide the book of choice for hundreds of thousands of SCJPs? We took into account not only what you need to know to pass the exam, but also what you need to know to take what you’ve learned and apply it in the real world. Each book contains the following: Objective-by-objective coverage of the topics you need to know Each chapter lists the objectives covered in that chapter. The topics covered in this Study Guide map directly to Sun’s official exam objectives. Each exam objective is covered completely. Assessment Test Directly following this Introduction is an Assessment Test that you should take. It is designed to help you determine how much you already know about the Java Platform, Standard Edition 6. Each question is tied to a topic discussed in the book. Using the results of the Assessment Test, you can figure out the areas where you need to focus your study. Of course, we do recommend you read the entire book. Exam Essentials To highlight what you learn, you’ll find a list of Exam Essentials at the end of each chapter. The Exam Essentials section briefly highlights the topics that need your particular attention as you prepare for the exam. Glossary Throughout each chapter, you will be introduced to important terms and con- cepts that you will need to know for the exam. These terms appear in italic within the chapters, and at the end of the book, a detailed Glossary gives definitions for these terms, as well as other general terms you should know. Review questions, complete with detailed explanations Each chapter is followed by a set of Review Questions that test what you learned in the chapter. The questions are written with the exam in mind, meaning that they are designed to have the same look and feel as what you’ll see on the exam. Real World Scenarios Because reading a book isn’t enough for you to learn how to apply these topics in your everyday duties, we have provided Real World Scenarios in special side- bars. These explain when and why a particular solution would make sense, in a working environment you’d actually encounter. Interactive CD Every Sybex Study Guide comes with a CD complete with additional questions, flashcards for use with an interactive device, and the book in electronic format. Details are in the following section. What’s on the CD? With this new member of our best-selling Study Guide series, we are including quite an array of training resources. The CD offers bonus exams and flashcards to help you study
  18. 18. Introduction xxi for the exam. We have also included the complete contents of the Study Guide in electronic form. The CD’s resources are described here: The Sybex E-book for SCJP: Sun Certified Programmer for Java Platform, SE6 Study Guide Many people like the convenience of being able to carry their whole Study Guide on a CD. They also like being able to search the text via computer to find specific information quickly and easily. For these reasons, the entire contents of this Study Guide are supplied on the CD, in PDF. We’ve also included Adobe Acrobat Reader, which provides the interface for the PDF contents as well as the search capabilities. The Sybex Test Engine This is a collection of multiple-choice questions that will help you prepare for your exam. There are three sets of questions: Two bonus exams designed to simulate the actual live exam. All the questions from the Study Guide, presented in a test engine for your review. You can review questions by chapter, or you can take a random test. The Assessment Test. Here is a sample screen from the Sybex Test Engine:
  19. 19. xxii Introduction Sybex Flashcards for PCs and Handheld Devices The “flashcard” style of question offers an effective way to quickly and efficiently test your understanding of the fundamental con- cepts covered in the exam. The Sybex Flashcards set consists of 100 questions presented in a special engine developed specifically for this Study Guide series. Here’s what the Sybex Flashcards interface looks like: Because of the high demand for a product that will run on handheld devices, we have also developed, in conjunction with Land-J Technologies, a version of the flashcard questions that you can take with you on your Palm OS PDA (including the PalmPilot and Hand- spring’s Visor). How to Use This Book This book is loaded with valuable information, and you will get the most out of your studying time if you understand how I put the book together. Here’s a list on how to approach studying it so you get the most out of it: 1. Take the Assessment Test immediately following this introduction. It’s okay if you don’t know any of the answers—that’s what this book is for! Carefully read over the explanations for any question you get wrong and make note of the chapters where that material is covered.
  20. 20. Introduction xxiii 2. Study each chapter carefully, making sure that you fully understand the information and the test objectives listed at the beginning of each one. Again, pay extra-close attention to any chapter that includes material covered in questions you missed on the Assessment Test. 3. Answer all of the Review Questions related to each chapter. Specifically note any questions that confuse you and study those sections of the book again. And don’t just skim these questions—make sure you understand each answer completely! 4. Try your hand at the bonus exams included on the companion CD. The questions in these exams appear only on the CD. 5. Test yourself using all the flashcards on the CD. If you follow the steps listed here and study and practice the Review Questions, bonus exams, and the electronic flashcards, you should do fine.
  21. 21. Assessment Test 1. The following code appears in a file named Book.java. What is the result of compiling this source file? (Select one answer.) 1. public class Book { 2. private int pageNumber; 3. 4. private class BookReader { 5. public int getPage() { 6. return pageNumber; 7. } 8. } 9. } A. The code compiles successfully and one bytecode file is generated: Book.class. B. The code compiles successfully and two bytecode files are generated: Book.class and BookReader.class. C. The code compiles successfully and two bytecode files are generated: Book.class and Book$BookReader.class. D. A compiler error occurs on line 4. E. A compiler error occurs on line 6. 2. Given the following TV class: 1. public class TV { 2. private String make; 3. private String model; 4. 5. public TV(String make, String model) { 6. this.make = make; 7. this.model = model; 8. } 9. 10. public boolean equals(TV other) { 11. return make.equals(other.make) && 12. model.equals(other.model); 13. } 14. 15. public int hashCode() { 16. return make.length() * 10 + model.length(); 17. } 18. }
  22. 22. what is the result of the following statements? TV a = new TV(“Philips”, “42PFL5603D”); TV b = new TV(“Philips”, “42PFL5603D”); if(a.equals(b)) { System.out.println(“equal”); } else { System.out.println(“not equal”); } A. equal B. not equal C. Line 10 causes a compiler error. D. Line 11 causes a compiler error. E. Line 15 causes a runtime exception to occur. 3. When does the String object “hi” instantiated on line 2 become eligible for garbage collection? 1. public class Hello { 2. String greeting = “hi”; 3. 4. public static void main(String [] args) { 5. Hello h = new Hello(); 6. h.greeting = null; 7. System.gc(); 8. return; 9. } 10. } A. Immediately after line 5 B. Immediately after line 6 C. Immediately after line 7 D. Immediately after line 8 E. Immediately after line 9 4. What is the result of the following code? 6. byte x = 23, y = 4; 7. int z = 23 % 4; 8. System.out.println(z); A. 3 B. 4 C. 4.75 Assessment Test xxv
  23. 23. D. Compiler error on line 6 E. Compiler error on line 7 5. What is the result of the following program? 1. public class Vehicle { 2. public boolean used; 3. public String make; 4. 5. public static void main(String [] args) { 6. Vehicle v = new Vehicle(); 7. if(v.used) { 8. System.out.println(v.make); 9. } else { 10. System.out.println(v.make.length()); 11. } 12. } 13. } A. null B. 0 C. Line 7 generates a compiler error. D. Line 8 generates an exception at runtime. E. Line 10 generates an exception at runtime. 6. Given the following class definition: 1. public class PrintStrings { 2. public static void print(String... values) { 3. for(String value : values) { 4. System.out.print(value); 5. } 6. } 7. } which of the following statements are valid method calls to print? A. PrintStrings.print(); B. PrintStrings.print(“abc“); C. PrintStrings.print(‘a’, ‘b’, ‘c’); D. PrintStrings.print(“a”, “b”, “c“); E. PrintStrings.print(new java.util.Date()); xxvi Assessment Test
  24. 24. 7. Given the following Football class definition: 1. package my.sports; 2. 3. public class Football { 4. public static final int teamSize = 11; 5. } and also the following FootballGame class: 1. package my.apps; 2. 3. 4. 5. public class FootballGame { 6. public int getTeamSize() { 7. return teamSize; 8. } 9. } which of the following statements can appear on line 3 so that the FootballGame class compiles successfully? A. import static my.sports.Football; B. import my.sports.Football; C. import static my.sports.Football.*; D. import static my.sports.*; E. No import statement is necessary. 8. What is the result of the following statements? 28. Integer i = 5; 29. switch(i) { 30. case 1: System.out.print(1); break; 31. case 3: System.out.print(3); 32. case 5: System.out.print(5); 33. case 7: System.out.print(7); break; 34. default: System.out.print(“default”); 35. } A. 5 B. 57 C. 57default D. Compiler error on line 28 E. Compiler error on line 29 Assessment Test xxvii
  25. 25. 9. What is the result of the following code? 3. Boolean m = true; 4. int n = 14; 5. do { 6. n = n >> 1; 7. if(n < 4) { 8. m = new Boolean(false); 9. } 10. }while(m); 11. System.out.println(n); A. 0 B. 2 C. 3 D. An infinite loop E. Line 10 generates a compiler error. 10. Given the following class definition: 1. public class AssertDemo { 2. public static void main(String [] args) { 3. Integer x = 10; 4. assert x == null && x >= 0; 5. System.out.println(x); 6. } 7. } and given the following command line, which one of the following statements is true? java AssertDemo A. Line 3 generates a compiler error. B. Line 4 generates a compiler error. C. Line 4 throws an AssertionError at runtime. D. The output is 10. 11. Which of the following statements are true? (Select two.) A. All string literals are automatically instantiated into a String object. B. The StringBuilder and StringBuffer classes define the exact same public methods. C. In a multithreaded environment, use StringBuilder instead of StringBuffer. D. A StringBuilder object is immutable. E. A StringBuffer object cannot change its length once it is instantiated. xxviii Assessment Test
  26. 26. 12. Suppose you need to write data that consists of char values and String objects to a file that maintains the format of the original data. The data needs to be buffered to improve performance. Which two java.io classes can be chained together to best achieve this result? A. FileWriter B. FileOutputStream C. BufferedOutputStream D. BufferedWriter E. PrintWriter F. PipedOutputStream 13. What is the result of the following code? 14. DecimalFormat df = new DecimalFormat(“#,000.0#”); 15. double pi = 3.141592653; 16. System.out.println(df.format(pi)); A. 3.141592653 B. 0,003.14 C. ,003.1 D. 003.14 E. 00.04 14. What is the result of the following program? 1. public class PrintX implements Runnable { 2. private int count; 3. 4. public PrintX(int count) { 5. this.count = count; 6. } 7. 8. public void run() { 9. for(int i = 1; i <= count; i++) { 10. System.out.print(“x”); 11. } 12. } 13. 14. public static void main(String [] args) { 15. Thread t = new Thread(new PrintX(3)); 16. t.start(); 17. System.out.print(“y”); Assessment Test xxix
  27. 27. 18. t.start(); 19. } 20. } A. xxxyxxx B. yxxxxxx C. Six xs and one y printed in an indeterminate order D. The code throws an exception at runtime. E. The code does not compile. 15. What is the result of the following statements? 4. Thread t = new Thread() { 5. public void run() { 6. System.out.println( 7. Thread.currentThread().getState()); 8. } 9. }; 10. t.start(); A. NEW B. RUNNABLE C. BLOCKED D. TERMINATED E. The state of the thread is indeterminate. 16. Given the following class definitions: 1. public class Student implements java.io.Serializable { 2. private String name; 3. 4. public static void main(String [] args) { 5. ___________________ s = new Senior(); 6. } 7. } 8. 9. class Senior extends Student {} 10. 11. class Junior extends Student {} which of the following answers can fill in the blank on line 5 and have the code com- pile successfully? (Select three.) xxx Assessment Test
  28. 28. A. Object B. Junior C. Student D. String E. java.io.Serializable 17. What is the result of the following program? 1. public abstract class Message { 2. public String recipient; 3. 4. public abstract final void sendMessage(); 5. 6. public static void main(String [] args) { 7. Message m = new TextMessage(); 8. m.recipient = “6055551212”; 9. m.sendMessage(); 10. } 11. } 12. 13. class TextMessage extends Message { 14. public final void sendMessage() { 15. System.out.println(“TextMessage to “ 16. + recipient); 17. } 18. } A. TextMessage to 6055551212 B. TextMessage to null C. Compiler error on line 1 D. Compiler error on line 4 E. Compiler error on line 9 18. Given the following Parent class definition: 1. public class Parent { 2. Object doSomething(int x) { 3. return null; 4. } 5. } Assessment Test xxxi
  29. 29. which of the following methods could appear in a child class of Parent? (Select three answers.) A. public void doSomething(int x) B. protected String doSomething(int x) C. private Thread doSomething(int x) D. private Thread doSomething(short x) E. public double doSomething(int y) 19. What is the result of the following statements? 23. List<Number> data = new Vector<Number>(); 24. data.add(10); 25. data.add(“4.5F”); 26. data.add(new Double(56.7)); 27. for(Number number : data) { 28. System.out.print(number); 29. } A. 104.556.7 B. 104.5F56.7 C. 10 followed by a ClassCastException D. Compiler error on line 25 E. Compiler error on line 27 20. Given the following Box class definition: 1. public class Box<T> { 2. T value; 3. 4. public Box(T value) { 5. this.value = value; 6. } 7. 8. public T getValue() { 9. return value; 10. } 11. } what is the result of the following statements? 15. Box<String> one = new Box<String>(“a string”); 16. Box<Integer> two = new Box<Integer>(123); 17. System.out.print(one.getValue()); 18. System.out.print(two.getValue()); xxxii Assessment Test
  30. 30. A. Compiler error on line 1 B. Compiler error on line 2 C. Compiler error on line 16 D. a string123 E. The code compiles but throws an exception at runtime. 21. Given the following statements: 30. Set<Object> objects = new HashSet<Object>(); 31. String one = “hello”; 32. int two = 2; 33. Boolean three = new Boolean(true); 34. objects.add(one); 35. objects.add(two); 36. objects.add(three); 37. objects.add(three); 38. for(Object object : objects) { 39. System.out.print(object); 40. } which of the following statements are true? (Select two.) A. The code compiles successfully. B. The output is hello, 2 and true in an indeterminate order. C. The output is hello, 2, true and true in an indeterminate order. D. Line 35 generates a compiler error. E. Line 37 throws an exception at runtime. 22. Suppose a class named com.mypackage.MyProgram contains the main method of a stand- alone Java application, and MyProgram.class is in the following directory: myclassescommypackage Which of the following commands successfully executes MyProgram? (Select two answers.) A. java -classpath myclasses com.mypackage.MyProgram B. java -classpath myclassescommypackage MyProgram C. java -classpath=myclasses com.mypackage.MyProgram D. java -classpath myclassescom mypackage.MyProgram E. java -cp myclasses com.mypackage.MyProgram Assessment Test xxxiii
  31. 31. 23. What is the result of the following program? 1. public class MathFunctions { 2. public static void addToInt(int x, int amountToAdd) 3. { 4. x = x + amountToAdd; 5. } 6. 7. public static void main(String [] args) { 8. int a = 15; 9. int b = 10; 10. MathFunctions.addToInt(a, b); 11. System.out.println(a); 12. } 13. } A. 25 B. 15 C. 10 D. A compiler error occurs on line 4. E. A compiler error occurs on line 10. 24. Given the following interface and class definitions: 1. //Readable.java 2. public interface Readable { 3. public void read(); 4. public int MAX_LENGTH = 10; 5. } 1. //MyReader.java 2. public class MyReader implements Readable { 3. public void read() { 4. Readable.MAX_LENGTH = 25; 5. System.out.println(Readable.MAX_LENGTH); 6. } 7. } what is the result of the following statement? new MyReader().read(); A. 25 B. 10 C. Compiler error on line 3 of Readable.java xxxiv Assessment Test
  32. 32. D. Compiler error on line 4 of Readable.java E. Compiler error on line 4 of MyReader.java 25. Given the following enum declaration: 1. public enum Toppings { 2. PEPPERONI, SAUSAGE, ONION, OLIVES, CHEESE; 3. } what is the result of the following statements? 8. Toppings [] choices = Toppings.values(); 9. System.out.println(choices[1]); A. PEPPERONI B. SAUSAGE C. The code compiles but the output is indeterminate. D. Line 8 generates a compiler error. E. Line 9 generates a compiler error. 26. What is the result of the following code? 21. final byte b = 1; 22. int value = 2; 23. switch(value) { 24. case b : System.out.print(“A”); 25. break; 26. case 2 : System.out.print(“B”); 27. case 3 : System.out.print(“C”); 28. default : System.out.print(“D”); 29. break; 30. } A. Compiler error on line 24 B. B C. BC D. BCD E. Compiler error on line 29 27. Given the following class definition: 1. public class EchoInput { 2. public static void main(String [] args) { 3. if(args.length <= 3) { 4. assert false; 5. } Assessment Test xxxv
  33. 33. 6. System.out.println(args[0] + args[1] 7. + args[2]); 8. } 9. } what is the result of the following command line? java EchoInput hi there A. hithere B. The assert statement on line 4 throws an AssertionError. C. Line 7 throws an ArrayIndexOutOfBoundsException. D. The code compiles and runs successfully, but there is no output. E. The code does not compile. 28. What is the result of the following code? 46. NumberFormat nf = 47. NumberFormat.getCurrencyInstance(Locale.US); 48. double value = 123.456; 49. System.out.println(nf.format(value)); A. $123.456 B. $123.45 C. $123.46 D. 123.45 E. 123.46 29. Given the following code: 3. Pattern p = Pattern.compile(“.+es”); 4. String [] words = {“unless”, “guesses”, 5. “boxes”, “guest”}; 6. for(String word : words) { 7. if(p.matcher(word).matches()) { 8. System.out.println(word); 9. } 10. } which of the following strings is output? (Select all that apply.) A. unless B. guesses C. boxes D. guest E. None of the above xxxvi Assessment Test
  34. 34. 30. What state can a NEW thread transition into? (Select all that apply.) A. WAITING B. RUNNABLE C. BLOCKED D. TIMED_WAITING E. TERMINATED 31. What is the output of the following program? 1. public class Worker extends Thread { 2. public void run() { 3. System.out.print(“N”); 4. } 5. 6. public static void main(String [] args) { 7. Thread worker = new Worker(); 8. worker.run(); 9. System.out.print(“O”); 10. } 11. } A. The output is always NO. B. The output is always ON. C. The output varies and is either NO or ON. D. The code does not compile. 32. Fill in the blank: When an object performs a collection of closely related tasks, this is referred to as . A. The is-a relationship B. The has-a relationship C. Tight encapsulation D. Loose coupling E. High cohesion 33. What is the result of the following code? 1. public class Beverage { 2. private void drink() { 3. System.out.println(“Beverage”); 4. } 5. 6. public static void main(String [] args) { 7. Beverage b = new Coffee(); Assessment Test xxxvii
  35. 35. 8. b.drink(); 9. } 10. } 11. 12. class Coffee extends Beverage { 13. public void drink() { 14. System.out.println(“Coffee”); 15. } 16. } A. Beverage B. Coffee C. Compiler error on line 2 D. Compiler error on line 8 E. Compiler error on line 13 34. Given the following variable declaration: Set<? extends RuntimeException> set = ___________________; which of the following statements can appear in the blank line so that the statement compiles successfully? (Select all that apply.) A. new HashSet<? extends RuntimeException() B. new TreeSet<RuntimeException>() C. new TreeSet<NullPointerException>() D. new LinkedHashSet<Exception>() E. None of the above xxxviii Assessment Test
  36. 36. Answers to Assessment Test 1. C. The code compiles fine, so D and E are incorrect. The bytecode file for the outer class Book is Book.class, and the bytecode file for the inner class BookReader is Book$BookReader.class, so the answer is C. For more information, see Chapter 2. 2. A. The code compiles fine, so C, D, and E are incorrect. Based on the definition of the equals method, two TV objects are equal if they have the same make and model fields, so the line a.equals(b) evaluates to true and equal is output, so the answer is A. For more information, see Chapter 1. 3. B. The String on line 2 is created in memory after line 5 executes, and the greeting ref- erence points to it. After line 6, no references point to “hi“ anymore and it immediately becomes eligible for garbage collection then, so the answer is B. For more information, see Chapter 1. 4. A. The code compiles fine, so D and E are incorrect. The value of z is the remainder of 23 divided by 4, which is 3. Therefore, the answer is A. For more information, see Chapter 1. 5. E. The code compiles fine, so C is incorrect. The used field initializes to false and the make field initializes to null for the new Vehicle v. Therefore, line 7 is false and line 10 executes. Because v.make is a null reference, attempting to invoke its length method results in a NullPointerException at runtime. Therefore, the answer is E. For more information, see Chapter 2. 6. A, B, and D. The print method can take in any number of String objects, including zero, so A, B, and D are valid statements. C attempts to pass in chars, which is not valid and generates a compiler error. D also generates a compiler error attempting to pass in a Date object. For more information, see Chapter 2. 7. C. The code does not compile without a proper import for the teamSize variable on line 7, so E is incorrect. A is not a valid statement. B is a valid statement but does not import teamSize, so B is incorrect. D causes a compiler error because sports is not a class or interface name. C is valid and imports all static members of the Football class, so C is the correct answer. For more information, see Chapter 2. 8. B. You cannot switch on an Integer, but because of Java’s autoboxing, i is converted to an int, so lines 28 and 29 are valid, which means D and E are incorrect. The value of i is 5, so the case on line 32 executes and prints 5. Because there is no break, 7 is printed. The break on line 33 causes control to break out of the switch, so the output is 57 and the answer is B. For more information, see Chapter 3. 9. C. Line 10 compiles fine, so E is incorrect. Line 6 right shifts n by 1, which is equivalent to integer division by 2. The first time through the loop, n becomes 14/2 = 7; the second time through n becomes 7/2 = 3. Because 3 < 4 is true, m is set to false and the loop terminates. The value of n is 3, which is printed on line 11, so the answer is C. For more information, see Chapter 3.
  37. 37. 10. D. The code compiles, so A and B are incorrect. The command line does not enable asser- tions, so C cannot happen. Line 5 executes and prints out 10, so the answer is D. For more information, see Chapter 3. 11. A and B. String literals are automatically instantiated into String objects, so A is true. B is also true; the two classes contain the same methods. The only difference between String- Builder and StringBuffer is that StringBuffer is thread-safe, which is why C is false. You should use StringBuffer if using mutable strings in a multithreaded application. D is false; the StringBuilder and StringBuffer classes represent mutable character sequences. E is false; a StringBuffer and StringBuilder can grow and shrink to match the number of characters in the sequence. For more information, see Chapter 4. 12. A and D. The data to be output consists of strings and characters, so writer classes are the best choice. FileWriter is needed to write to the file, and BufferedWriter is needed to buffer the data, so the best choices are A and D. For more information, see Chapter 4. 13. D. The DecimalFormat object calls for at least three digits before the decimal point, so two leading 0s appears before the 3. The format also calls for at least one digit past the decimal but no more than two. Therefore, the output is 003.14 and the answer is D. For more infor- mation, see Chapter 4. 14. D. The code compiles fine, so E is incorrect. However, a Thread object cannot be started twice, so line 18 throws an IllegalThreadStateException and D is the correct answer. For more information, see Chapter 5. 15. B. The state of the currently running thread must be RUNNABLE, so the answer is B. For more information, see Chapter 5. 16. A, C, and E. A and C are valid because Object and Student are both parent classes of Senior. B and D are not valid because Junior and String are not compatible with Senior. E is valid because Senior is of type Serializable—a type inherited from Student. For more information, see Chapter 6. 17. D. The code does not compile, so A and B are incorrect. The problem with this code is the Message declares the sendMessage method as both abstract and final, which does not make sense. An abstract method must be overridden, and a final method cannot be overridden. Using abstract and final on the same method results in a compiler error, so the answer is D. For more information, see Chapter 6. 18. B and D. A is incorrect because void is an incompatible return type with Object. (If the return type is changed, it must be a subclass of the return type in the parent class.) B is a valid overriding of doSomething in Parent because it is more accessible and String is a subclass of Object. C is incorrect because it assigns a weaker access, which is not allowed. D is valid because it is not overriding doSomething in Parent—it is overloading the method instead. E is not valid because double is not a subclass of Object. Therefore, the answers are B and D. For more information, see Chapter 6. 19. D. The code does not compile, so A, B, and C are incorrect. E is also incorrect; line 27 compiles fine because data contains Number objects. Line 25 does not compile because data is instantiated using generics; only Number objects can be added to data and “4.5F” is a String. Therefore, the answer is D. For more information, see Chapter 7. xl Answers to Assessment Test
  38. 38. 20. D. The compiles and runs fine, so A, B, C, and E are incorrect. The Box class uses a generic type named T. For one, the generic type is a String. For two, the generic type is an Integer. The two value fields are printed out on lines 17 and 18, which print a string123, so the answer is D. For more information, see Chapter 7. 21. A and B. The code compiles and runs fine, so D and E are incorrect and A is true. Line 37 attempts to add the same object to the set, which does not alter the set. Therefore, C is incorrect. The for loop on line 38 outputs the objects in an indeterminate order, so the other correct answer is B. For more information, see Chapter 7. 22. A and E. A assigns the -classpath flag to the appropriate directory. E also sets the class path correctly except -cp is used. C uses an equals sign, =, with the -classpath flag, which is not the correct syntax. B and D set the class path to the wrong directory and also incor- rectly refer to the MyProgram class without its fully qualified name. Therefore, the answers are A and E. For more information, see Chapter 1. 23. B. The code compiles successfully, so D and E are incorrect. The value of a cannot be changed by the addToInt method, no matter what the method does, because only a copy of a is passed into the parameter x. Therefore, a does not change and the output on line 11 is 15, so the answer is B. For more information, see Chapter 1. 24. E. The Readable interface compiles fine, so C and D are incorrect. However, the MyReader class does not compile, so A and B are incorrect. Fields in an interface are implicitly final, so attempting to set MAX_LENGTH to 25 on line 4 of MyReader is not allowed and generates a compiler error. Therefore, the answer is E. For more information, see Chapter 2. 25. B. The code compiles fine, so D and E are incorrect. The values method of an enum returns an array containing the elements in the enum, in the order they are declared in the enum. The element at index 1 is SAUSAGE, which is printed at line 9. Therefore, the answer is B. For more information, see Chapter 2. 26. D. The code compiles fine, so A and E are incorrect. The case on line 26 is satisfied, so B is printed. There is no break, so line 27 executes and C is printed. Because there is no break, the default block executes and D is printed on line 28. Therefore, the output is BCD and the answer is D. For more information, see Chapter 3. 27. C. The code compiles fine, so E is incorrect. The command line has only two arguments, so args.length is 2 and line 3 is true. However, because assertions are not enabled, line 4 does not throw an AssertionError, so B is incorrect. Line 7 attempts to print args[2], which generates an ArrayIndexOutOfBoundsException, so the answer is C. For more information, see Chapter 3. 28. C. The currency format rounds decimals up to two decimal places, so 123.456 is rounded up to 123.46 and printed in the U.S. locale. The output is $123.46, and therefore the answer is C. For more information, see Chapter 4. 29. B and C. The regular expression .+es matches character streams that start with any number of characters and end in es. Two of the strings in the array match this pattern: guesses and boxes. Therefore, the answers are B and C. For more information, see Chapter 4. Answers to Assessment Test xli
  39. 39. 30. B. A NEW thread can only transition into the RUNNABLE state, so the answer is B. For more information, see Chapter 5. 31. A. The code compiles fine and runs fine, so D is incorrect. On line 8, the run method of the new Worker thread is invoked. However, the run method does not start a new thread in the process. (Only a call to start starts a new thread.) In other words, this program is not multithreaded and the call to run occurs within the main thread. The output of this pro- gram is always NO and therefore the answer is A. For more information, see Chapter 5. 32. E. The definition of high cohesion is when an object performs a collection of closely related tasks, so the answer is E. For more information, see Chapter 6. 33. A. The code compiles fine, so C, D and E are incorrect. A private method cannot be over- ridden, so drink in Coffee is not overriding drink in Beverage. The method call to drink on line 8 is referring to the private method on line 2, and that is also the method that gets invoked at runtime because it is not overridden. Therefore, the output is Beverage and the correct answer is A. For more information, see Chapter 6. 34. B and C. The reference set declares an upper bound of RuntimeException on the generic, so D is not valid because Exception is a parent class of RuntimeException. A is not valid because a new statement cannot declare a wildcard in the generic type. B is valid because TreeSet implements Set. C is valid because TreeSet implements Set and NullPointerEx- ception is a subclass of RuntimeException. Therefore, the answers are B and C. For more information, see Chapter 7. xlii Answers to Assessment Test
  40. 40. SCJP: Sun Certified Programmer for Java Platform, SE6 Study Guide CX-301-065 Exam Objectives OBJECTIVE CHAPTER Section 1: Declarations, Initialization and Scoping Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports). 2 Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class. 2 Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names. 2 Develop code that declares both static and non-static methods, and—if appropriate—use method names that adhere to the JavaBeans naming standards. Also develop code that declares and uses a variable-length argument list. 2 Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method. 2 Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class. 2 Section 2: Flow Control Develop code that implements an if or switch statement; and identify legal argument types for these statements. 3 Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution. 3 Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions. 3
  41. 41. OBJECTIVE CHAPTER Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions. 3 Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error. 3 Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programmatically. 3 Section 3: API Contents Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing and unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes. 4 Given a scenario involving navigating file systems, reading from files, writing to files, or interacting with the user, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader, BufferedWriter, File, FileReader, FileWriter, PrintWriter, and Console. 4 Develop code that serializes and/or de-serializes objects using the following APIs from java.io: DataInputStream, DataOutputStream, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream and Serializable. 4 Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class. 4 Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, d, s, w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings. 4
  42. 42. OBJECTIVE CHAPTER Section 4: Concurrency Write code to define, instantiate, and start new threads using both java.lang .Thread and java.lang.Runnable. 5 Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another. 5 Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems. 5 Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll. 5 Section 5: OO Concepts Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits. 6 Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting. 6 Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods. 6 Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, or overloaded constructors. 6 Develop code that implements “is-a” and/or “has-a” relationships. 6 Section 6: Collections/Generics Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface. 7 Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method. 7 Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions. Write code that uses the NavigableSet and NavigableMap interfaces. 7 Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches. 7
  43. 43. OBJECTIVE CHAPTER Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the “natural ordering” of primitive wrapper classes and java.lang.String on sorting. 7 Section 7: Fundamentals Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example. 1 Given an example of a class and a command line, determine the expected runtime behavior. 1 Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters. 1 Given a code example, recognize the point at which an object becomes eligible for garbage collection, determine what is and is not guaranteed by the garbage collection system, and recognize the behaviors of the Object.finalize() method. 1 Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully. 1 Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives. 1 Exam specifications and content are subject to change at any time without prior notice and at Sun Microsystems’ sole discretion. Please visit Sun’s website (www.sun.com/training) for the most current information on their exam content.
  44. 44. Fundamentals SCJP EXAM OBJECTIVES COVERED IN THIS CHAPTER: Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example. Given an example of a class and a command line, determine the expected runtime behavior. Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters. Given a code example, recognize the point at which an object becomes eligible for garbage collection, determine what is and is not guaranteed by the garbage collection system, and recognize the behaviors of the Object .finalize() method. Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully. Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives. Chapter 1
  45. 45. Java is an interpretive, object-oriented programming language that Sun Microsystems developed. A considerable benefit of writing Java applications is that they run in a Java Runtime Environment (JRE) that is well defined. As a Java programmer, you know your Java program is going to run on a Java Virtual Machine (JVM), regardless of the device or operating system. Consequently, you know an int is 32 bits and signed, a boolean is true or false, method arguments are passed by value, and the garbage collector cleans up your unreachable objects whenever it feels like it. (Okay, not every aspect of Java is an exact science!) The point is that Java runs in a precise environment, and passing the SCJP exam requires a strong knowledge of these well-defined Java fundamentals. This chapter covers the fundamentals of Java programming, including writing Java classes, running Java applications, creating packages, defining classpath, and using the Java operators. We will also discuss the details of garbage collection and call by value. Writing Java Classes The exam objectives state that you need to be able to “write code that uses the appropriate access modifiers, package declarations, and imports statements.” In other words, you need to be able to write Java classes, which makes sense because Java is an object-oriented programming (OOP) language and writing classes is an essential aspect of OOP. Your executable Java code will appear within the definition of a class. A class describes an object, which is a noun in your program. The object can either represent something tangible, like a television or an employee, or it can represent something less obvious but just as useful in your program, like an event handler or a stream of data being read from a file. An object is an instance of a class. Think of a class as a blueprint for a house, and the object as the house. Another common analogy is to think of a class as a recipe for cookies, and the objects are the cookies. (We will discuss the details of instantiating objects in Chapter 2, “Declarations, Initialization, and Scoping.”) Because classes are a fundamental aspect of Java programming, the certification exam assumes you are familiar with the rules for writing them, and in this section we cover these details. For starters, a Java class must be defined in a text file with a .java extension. In addition, if the class is declared public, then the name of the file must match the name of the class. Consequently, a .java file can only contain at most one top-level public class. For example, the following class definition must appear in a file named Cat.java:
  46. 46. public class Cat { public String name; public int weight; } Compiled Java code is referred to as bytecode, and the name of the bytecode file matches the name of the class. Compiling the Cat.java source file creates a bytecode file named Cat.class. Line Numbers Java source files do not contain line numbers. However, the classes on the exam display line numbers. If the numbering starts with a 1, then the entire definition of a source file is being displayed. If the numbering starts with some other value, then only a portion of a source file is being displayed. You will see this explanation in the instructions at the beginning of the SCJP exam. Java allows multiple classes in a single .java file as long as no more than one of the top- level classes is declared public. The compiler still generates a separate .class file for each class defined in the .java file. For example, suppose a file named Customer.java contains the following two class definitions: 1. public class Customer { 2. public String name; 3. public String address; 4. } 5. 6. class Order { 7. public int partNumber; 8. public int quantity; 9. public boolean shipped; 10. } Compiling Customer.java generates two files: Customer.class and Order.class. Note that the Order class cannot be public because Customer is already public, nor can Order be protected or private because Java does not allow top-level classes to be protected or private. Therefore, Order must have the default access, often referred to as friendly or package-level access, meaning only classes within the same package can use the Order class. (We discuss packages in the next section.) Writing Java Classes 3
  47. 47. 4 Chapter 1 Fundamentals Access Specifiers for Top-Level Classes A top-level class has two options for an access modifier: public or package-level access (often called the default access). Keep an eye out for exam questions that declare a top- level class as private or protected. For example, the following code will not compile: //Generates a compiler error: “modifier private not allowed here” private class HelloWorld { public static void main(String [] args) { System.out.println(args[1] + args[2]); } } Multiple Classes in a Single File Java allows multiple top-level classes to be defined in a single file, but in the real world this is rarely done. We typically want our classes to be public, and only top-level classes can be public. That being said, the exam might contain questions that define multiple classes in a single source file because it is convenient and many questions on the exam involve more than one class. Packages The exam objectives state that you need to be able to “write code that uses the appropriate package declarations and import statements,” and I can assure you there will be more than one question on the exam testing your knowledge of the package keyword and its effect on a Java class. This section discusses the details you need to know about Java packages. A package is a grouping of classes and interfaces. It can also contain enumerations and annotated types, but because these are special types of classes and interfaces, I will refer to items in a package as simply classes and interfaces for brevity. This grouping of classes and interfaces is typically based on their relationship and usage. For example, the java.io package contains classes and interfaces related to input and output. The java.net package contains the classes and interfaces related to networking. There are two key benefits of using packages in Java: Packages organize Java programs by grouping together related classes and interfaces. Packages create a namespace for your classes and interfaces. The Application Programming Interface (API) for the Java Platform, Standard Edition (Java SE) contains hundreds of packages that you can use in any Java SE application. As
  48. 48. a Java programmer, you will create your own packages for the classes that you develop. Packages are often drawn as tabbed folders, as shown in Figure 1.1. F I G U R E 1.1 When designing a Java application, packages are drawn as tabbed folders. String Object System Thread java.lang File InputStream OutputStream PrintWriter java.io JButton JFrame Timer ImageIcon javax.swing Item Order ShippingAddress my.company.inventory To view all of the packages in the Java SE API, visit the API documentation at http://java.sun.com/javase/6/docs/api/. This web page contains three frames. The upper- left frame is a list of all the packages. Clicking a package displays its classes and interfaces in the lower-left frame. Clicking a class or interface in the lower-left frame displays its documentation page in the main frame. You should spend time browsing the Java API documentation! I find it extremely useful, especially when using a Java class or interface for the first time. If you are developing a Java program with hundreds of classes and interfaces, grouping related types into packages provides a much-needed organization to the project. In addition, the namespace provided by a package is useful for avoiding naming conflicts. This section discusses these two benefits of packages in detail. I will start with a discussion on the package keyword and then cover the details of imports, the CLASSPATH environment variable, and the directory structure required for packages. The package Keyword The package keyword puts a class or interface in a package, and it must be the first line of code in your source file (aside from comments, which can appear anywhere within a source file). For example, the following Employee class is declared in the com.sybex.payroll package: package com.sybex.payroll; public class Employee { public Employee() { System.out.println( “Constructing a com.sybex.payroll.Employee”); } } Packages 5
  49. 49. 6 Chapter 1 Fundamentals Putting a class in a package has two important side effects that you need to know for the exam: 1. The fully qualified name of a class or interface changes when it is in a package. The package name becomes a prefix for the class name. For example, the fully qualified name of the Employee class shown earlier is com.sybex.payroll.Employee. 2. The compiled bytecode file must appear in a directory structure on your file system that matches the package name. For example, a .class file for any class or interface in the com.sybex.payroll package must appear in a directory structure matching comsybexpayroll. You can either create this directory structure yourself or use the -d flag during compilation and the compiler will create the necessary directory structure for you. We discuss the -d flag in detail later in this section. The fully qualified name of the Employee class is com.sybex.payroll.Employee. Other classes that want to use the Employee class need to refer to it by its fully qualified name. For example, the following program creates an instance of the Employee class: public class CreateEmployee { public static void main(String [] args) { com.sybex.payroll.Employee e = new com.sybex.payroll.Employee(); } } Here’s the output of the CreateEmployee program: Constructing a com.sybex.payroll.Employee The Unnamed Package If a class is not specifically declared in a package, then that class belongs to the unnamed package. Classes and interfaces in the unnamed package cannot be imported into a source file. You should only use the unnamed package when writing simple classes and interfaces that are not being used in a production application. In the real world, you will rarely write a Java class or interface that is not declared in a package. Your classes will appear in a package name that contains your company’s Internet domain name, which the next section discusses. The import Keyword As you can see by the CreateEmployee program, using the fully qualified name of a class can be tedious and makes for a lot of typing! The import keyword makes your life as a coder easier by allowing you to refer to a class in a source file without using its fully qualified name.
  50. 50. The import keyword is used to import a single class or, when used with the wildcard (*), an entire package. A source file can have any number of import statements, and they must appear after the package declaration and before the class declaration. Importing classes and packages tells the compiler that you are not going to use fully qualified names for classes. The compiler searches your list of imports to determine the fully qualified names of the classes referenced in the source file. Here is the CreateEmployee program again, except this time the com.sybex.payroll .Employee class is imported, allowing the Employee class to be referred to without using its fully qualified name: import com.sybex.payroll.Employee; public class CreateEmployee2 { public static void main(String [] args) { Employee e = new Employee(); } } The output is the same as before: Constructing a com.sybex.payroll.Employee In fact, the compiled bytecode files CreateEmployee.class and CreateEmployee2.class are completely identical (except for the number 2 that appears in CreateEmployee2.class). The import statement does not affect the compiled code. Behind the scenes, the compiler removes the import statement and replaces each occurrence of Employee with com.sybex .payroll.Employee. What Does Import Mean? The term import sounds like something is being brought into your source file, but nothing is physically added to your source code by importing a class or package. An import state- ment is strictly to make your life as a programmer easier. The Java compiler removes all import statements and replaces all the class names in your source code with their fully qualified names. For this reason, you never need to use import statements. Instead, you can use fully qualified names throughout your source files. However, you will quickly discover the benefit of import statements, especially when you work with long package names. The CreateEmployee and CreateEmployee2 programs both refer to the String class. String is defined in the java.lang package, but this package was not imported. The java .lang package is unique in that the compiler automatically imports all the public classes and Packages 7
  51. 51. 8 Chapter 1 Fundamentals interfaces of java.lang into every source file, so there is never any need to import types from java.lang (although it is perfectly valid to do so). The following program demonstrates an import statement that uses the wildcard to import an entire package. The program uses the File, FileReader, BufferedReader, and IOException classes, all found in the java.io package. The program reads a line of text from a file named mydata.txt. 1. import java.io.*; 2. 3. public class ReadFromFile { 4. public static void main(String [] args) { 5. File file = new File(“mydata.txt”); 6. FileReader fileReader = null; 7. try { 8. fileReader = new FileReader(file); 9. BufferedReader in = new BufferedReader(fileReader); 10. System.out.println(in.readLine()); 11. }catch(IOException e) { 12. e.printStackTrace(); 13. } 14. } 15. } Because nothing is actually included into your source file by the import keyword, using the wildcard does not impact the size of your bytecode files. However, common practice in Java is to avoid using the wildcard because it may lead to ambiguity when two packages are imported that share a common class name. For example, the following code does not compile because there is a class called AttributeList in both the javax.swing.text.html .parser package and the javax.management package: 1. import javax.swing.text.html.parser.*; 2. import javax.management.*; 3. 4. public class ImportDemo { 5. public AttributeList a; 6. } The ImportDemo class generates the following compiler error: reference to AttributeList is ambiguous, both class javax.management.AttributeList in javax.management and class javax.swing.text.html.parser.AttributeList in javax.swing.text.html.parser match public AttributeList a;
  52. 52. If you ever are in a situation where you need to use two classes with the same name but in different packages, then using imports does not work. You will need to refer to each class by their fully qualified name in your source file. The following code compiles successfully: 1. public class FullyQualifiedDemo { 2. public javax.management.AttributeList a1; 3. public javax.swing.text.html.parser.AttributeList a2; 4. } The FullyQualifiedDemo program demonstrates why packages are often referred to as namespaces because package names are used to avoid naming conflicts. Without packages, there is no way for the compiler or the JVM to distinguish between the two AttributeList classes. However, because the two AttributeList classes are declared in different packages, they can be referred to by their fully qualified names to avoid any ambiguity. Naming Convention for Packages The namespace ambiguity situation can still occur if programmers happen to use the same package names in different programs. If you and I both write a class called Dog and we both define Dog in a package named pets, then a naming conflict still occurs. How- ever, the standard Java naming convention for a package name is to use your company’s domain name (in reverse) as a prefix to your package names. For example, a class written by an employee of Sybex uses a package name that starts with com.sybex. Subsequent components of the package name may include your department and project name, followed by a descriptive name for the package. For example, com.sybex .scjpbook.pets is a good package name for a class named Dog that appears in this book. It is extremely unlikely that someone else would use this package name, although I am sure there are other Dog classes in the world. If everyone who writes Java code follows this naming convention for package names, then naming conflicts can only occur within a single company or project, making it easier to resolve the naming conflict. Package Directory Structure The exam objectives state that “given the fully-qualified name of a class that is deployed inside and/or outside a JAR file,” you need to be able to “construct the appropriate directory structure for that class.” This objective refers to the required directory structure that results from using packages. In addition to creating a namespace, packages organize your programs by grouping related classes and interfaces together. One result of using packages is that the bytecode of a class or interface must appear in a directory structure that matches its package name. If you do not put your bytecode in the proper directory structure, the compiler or the JVM will be unable to find your classes. Packages 9
  53. 53. 10 Chapter 1 Fundamentals Suppose we have the following class definition: package com.sybex.payroll; public class Employee { public Employee() { System.out.println( “Constructing a com.sybex.payroll.Employee”); } } This Employee class is in the com.sybex.payroll package, so its compiled file Employee .class must be in a directory with a pathname comsybexpayroll. This requires a directory named com, which can appear anywhere on your file system. Inside com you must have a sybex subdirectory, which must contain a payroll subdirectory. The com directory can appear anywhere on your file system. A common technique is to put your source files in a directory named src and your bytecode files in a directory named build. For example, suppose the Employee source file is in the following directory: c:myprojectsrccomsybexpayrollEmployee.java Suppose you want the compiled code to be in the c:myprojectbuild directory. You can use the -d flag of the compiler to achieve this. The -d flag has two effects: The compiled code will be output in the directory specified by the -d flag. The appropriate directory structure that matches the package names of the classes is created automatically in the output directory. Consider the following compiler command, executed from the c:myprojectsrc directory: javac -d c:myprojectbuild .comsybexpayrollEmployee.java The -d flag specifies the output directory as c:myprojectbuild. Assuming the class compiles successfully, the compiler creates the file Employee.class in the following directory: c:myprojectbuildcomsybexpayrollEmployee.class Keep in mind the directory c:myprojectbuild is arbitrary; we could have output the bytecode into the directory of our choosing. After you start putting bytecode in arbitrary directories on your file system, the compiler and the JVM need to know where to look to find it. They look for the bytecode files in your classpath, an important concept that the next section discusses in detail.
  54. 54. The CLASSPATH Environment Variable The exam objectives state that “given a code example and a classpath,” you need to be able to “determine whether the classpath will allow the code to compile successfully.” The classpath refers to the path on your file system where your .class files are saved, and the classpath is defined by the CLASSPATH environment variable. The CLASSPATH environment variable specifies the directories and JAR files where you want the compiler and the JVM to search for bytecode. Using CLASSPATH allows your bytecode to be stored in the directory of your choosing, as well as in multiple directories or Java archive (JAR) files. For example, suppose you have a class named com.sybex.payroll.Employee. The compiler and the JVM look for the comsybexpayroll directory structure by searching your CLASSPATH environment variable. For example, if Employee.class is in the following directory: c:Documents and SettingsRichworkspacesbuildcomsybexpayroll then your CLASSPATH needs to include the directory: c:Documents and SettingsRichworkspacesbuild The CLASSPATH environment variable can contain any number of directories and JAR files. Setting CLASSPATH on Windows can be done from a command prompt using a semicolon to separate multiple values: set CLASSPATH=”c:Documents and SettingsRichworkspacesbuild”; c:myprojectbuild;c:tomcatlibservlet.jar;.; In this example, the compiler and the JVM look for bytecode files in the two build directories specified, the servlet.jar file in c:tomcatlib, and the current working directory (represented by the dot). The double quotes are necessary in the first directory because of the spaces in the pathname. On Unix, you use the setenv command and colons to separate multiple values. For example: setenv CLASSPATH /usr/build:/myproject/build:/tomcat/lib/servlet.jar A common mistake new Java programmers make is to include part of the package pathname in the CLASSPATH. If you are struggling with classes not being found, you might be tempted to try the following command line: set CLASSPATH=c:myprojectbuildcomsybexpayroll; Including comsybexpayroll in your CLASSPATH does not work! Do not add any of the package directories to your CLASSPATH, only the parent directory. The compiler and the JRE will look for the appropriate subdirectories. CLASSPATH plays a key role in compiling and running your Java applications, which we discuss in the next section. Packages 11
  55. 55. 12 Chapter 1 Fundamentals Running Java Applications The SCJP certification exam tests your knowledge of running a Java program from the command line using an appropriate CLASSPATH. If you are using Sun’s Java Development Kit (JDK), then java.exe in the bin folder of the JDK directory is the executable used to run your Java applications. The sample commands in this book assume java.exe is in your path. The entry point of a Java program is main, which you can define in any class. The signature of main must look like this: public static void main(String [] args) The only changes you can make to this signature are the name of the parameter args, which can be arbitrary, and the order of public and static. For example, the following declaration is a valid signature of main: static public void main(String [] x) In addition, you can specify the array of String objects using the syntax for variable- length arguments: public static void main(String... args) Variable-Length Arguments As of Java 5.0, a method in Java can declare a variable-length argument list denoted by the ellipsis (...). Variable-length arguments are discussed in detail in Chapter 2. The args array contains the command-line arguments, discussed in detail later in this section. The main method has to be public so that the JVM has access to it, and making it static allows the JVM to invoke this method without having to instantiate an instance of the containing class. Let’s start with a simple example. Suppose the following class is saved in the c:myproject directory. First, does the following SaySomething class compile, and does it successfully declare the main method? 1. public class SaySomething { 2. private static String message = “Hello!”; 3. 4. public static void main() { 5. System.out.println(message); 6. } 7. }
  56. 56. The answers are yes and no. Yes, this class compiles, but no, it does not define main properly. A static method can access a static field in the same class, so there is no problem with the message field. Also, you can write a method called main that does not have an array of String objects, so the compiler will not complain about the main method defined on line 4. However, this class cannot be executed as a Java application because it does not successfully declare the proper main method for a Java application. Let’s try it again, this time with the following SayHello class. Does this class compile and successfully declare the main method? 1. public class SayHello { 2. private static String message = “Hello!”; 3. 4. public static void main(String [] args) { 5. System.out.println(message); 6. } 7. } The answer is yes to both: SayHello compiles and declares the proper version of main so that it can be executed as a stand-alone Java application. The following command line runs the SayHello application: java SayHello This command line assumes that you run the command from the directory that contains the file SayHello.class, which in our case is c:myproject. If you want to run this Java application from any directory (instead of just c:myproject), you need to include c:myproject in your CLASSPATH. Figure 1.2 shows SayHello being executed from c:myproject, and then being executed from c: after the CLASSPATH is correctly set. F I G U R E 1. 2 Compiling and running the SayHello program from a command prompt Running Java Applications 13
  57. 57. 14 Chapter 1 Fundamentals Specifying the Class Name The command line for java.exe requires the name of the class that contains main. Notice that the name of the class is not the same as the name of the bytecode file, which in the SayHello example is SayHello.class. The following command line does not work: java SayHello.class The JVM looks for a class named class in the SayHello package (which it will not find) and throws a NoClassDefFoundError. The JVM only needs the name of the class; it will find the corresponding bytecode file by scanning all the directories and JAR files set in your CLASSPATH environment variable. If you do not set a CLASSPATH, the JVM looks in the current working directory. The exam will likely test your knowledge with a more complex example where the class containing main is in a package. Let’s look at another example, starting with a class called ColorChanger in the com.sybex.events package: 1. package com.sybex.events; 2. 3. import java.awt.Component; 4. import java.awt.Color; 5. import java.awt.event.*; 6. 7. public class ColorChanger implements ActionListener { 8. private Component container; 9. 10. public ColorChanger(Component c) { 11. container = c; 12. } 13. 14. public void actionPerformed(ActionEvent e) { 15. String color = e.getActionCommand(); 16. if(color.equals(“red”)) { 17. container.setBackground(Color.RED); 18. } else if(color.equals(“blue”)) { 19. container.setBackground(Color.BLUE); 20. } else { 21. container.setBackground(Color.WHITE); 22. } 23. } 24. }
  58. 58. The source file ColorChanger.java is saved in c:myprojectsrccomsybexevents and the class is compiled using the following command executed from c:myprojectsrc: javac -d c:myprojectbuild .comsybexeventsColorChanger.java This command line creates ColorChanger.class in the c:myprojectbuildcomsybex events directory. The following program contains main and tests the ColorChanger class: 1. package com.sybex.demos; 2. 3. import com.sybex.events.ColorChanger; 4. import java.awt.Button; 5. import java.awt.Color; 6. import java.awt.event.ActionEvent; 7. 8. public class TestColors { 9. 10. public static void main(String [] args) { 11. Button b = new Button(“Testing...”); 12. b.setBackground(Color.GREEN); 13. System.out.println(“Color is “ + b.getBackground()); 14. 15. ColorChanger cc = new ColorChanger(b); 16. ActionEvent action = new ActionEvent(b, 17. ActionEvent.ACTION_PERFORMED, 18. “blue”); 19. cc.actionPerformed(action); 20. System.out.println(“Now the color is “ 21. + b.getBackground()); 22. } 23. } TestColors.java is saved in the c:myprojectsrccomsybexdemos directory. Because TestColors is not in the same package as ColorChanger, it imports the ColorChanger class. TestColors is compiled using the following command executed from the c:myprojectsrc directory: javac -d c:myprojectbuild .comsybexdemosTestColors.java This command line creates TestColors.class in the directory c:myprojectbuildcom sybexdemos. Figure 1.3 shows the directory structure after compiling the source files with -d. Running Java Applications 15
  59. 59. 16 Chapter 1 Fundamentals A typical exam question at this point is to ask what the CLASSPATH needs to be for you to run the TestColors program at the command prompt from any working directory. Do you know the answer? I will reveal it in a moment, but first here is the command prompt that runs the TestColors application if you execute it from the c:myprojectbuild directory: java com.sybex.demos.TestColors Notice the fully qualified class name of TestColors must be specified to execute properly. Using the fully qualified name has nothing to do with CLASSPATH or the current working directory. The following command does not work and results in a java.lang .NoClassDefFoundError, no matter what directory you run it from or what your CLASSPATH is set to: java TestColors Why will this never work? Because there is no class called TestColors. Remember, putting a class in a package changes the name of the class. Because TestColors is in the com.sybex.demos package, the name of the class is com.sybex.demos.TestColors, and that name must be used on the command line. By the way, the answer to the question earlier about CLASSPATH is it needs to contain c:myprojectbuild: set CLASSPATH=c:myprojectbuild; With this CLASSPATH, the command to run the TestColors program can be executed from any directory. • c:myproject • +src • | +com • | +sybex • | +demos • | | +TestColors.java • | +events • | +ColorChanger.java • +build • +com • +sybex • +demos • | +TestColors.class • +events • +ColorChanger.class F I G U R E 1. 3 The source code and bytecode are typically stored in separate folders.
  60. 60. Don’t Panic During the Exam! The purpose of the ColorChanger and TestColors example is to demonstrate running a Java application from a command line, so what the code does is not relevant in this situation. If you are not familiar with the Container and ActionListener classes, a ColorChanger can listen to action events of a GUI component in Java because it implements ActionListener. When an action event occurs, the actionPerformed method is invoked, which changes the background color of the given GUI component. You might encounter a situation on the exam where you are not familiar with some of the classes in the given code. Don’t panic! Focus on what the exam question is asking before trying to figure out what the code is doing. You might discover that the behavior of the code is irrelevant because the question is testing you on a different facet of the language. You can also set the classpath for the JVM on the command line using the -classpath flag, which is discussed in the next section, followed by a discussion on running Java code stored in JAR files. The -classpath Flag The java command that starts the JVM has a -classpath flag that allows the classpath to be specified from the command line. This is a common technique for ensuring the classpath is pointing to the right directories and JAR files. Using the -classpath flag overrides the CLASSPATH environment variable. For example, we could run the TestColors program using the following command prompt executed from any directory: java -classpath c:myprojectbuild com.sybex.demos.TestColors If you have multiple directories or JAR files, use a semicolon on a Windows machine to separate them on the -classpath flag. For example, the following command line adds the current directory to the classpath: java -classpath c:myprojectbuild;. com.sybex.demos.TestColors On a Unix machine, use a colon to separate multiple directories and JAR files: java -classpath /myproject/build:. com.sybex.demos.TestColors The java command can also define the classpath using the -cp flag, which is just a shortcut for the -classpath flag. JAR Files Bytecode can be stored in archived, compressed files known as JAR files. JAR is short for Java archive. The compiler and the JVM can find bytecode files in JAR files without needing to uncompress the files onto your file system. JAR files are the most common way Running Java Applications 17
  61. 61. 18 Chapter 1 Fundamentals to distribute Java code, and the exam tests your understanding of JAR files and how they relate to CLASSPATH. The JDK comes with the tool jar.exe for creating and extracting JAR files. The following command adds the bytecode files of the c:myprojectbuild directory to a new JAR file named myproject.jar: C:myprojectbuild>jar -cvf myproject.jar . added manifest adding: com/(in = 0) (out= 0)(stored 0%) adding: com/sybex/(in = 0) (out= 0)(stored 0%) adding: com/sybex/demos/(in = 0) (out= 0)(stored 0%) adding: com/sybex/demos/TestColors.class(in = 1209) (out= 671)(deflated 44%) adding: com/sybex/events/(in = 0) (out= 0)(stored 0%) adding: com/sybex/events/ColorChanger.class(in = 883) (out= 545)(deflated 38%) adding: com/sybex/payroll/(in = 0) (out= 0)(stored 0%) adding: com/sybex/payroll/Employee.class(in = 402) (out= 292)(deflated 27%) The -c flag is for creating a new JAR file. The -v flag tells the jar command to be verbose while it is processing files. The -f flag is for denoting the filename of the new JAR file, which in this example is myproject.jar. After the filename, you specify the files or directories to include in the JAR. In our example, because all of our bytecode was conveniently located in the build directory, we simply added the entire contents of c:myprojectbuild, using the dot to represent the current directory. JAR Files and Package Names If a class is in a package, then the JAR file must contain the appropriate directory structure when the .class file is included in the JAR. Notice in the verbose output of the jar command shown earlier, the necessary com directory and subdirectories matching our package names are added to the JAR. You can add a JAR file to your CLASSPATH. In fact, it is common to have lots of JAR files in your CLASSPATH. The following example demonstrates adding myproject.jar to the CLASSPATH of a Windows machine, then running the TestColors program (which is in myproject.jar): C:>set CLASSPATH=c:myprojectbuildmyproject.jar; C:>java com.sybex.demos.TestColors Color is java.awt.Color[r=0,g=255,b=0] Now the color is java.awt.Color[r=0,g=0,b=255]

×