Effective Java (Java Series) / Edition 2

Paperback (Print)
Rent
Rent from BN.com
$13.69
(Save 75%)
Est. Return Date: 11/20/2014
Buy Used
Buy Used from BN.com
$32.35
(Save 41%)
Item is in good condition but packaging may have signs of shelf wear/aging or torn packaging.
Condition: Used – Good details
Used and New from Other Sellers
Used and New from Other Sellers
from $34.68
Usually ships in 1-2 business days
(Save 36%)
Other sellers (Paperback)
  • All (28) from $34.68   
  • New (23) from $38.03   
  • Used (5) from $34.68   

Overview

Are you looking for a deeper understanding of the Java™ programming language so that you can write code that is clearer, more correct, more robust, and more reusable? Look no further! Effective Java™, Second Edition, brings together seventy-eight indispensable programmer’s rules of thumb: working, best-practice solutions for the programming challenges you encounter every day.

This highly anticipated new edition of the classic, Jolt Award-winning work has been thoroughly updated to cover Java SE 5 and Java SE 6 features introduced since the first edition. Bloch explores new design patterns and language idioms, showing you how to make the most of features ranging from generics to enums, annotations to autoboxing.

Each chapter in the book consists of several “items” presented in the form of a short, standalone essay that provides specific advice, insight into Java platform subtleties, and outstanding code examples. The comprehensive descriptions and explanations for each item illuminate what to do, what not to do, and why.

Highlights include:

  • New coverage of generics, enums, annotations, autoboxing, the for-each loop, varargs, concurrency utilities, and much more
  • Updated techniques and best practices on classic topics, including objects, classes, libraries, methods, and serialization
  • How to avoid the traps and pitfalls of commonly misunderstood subtleties of the language
  • Focus on the language and its most fundamental libraries: java.lang, java.util, and, to a lesser extent, java.util.concurrent and java.io

Simply put, Effective Java™, Second Edition, presents the most practical, authoritative guidelines available for writing efficient, well-designed programs.

Read More Show Less

Editorial Reviews

From the Publisher

Raves for the First Edition!

“I sure wish I had this book ten years ago. Some might think that I don’t need any Java books, but I need this one.”

—James Gosling, fellow and vice president, Sun Microsystems, Inc.

“An excellent book, crammed with good advice on using the Java programming language and object-oriented programming in general.”

—Gilad Bracha, coauthor of The Java™ Language Specification, Third Edition

“10/10—anyone aspiring to write good Java code that others will appreciate reading and maintaining should be required to own a copy of this book. This is one of those rare books where the information won’t become obsolete with subsequent releases of the JDK library.”
—Peter Tran, bartender, JavaRanch.com

“The best Java book yet written.... Really great; very readable and eminently useful. I can’t say enough good things about this book. At JavaOne 2001, James Gosling said, ‘Go buy this book!’ I’m glad I did, and I couldn’t agree more.”
—Keith Edwards, senior member of research staff, Computer Science Lab at the Palo Alto Research Center (PARC), and author of Core JINI (Prentice Hall, 2000)

“This is a truly excellent book done by the guy who designed several of the better recent Java platform APIs (including the Collections API).”
—James Clark, technical lead of the XML Working Group during the creation of the XML 1.0 Recommendation, editor of the XPath and XSLT Recommendations

“Great content. Analogous to Scott Meyers’ classic Effective C++. If you know the basics of Java, this has to be your next book.”
—Gary K. Evans, OO mentor and consultant, Evanetics, Inc

“Josh Bloch gives great insight into best practices that really can only be discovered after years of study and experience.”
—Mark Mascolino, software engineer

“This is a superb book. It clearly covers many of the language/platform subtleties and trickery you need to learn to become a real Java master.”
—Victor Wiewiorowski, vice president development and code quality manager, ValueCommerce Co., Tokyo, Japan

