Item 61: Prefer primitive types to boxed primitives

Applying the == operator to boxed primitives is almost always wrong. The two boxed primitives can have same value and different identities, whereas the primitives have only values. Check the code below: When you mix primitives and boxed primitives in an operation, the boxed primitive is auto-unboxed. If a null object reference is auto-unboxed, you […]

Item 60: Avoid float and double if exact answers are required

Use BigDecimal, int, or long for monetary calculations instead of float and double types Advantages of using BigDecimal You want to have full control over rounding You don’t mind keeping track of the decimal point You don’t mind the inconvenience and cost of not using a primitive type Disadvantages to using BigDecimal Less convenient than […]

Item 59: Know and use the libraries

The takeaway from this section is “Don’t reinvent the wheel!”. The author explains the pitfalls of most developers fall into by giving random number generation example. Check the library before you try an ad hoc solution. By using a standard library, you take advantage of the knowledge of the experts who wrote it and the […]

Item 58: Prefer for-each loops to traditional for loops

Traditional for loop distracts the programmer because of index variables. It gives you many chances to use the wrong variable. for-each loop hides the iterator or index variable. There are some cases that you do need to use an ordinary for loop. For instance, you want to replace the value of a list while you iterate a […]

Item 57: Minimize the scope of local variables

Declare the variable where it is first usedThe reader will not be distracted to figure out where the variable is declared Prefer for loops to while loops, assuming the contents of the loop variable aren’t needed after the loop terminates. Advantages of for lops over while loops Eliminate copy-paste errors Shorter and more readable Declare […]