Effective Java Programming Language Guide / Edition 1

Paperback (Print)
Used and New from Other Sellers
Used and New from Other Sellers
from $1.99
Usually ships in 1-2 business days
(Save 96%)
Other sellers (Paperback)
  • All (37) from $1.99   
  • New (4) from $9.10   
  • Used (33) from $1.99   
Sort by
Page 1 of 1
Showing All
Note: Marketplace items are not eligible for any BN.com coupons and promotions
Seller since 2010

Feedback rating:



New — never opened or used in original packaging.

Like New — packaging may have been opened. A "Like New" item is suitable to give as a gift.

Very Good — may have minor signs of wear on packaging but item works perfectly and has no damage.

Good — item is in good condition but packaging may have signs of shelf wear/aging or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Acceptable — item is in working order but may show signs of wear such as scratches or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Used — An item that has been opened and may show signs of wear. All specific defects should be noted in the Comments section associated with each item.

Refurbished — A used item that has been renewed or updated and verified to be in proper working condition. Not necessarily completed by the original manufacturer.

New Book. Ship within one business day with tracking number.

Ships from: Hayward, CA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
Seller since 2014

Feedback rating:


Condition: New
New New. Free tracking! Fast shipping! Satisfaction guaranteed!

Ships from: Media, PA

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
Seller since 2015

Feedback rating:


Condition: New
Brand new.

Ships from: acton, MA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
Seller since 2015

Feedback rating:


Condition: New
Brand new.

Ships from: acton, MA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
Page 1 of 1
Showing All
Sort by


A new edition of this title is available, ISBN-10: 0321356683 ISBN-13: 9780321356680

Read More Show Less

Editorial Reviews

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: 9780201310054
  • Publisher: Prentice Hall
  • Publication date: 6/28/2001
  • Series: Java Series
  • Edition description: Older Edition
  • Edition number: 1
  • Pages: 272
  • Product dimensions: 7.25 (w) x 9.08 (h) x 0.68 (d)

Meet the Author

Joshua Bloch is a principal engineer at Google and a Jolt Award-winner. He was previously a distinguished engineer at Sun Microsystems and a senior systems designer at Transarc. Josh led the design and implementation of numerous Java platform features, including JDK 5.0 language enhancements and the award-winning Java Collections Framework. He holds a Ph.D. in computer science from Carnegie Mellon University.

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




1. Introduction.

2. Creating and Destroying Objects.

Consider Providing Static Factory Methods Instead of Constructors.

Enforce the Singleton Property with a Private Constructor.

Enforce Noninstantiability with a Private Constructor.

Avoid Creating Duplicate Objects.

Eliminate Obsolete Object References.

Avoid Finalizers.

3. Methods Common to All Objects.

Obey the General Contract when Overriding Equals.

Always Override HashCode When You Override Equals.

Always Override to String.

Override Clone Judiciously.

Consider Implementing Comparable.

4. Classes and Interfaces.

Minimize the Accessibility of Classes and Members.

Favor Immutability.

Favor Composition Over Inheritance.

Design and Document for Inheritance or Else Prohibit It.

Prefer Interfaces to Abstract Classes.

Use Interfaces Only to Define Types.

Favor Static Member Classes Over Non-Static.

5. Substitutes for C Constructs.

Replace Structures with Classes.

Replace Unions with Class Hierarchies.

Replace Enums with Classes.

Replace Function Pointers with Classes and Interfaces.

6. Methods.

Check Parameters for Validity.

Make Defensive Copies when Needed.

Design Method Signatures Carefully.

Use Overloading Judiciously.

Return Zero-Length Arrays, Not Nulls.

Write Doc Comments for All Exposed API Elements.

7. General Programming.

Minimize the Scope of Local Variables.

Know and Use the Libraries.

Avoid Float and Double if Exact Answers are Required.

Avoid Strings where Other Types are More Appropriate.

Beware the Performance of String Concatenation.

Refer to Objects by their Interfaces.

Prefer Interfaces to Reflection.

Use Native Methods Judiciously.

Optimize Judiciously.

Adhere to Generally Accepted Naming Conventions.

8. Exceptions.

Use Exceptions Only for Exceptional Conditions.

Use Checked Exceptions for Recoverable Conditions, Runtime Exceptions for Programming Errors.

Avoid Unnecessary Use of Checked Exceptions.

Favor the Use of Standard Exceptions.

Throw Exceptions Appropriate to the Abstraction.

Document All Exceptions Thrown by Each Method.