“I like books that under-promise in their titles and over-deliver in their contents. This book has 57 items of programming advice that are well chosen. Each item reveals a clear, deep grasp of the language. Each one illustrates in simple, practical terms the limits of programming on intuition alone, or taking the most direct path to a solution without fully understanding what the language offers.”

—Michael Ernest, Inkling Research, Inc.

“I don’t find many programming books that make me want to read every page—this is one of them.”
—Matt Tucker, chief technical officer, Jive Software

“Great how-to resource for the experienced developer.”
—John Zukowski, author of numerous Java technology books

“I picked this book up two weeks ago and can safely say I learned more about the Java language in three days of reading than I did in three months of study! An excellent book and a welcome addition to my Java library.”
—Jane Griscti, I/T advisory specialist

Booknews
Having worked as a platform libraries architect for Java since 1996, Bloch shares with programmers what he has learned about what works, what does not, and how to use the language and its libraries to best effect. He presents 57 specific hints in sections on creating and destroying objects, methods common to all objects, classes and interfaces, substitutes for C constructs, methods, general programming, exceptions, threads, and serialization. Annotation c. Book News, Inc., Portland, OR (booknews.com)
Read More Show Less

Product Details

  • ISBN-13: 9780321356680
  • Publisher: Addison-Wesley
  • Publication date: 5/18/2008
  • Series: Java Series
  • Edition number: 2
  • Pages: 384
  • Sales rank: 93,099
  • Product dimensions: 7.30 (w) x 9.10 (h) x 1.00 (d)

Meet the Author

Joshua Bloch is chief Java architect at Google and a Jolt Award winner. He was previously a distinguished engineer at Sun Microsystems and a senior systems designer at Transarc. Bloch led the design and implementation of numerous Java platform features, including JDK 5.0 language enhancements and the award-winning Java Collections Framework. He coauthored Java™ Puzzlers (Addison-Wesley, 2005) and Java™ Concurrency in Practice (Addison-Wesley, 2006).

Read More Show Less

Read an Excerpt

Chapter 6: Methods

This chapter discusses several aspects of method design: how to treat parameters and return values, how to design method signatures, and how to document methods. Much of the material in this chapter applies to constructors as well as to methods. Like Chapter 5, this chapter focuses on usability, robustness, and flexibility.

Item 23: Check parameters for validity

Most methods and constructors have some restrictions on what values may be passed into their parameters. For example, it is not uncommon that index values must be nonnegative and object references must be non-null. You should clearly document all such restrictions and enforce them with checks at the beginning of the method body. This is a special case of the general principle, and you should attempt to detect errors as soon as possible after they occur. Failing to do so makes it less likely that an error will be detected and makes it harder to determine the source of an error once it has been detected.

If an invalid parameter value is passed to a method and the method checks its parameters before execution, it will fail quickly and cleanly with an appropriate exception. If the method fails to check its parameters, several things could happen. The method could fail with a confusing exception in the midst of processing. Worse, the method could return normally but silently compute the wrong result. Worst of all, the method could return normally but leave some object in a compromised state, causing an error at some unrelated point in the code at some undetermined time in the future.

For public methods, use the Javadoc @throws tag to document the exception that will be thrown if a restriction on parameter values is violated (Item 44). Typically the exception will be IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException (Item 42). Once you've documented the restrictions on a method's parameters and you've documented the exceptions that will be thrown if these restrictions are violated, it is a simple matter to enforce the restrictions. Here's a typical example:

/**
*Returns a BigInteger whose value is (this mod m).This method
*differs from the remainder method in that it always returns
*nonnegative BigInteger.
*
*@param m the modulus,which must be positive.
*@return this mod m.
*@throws ArithmeticException if m <= 0.
*/
public BigInteger mod(BigInteger m){
       if (m.signum()<= 0)
            throw new ArithmeticException("Modulus not positive");
       ... // Do the computation
}

For an unexported method, you as the package author control the circumstances under which the method is called, so you can and should ensure that only valid parameter values are ever passed in. Therefore nonpublic methods should generally check their parameters using assertions rather than normal checks. If you are using a release of the platform that supports assertions (1.4 or later), you should use the assert construct; otherwise you should use a makeshift assertion mechanism.

It is particularly important to check the validity of parameters that are not used by a method but are stored away for later use. For example, consider the static factory method on page 86, which takes an int array and returns a List view of the array. If a client of this method were to pass in null , the method would throw a NullPointerException because the method contains an explicit check. If the check had been omitted, the method would return a reference to a newly created List instance that would throw a NullPointerException as soon as a client attempted to use it. By that time, unfortunately, the origin of the List instance might be very difficult to determine, which could greatly complicate the task of debugging.

Constructors represent a special case of the principle that you should check the validity of parameters that are to be stored away for later use. It is very important to check the validity of parameters to constructors to prevent the construction of an object that violates class invariants.

There are exceptions to the rule that you should check a method's parameters before performing its computation. An important exception is the case in which the validity check would be expensive or impractical and the validity check is performed implicitly in the process of doing the computation. For example, consider a method that sorts a list of objects, such as Collections.sort(List). All of the objects in the list must be mutually comparable. In the process of sorting the list, every object in the list will be compared to some other object in the list. If the objects aren't mutually comparable, one of these comparisons will throw a ClassCastException, which is exactly what the sort method should do. Therefore there would be little point in checking ahead of time that the elements in the list were mutually comparable. Note, however, that indiscriminate application of this technique can result in a loss of failure atomicity (Item 46).

Occasionally, a computation implicitly performs the required validity check on some parameter but throws the wrong exception if the check fails. That is to say, the exception that the computation would naturally throw as the result of an invalid parameter value does not match the exception that you have documented the method to throw. Under these circumstances, you should use the exception translation idiom described in Item 43 to translate the natural exception into the correct one.

Do not infer from this item that arbitrary restrictions on parameters are a good thing. On the contrary, you should design methods to be as general as it is practical to make them. The fewer restrictions that you place on parameters, the better, assuming the method can do something reasonable with all of the parameter values that it accepts. Often, however, some restrictions are intrinsic to the abstraction being implemented.

To summarize, each time you write a method or constructor, you should think about what restrictions exist on its parameters. You should document these restrictions and enforce them with explicit checks at the beginning of the method body. It is important to get into the habit of doing this; the modest work that it entails will be paid back with interest the first time a validity check fails.

Item 24: Make defensive copies when needed

One thing that makes the Java programming language such a pleasure to use is that it is a safe language. This means that in the absence of native methods it is immune to buffer overruns, array overruns, wild pointers, and other memory corruption errors that plague unsafe languages such as C and C++. In a safe language it is possible to write classes and to know with certainty that their invariants will remain true, no matter what happens in any other part of the system. This is not possible in languages that treat all of memory as one giant array.

Even in a safe language, you aren't insulated from other classes without some effort on your part. You must program defensively with the assumption that clients of your class will do their best to destroy its invariants. This may actually be true if someone tries to break the security of your system, but more likely your class will have to cope with unexpected behavior resulting from honest mistakes on the part of the programmer using your API. Either way, it is worth taking the time to write classes that are robust in the face of ill-behaved clients.

While it is impossible for another class to modify an object's internal state without some assistance from the object, it is surprisingly easy to provide such assistance without meaning to do so. For example, consider the following class, which purports to represent an immutable time period...

Read More Show Less

Table of Contents

Foreword xi

Preface xiii

Acknowledgments xvii

Chapter 1: Introduction 1

Chapter 2: Creating and Destroying Objects 5

Item 1: Consider static factory methods instead of constructors 5

Item 2: Consider a builder when faced with many constructor

parameters 11

Item 3: Enforce the singleton property with a private constructor 17

Item 4: Enforce noninstantiability with a private constructor 19

Item 5: Avoid creating unnecessary objects 20