Include Failure-Capture Information in Detail Messages.

Strive for Failure Atomicity.

Don't Ignore Exceptions.

9. Threads.

Synchronize Access to Shared Mutable Data.

Avoid Excessive Synchronization.

Never Invoke Wait Outside a Loop.

Don't Depend on the Thread Scheduler.

Document Thread-Safety.

Avoid Thread Groups.

10. Serialization.

Implement Serializable Judiciously.

Consider Using a Custom Serialized Form.

Write ReadObject Methods Defensively.

Provide a ReadResolve Method when Necessary.



Read More Show Less


In 1996 I pulled up stakes and headed west to work for JavaSoft, as it was then known, because it was clear that was where the action was. In the intervening five years I've served as Java Platform Libraries Architect. I've designed, implemented and maintained many of the libraries, and served as a consultant for many others. Presiding over these libraries as the Java platform matured was a once-in-a-lifetime opportunity. It is no exaggeration to say that I had the privilege to work with some of the great software engineers of our generation. In the process, I learned a lot about the Java programming language--what works, what doesn't, and how to use the language and its libraries to best effect.

This book is my attempt to share my experience with you, so that you can imitate my successes while avoiding my failures. I borrowed the format from Scott Meyers's Effective C++ Meyers98, which consists of fifty items, each conveying one specific rule for improving your programs and designs. I found the format to be singularly effective and I hope you do too.

In many cases, I took the liberty of illustrating the items with real-world examples from the Java platform libraries. When describing something that could have been done better, I tried to pick on code that I wrote myself, but occasionally I pick on something written by a colleague. I sincerely apologize if, despite my best efforts, I've offended anyone. Negative examples are cited not to cast blame but in the spirit of cooperation, so that all of us can benefit from the experience of those who've gone before.

While this book is not targeted solely at developers of reusable components, it is inevitably colored by my experience writing such components over the past two decades. I naturally think in terms of exported APIs (Application Programming Interfaces) and I encourage you to do likewise. Even if you aren't developing reusable components, thinking in these terms tends to improve the quality of the software you write. Furthermore, it's not uncommon to write a reusable component without knowing it: you write something useful, share it with your buddy across the hall, and before long you have half a dozen users. At this point, you no longer have the flexibility to change the API at will, and are thankful for all the effort that you put into designing the API when you first wrote the software.

My focus on API design may seem a bit unnatural to devotees of the new lightweight software development methodologies, such as Extreme Programming Explained Beck99. These methodologies emphasize writing the simplest program that could possibly work. If you're using one of these methodologies you'll find that a focus on API design serves you well in the refactoring process. The fundamental goals of refactoring are the improvement of system structure and the avoidance of code duplication. These goals are impossible to achieve in the absence of well-designed APIs for the components of the system.

No language is perfect, but some of them are excellent. I have found the Java programming language and its libraries to be immensely conducive to quality and productivity, and a joy to work with. I hope this book captures my enthusiasm and helps make your use of the language more effective and enjoyable.

Josh Bloch Cupertino, California April, 2001


Read More Show Less

Customer Reviews

Average Rating 4
( 3 )
Rating Distribution

5 Star


4 Star


3 Star


2 Star


1 Star


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


  • - 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 3 Customer Reviews
  • Anonymous

    Posted August 5, 2003

    This doesn't spend much time on my bookshelf...

    This doesn't spend much time on my bookshelf because I keep paging through it. I have to disagree with the review by 'JB.' Because Java and C++ (and Perl for that matter, for which there is also an 'Effective' title) are very different languages, it's a bit unreasonable to expect these books to be identical in presentation. That there is less actual code in the Java title illustrates Java's strength in abstraction rather than a shortcoming in book content. Joshua's book is very effective in communicating best practices, just as the C++ and Perl titles do (all from the same publisher). This book lives up to its title.

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

    Posted April 23, 2003

    Great book. A must read for any mature Java developer.

    Great book. I found it to be very useful. A must read for any mature Java developer. I liked the fact that the author often uses actual Java language classes to illustrate his examples. This gave me better appreciation and understanding of the internals of the core Java classes.

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

    Posted February 11, 2002

    Not really

    Nothing close to 'Effective C++' ( as title might suggest to those familiar). This doesn't imply, that the author doesn't know the subject: but the book isn't good. Wordy. Little code. Not worth a place on your shelf. Hope there won't be 'More effective Java'.

    Was this review helpful? Yes  No   Report this review
Sort by: Showing all of 3 Customer Reviews

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