Item 6: Eliminate obsolete object references 24

Item 7: Avoid finalizers 27

Chapter 3: Methods Common to All Objects 33

Item 8: Obey the general contract when overriding equals 33

Item 9: Always override hashCode when you override equals 45

Item 10: Always override toString 51

Item 11: Override clone judiciously 54

Item 12: Consider implementing Comparable 62

Chapter 4: Classes and Interfaces 67

Item 13: Minimize the accessibility of classes and members 67

Item 14: In public classes, use accessor methods, not public fields 71

Item 15: Minimize mutability 73

Item 16: Favor composition over inheritance 81

Item 17: Design and document for inheritance or else prohibit it 87

Item 18: Prefer interfaces to abstract classes 93

Item 19: Use interfaces only to define types 98

Item 20: Prefer class hierarchies to tagged classes 100

Item 21: Use function objects to represent strategies 103

Item 22: Favor static member classes over nonstatic 106

Chapter 5: Generics 109

Item 23: Don't use raw types in new code 109

Item 24: Eliminate unchecked warnings 116

Item 25: Prefer lists to arrays 119

Item 26: Favor generic types 124

Item 27: Favor generic methods 129

Item 28: Use bounded wildcards to increase API flexibility 134

Item 29: Consider typesafe heterogeneous containers 142

Chapter 6: Enums and Annotations 147

Item 30: Use enums instead of int constants 147

Item 31: Use instance fields instead of ordinals 158

Item 32: Use EnumSet instead of bit fields 159

Item 33: Use EnumMap instead of ordinal indexing 161

Item 34: Emulate extensible enums with interfaces 165

Item 35: Prefer annotations to naming patterns 169

Item 36: Consistently use the Override annotation 176

Item 37: Use marker interfaces to define types 179

Chapter 7: Methods 181

Item 38: Check parameters for validity 181

Item 39: Make defensive copies when needed 184

Item 40: Design method signatures carefully 189

Item 41: Use overloading judiciously 191

Item 42: Use varargs judiciously 197

Item 43: Return empty arrays or collections, not nulls 201

Item 44: Write doc comments for all exposed API elements 203

Chapter 8: General Programming 209

Item 45: Minimize the scope of local variables 209

Item 46: Prefer for-each loops to traditional for loops 212

Item 47: Know and use the libraries 215

Item 48: Avoid float and double if exact answers are required 218

Item 49: Prefer primitive types to boxed primitives 221

Item 50: Avoid strings where other types are more appropriate 224

Item 51: Beware the performance of string concatenation 227

Item 52: Refer to objects by their interfaces 228

Item 53: Prefer interfaces to reflection 230

Item 54: Use native methods judiciously 233

Item 55: Optimize judiciously 234

Item 56: Adhere to generally accepted naming conventions 237

Chapter 9: Exceptions 241

Item 57: Use exceptions only for exceptional conditions 241

Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors 244

Item 59: Avoid unnecessary use of checked exceptions 246

Item 60: Favor the use of standard exceptions 248

Item 61: Throw exceptions appropriate to the abstraction 250

Item 62: Document all exceptions thrown by each method 252

Item 63: Include failure-capture information in detail messages 254

Item 64: Strive for failure atomicity 256

Item 65: Don’t ignore exceptions 258

Chapter 10: Concurrency 259

Item 66: Synchronize access to shared mutable data 259

Item 67: Avoid excessive synchronization 265

Item 68: Prefer executors and tasks to threads 271

Item 69: Prefer concurrency utilities to wait and notify 273

Item 70: Document thread safety 278

Item 71: Use lazy initialization judiciously 282

Item 72: Don’t depend on the thread scheduler 286

Item 73: Avoid thread groups 288

Chapter 11: Serialization 289

Item 74: Implement Serializable judiciously 289

Item 75: Consider using a custom serialized form 295

Item 76: Write readObject methods defensively 302

Item 77: For instance control, prefer enum types to readResolve 309

Item 78: Consider serialization proxies instead of serialized instances 313

Appendix: Items Corresponding to First Edition 317

References 321

Index of Patterns and Idioms 327

Index 331

Read More Show Less

Preface

Preface to the Second Edition

A lot has happened to the Java platform since I wrote the first edition of this book in 2001, and it’s high time for a second edition. The most significant set of changes was the addition of generics, enum types, annotations, autoboxing, and the for-each loop in Java 5. A close second was the addition of the new concurrency library, java.util.concurrent, also released in Java 5. With Gilad Bracha, I had the good fortune to lead the teams that designed the new language features. I also had the good fortune to serve on the team that designed and developed the concurrency library, which was led by Doug Lea.

The other big change in the platform is the widespread adoption of modern Integrated Development Environments (IDEs), such as Eclipse, IntelliJ IDEA, and NetBeans, and of static analysis tools, such as FindBugs. While I have not been involved in these efforts, I’ve benefited from them immensely and learned how they affect the Java development experience.

In 2004, I moved from Sun to Google, but I’ve continued my involvement in the development of the Java platform over the past four years, contributing to the concurrency and collections APIs through the good offices of Google and the Java Community Process. I’ve also had the pleasure of using the Java platform to develop libraries for use within Google. Now I know what it feels like to be a user.

As was the case in 2001 when I wrote the first edition, my primary goal is to share my experience with you so that you can imitate my successes while avoiding my failures. The new material continues to make liberal use of real-world examples from the Java platform libraries.

The first edition succeeded beyond my wildest expectations, and I’ve done my best to stay true to its spirit while covering all of the new material that was required to bring the book up to date. It was inevitable that the book would grow, and grow it did, from fifty-seven items to seventy-eight. Not only did I add twenty-three items, but I thoroughly revised all the original material and retired a few items whose better days had passed. In the Appendix, you can see how the material in this edition relates to the material in the first edition.

In the Preface to the First Edition, I wrote that the Java programming language and its libraries were immensely conducive to quality and productivity, and a joy to work with. The changes in releases 5 and 6 have taken a good thing and made it better. The platform is much bigger now than it was in 2001 and more complex, but once you learn the patterns and idioms for using the new features, they make your programs better and your life easier. I hope this edition captures my continued enthusiasm for the platform and helps make your use of the platform and its new features more effective and enjoyable.

San Jose, California
April 2008

Read More Show Less

Customer Reviews

Average Rating 4.5
( 13 )
Rating Distribution

5 Star

(8)

4 Star

(3)

3 Star

(2)

2 Star

(0)

1 Star

(0)

Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation

Reminder:

  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

 
Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously
Sort by: Showing all of 13 Customer Reviews
  • Posted August 15, 2009

    One of a Kind

    Very useful, very insightful.

    0 out of 1 people found this review helpful.

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted May 22, 2012

    No text was provided for this review.

  • Anonymous

    Posted July 31, 2011

    No text was provided for this review.

  • Anonymous

    Posted October 6, 2009

    No text was provided for this review.

  • Anonymous

    Posted November 8, 2008

    No text was provided for this review.

  • Anonymous

    Posted October 28, 2010

    No text was provided for this review.

  • Anonymous

    Posted May 9, 2010

    No text was provided for this review.

  • Anonymous

    Posted November 16, 2008

    No text was provided for this review.

  • Anonymous

    Posted November 18, 2008

    No text was provided for this review.

  • Anonymous

    Posted June 5, 2010

    No text was provided for this review.

  • Anonymous

    Posted June 18, 2014

    No text was provided for this review.

  • Anonymous

    Posted February 7, 2009

    No text was provided for this review.

  • Anonymous

    Posted June 23, 2009

    No text was provided for this review.

Sort by: Showing all of 13 Customer Reviews

If you find inappropriate content, please report it to Barnes & Noble
Why is this product inappropriate?
Comments (optional)