tag:blogger.com,1999:blog-77037350189513060322024-03-16T06:40:06.318+05:30Java JazzleA java blog with a collection of examples and tutorials on Java and related technologies. (Under maintenance with continuous updates)
Be in touch with java jazzle or k2java.blogspot.com.Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.comBlogger1306125tag:blogger.com,1999:blog-7703735018951306032.post-51674245062847105132013-10-14T16:14:00.001+05:302013-10-14T16:15:59.097+05:30Notes of “Effective Java” (Chapter 7-11)<div dir="ltr" style="text-align: left;" trbidi="on">
<b>Item 37: Use marker interfaces to define types</b><br />
Marker interface contains no method declarations, which indicates
some property or features. The typical marker interface is Serialize
interface.<br />
<b>Item 38: Check parameters for validity</b><br />
Check and restrict the parameters of functions.<br />
<ul>
<li>Throw Exception</li>
<li>Assert</li>
</ul>
<b>Item 39: Make defensive copies when needed</b><br />
In general, if a class has mutable components that it gets from or
returns to its clients, the class must defensively copy these
components.<br />
Defensive copy usually implemented by:<br />
<ul>
<li>clone() method</li>
<li>copy constructor</li>
<li>static factory</li>
</ul>
This is not mandatory. If the class trusts the clients, then
defensive copy could be replaced by documentation explanation to save
the cost.<br />
<span id="more-154"></span><br />
<b>Item 40: Design method signatures carefully</b><br />
Avoid long parameter lists. Divide them to several methods or use helper method and helper class.<br />
Favor interfaces over classes.<br />
Prefer two-element enum types to boolean parameters for clearness and extendability.<br />
<b>Item 41: Use overloading judiciously</b><br />
Selection among overloaded methods is static (at the compile time), while selection among overridden methods is dynamic.<br />
Refrain using of overloading methods with same number of parameters.<br />
If you can not avoid that, try avoiding parameters that can be passed to different overloadings by casts.<br />
<b>Item 42: Use varargs judiciously</b><br />
Do not use varargs unless you really need it and benefit from it.<br />
Varargs is expensive in resources.<br />
Arrays.asList() is tricky. It returns List<Integer> when the
argument is Integer[] and returns List<int[]> when the argument is
int[].<br />
<b>Item 43: Return empty arrays or collections, not nulls</b><br />
Returning null requires extra judgement in the client side.<br />
Use new Object1[0] for arrays and emptyList(), emptySet() and emptyMap() for containers.<br />
<b>Item 44: Write doc comments for all exposed API elements</b><br />
@param tag for the parameters. @return for return values. @throws for exception may throw.<br />
Care the HTML metacharacters in doc comments.<br />
Write succinct and nice comment as the summary description in the beginning.<br />
For methods and constructors: verb phrase .<br />
<ul>
<li>Returns the number of elements in this collection.</li>
</ul>
For classes, interfaces, and fields: noun phrase.<br />
<ul>
<li>A task that can be scheduled for one-time or repeated execution by a Timer.</li>
</ul>
Document generic types and constants.<br />
<b>Item 45: Minimize the scope of local variables</b><br />
Minimize the scope of a local variable by declaring it where it is first used.<br />
Prefer for loops to while loops.<br />
<b>Item 46: Prefer for-each loops to traditional for loops</b><br />
Use the for each loops to iterate the arrays.<br />
Exception:<br />
<ol>
<li>you need to remove the elements.</li>
<li>you need to change the value of elements.</li>
<li>special control for the pace of iteration.</li>
</ol>
<b>Item 47: Know and use the libraries</b><br />
Be familiar with the contents of java.lang, java.util, and, to a lesser extent, java.io.<br />
<b>Item 48: Avoid float and double if exact answers are required</b><br />
Use the BigDecimal or int or long instead.<br />
int for number with less than 9 digits and long for 19 digits.<br />
<b>Item 49: Prefer primitive types to boxed primitives</b><br />
“==” operation to mixture of primitive and boxed primitive compares the reference identity but not value.<br />
Use autoboxing carefully.<br />
<b>Item 50: Avoid strings where other types are more appropriate</b><br />
Do not use string type in everywhere.<br />
<b>Item 51: Beware the performance of string concatenation</b><br />
Use append() of StringBuilder instead.<br />
<b>Item 52: Refer to objects by their interfaces</b><br />
Using interface as parameter type make the program more flexible.<br />
List<Subscriber> subscribers = new Vector<Subscriber>();<br />
List<Subscriber> subscribers = new ArrayList<Subscriber>();<br />
<b>Item 53: Prefer interfaces to reflection</b><br />
Reflection loses all information of complile-time check.<br />
Reflection is only used at design time.<br />
When using the class unknown at compile time, try to only instantiate
them by reflection. Access fields and call methods using interfaces or
superclasses.<br />
<b>Item 54: Use native methods judiciously </b><br />
Avoid using native code unless you really need it.<br />
<b>Item 55: Optimize judiciously</b><br />
Weshould forget about small efficiencies, say about 97% of the time:
prema-ture optimization is the root of all evil. –Donald E. Knuth.<br />
Write good programs but not fast programs.<br />
<b>Item 56: Adhere to generally accepted naming conventions</b><br />
Generally, follow The Java Language Specification as conventions.<br />
<i>Package </i> com.google.inject, org.joda.time.format<br />
<i>Class or Interface</i> Timer, FutureTask, LinkedHashMap, HttpServlet<br />
<i>Method or Field</i> remove, ensureCapacity, getCrc<br />
<i>Constant Field</i> MIN_VALUE, NEGATIVE_INFINITY<br />
<i>Local Variable </i> i, xref, houseNumber<br />
<i>Type Parameter</i> T, E, K, V, X, T1, T2<br />
<b>Item 57: Use exceptions only for exceptional conditions</b><br />
Do not use the exception for control flow, exception is designed for exceptional condition.<br />
<b>Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors</b><br />
Checked exception is used in recoverable case. For that, it need to
provide information or methods to help the caller to recover.<br />
<b>Item 59: Avoid unnecessary use of checked exceptions</b><br />
Avoid using the checked exception unless:<br />
<ul>
<li>the exception can not avoided by proper use of API.</li>
<li>Handling exception brings benefits.</li>
</ul>
<b>Item 60: Favor the use of standard exceptions</b><br />
Some commonly used exceptions:<br />
IllegalArgumentException: Non-null parameter value is inappropriate<br />
IllegalStateException: Object state is inappropriate for method invocation<br />
NullPointerException: Parameter value is null where prohibited<br />
IndexOutOfBoundsException: Index parameter value is out of range<br />
ConcurrentModificationException: Concurrent modification of an object has been detected where it is prohibited<br />
UnsupportedOperationException: Object does not support method<br />
<b>Item 61: Throw exceptions appropriate to the abstraction</b><br />
If it is impossible to prevent the occurring of exception in lower
level, propagate it to higher level by catching and rethrowing.<br />
Try to log the exception information if detailed information is needed.<br />
<b>Item 62: Document all exceptions thrown by each method</b><br />
Document the exceptions by Javadoc @throws tag. Do not “throws” unchecked exceptions.<br />
<b>Item 63: Include failure-capture information in detail messages</b><br />
Include failure-capture information in checked exceptions. Those information is useful in recovering from failure.<br />
<b>Item 64: Strive for failure atomicity</b><br />
Any generated exception should leave the object in the same state it was in prior to the method invocation.<br />
Example:<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_66213">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
<div class="line number5 index4 alt2">
5</div>
<div class="line number6 index5 alt1">
6</div>
<div class="line number7 index6 alt2">
7</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java keyword">public</code> <code class="java plain">Object pop() {</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">if</code> <code class="java plain">(size == </code><code class="java value">0</code><code class="java plain">)</code></div>
<div class="line number3 index2 alt2">
<code class="java keyword">throw</code> <code class="java keyword">new</code> <code class="java plain">EmptyStackException();</code></div>
<div class="line number4 index3 alt1">
<code class="java plain">Object result = elements[--size];</code></div>
<div class="line number5 index4 alt2">
<code class="java plain">elements[size] = </code><code class="java keyword">null</code><code class="java plain">; </code><code class="java comments">// Eliminate obsolete reference</code></div>
<div class="line number6 index5 alt1">
<code class="java keyword">return</code> <code class="java plain">result;</code></div>
<div class="line number7 index6 alt2">
<code class="java plain">}</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
Do not try to maintain the failure atomicity when throwing errors.<br />
<b>Item 65: Don’t ignore exceptions</b><br />
Do not use empty catch block to ignore the exception. Throw it outward at least if you do not know how to handle it.<br />
<b>Item 66: Synchronize access to shared mutable data</b><br />
Synchronization includes two parts: mutual exclusion and
visibility. Without synchronization, one thread’s changes might not be
visible to other threads.<br />
Do not use Thread.stop as it is depreciated.<br />
Synchronization has no effect unless both read and write operations are synchronized.<br />
Volatile and Atomic types should be carefully used.<br />
<b>Item 67: Avoid excessive synchronization</b><br />
Do not call alien methods in synchronized block. Doing this is uncontrollable and may cause exceptions and deadlock.<br />
Use concurrent containers like CopyOnWriteArrayList to separate the
data writing and reading. This is particularly useful to the situation
in which writing data is happened occasionally.<br />
In a multicore world, the real cost of excessive synchronization is
not the CPU time spent obtaining locks; it is the lost opportunities for
parallelism and the delays imposed by the need to ensure that every
core has a consistent view of memory.<br />
Do not synchronize the class internally unless you have good reason.<br />
<b>Item 68: Prefer executors and tasks to threads</b><br />
Executor framework separate the task and mechanism of executing. So use executors prior to Thread.<br />
Using Executors.newFixedThreadPool under heavy loading situations.<br />
Using ScheduledThreadPoolExecutor prior to Timer when multiple timing tasked are required.<br />
<b>Item 68: Prefer executors and tasks to threads</b><br />
The higher-level utilities in java.util.concurrent fall into three
categories:the Executor Framework, concurrent collections; and
synchronizers.<br />
Utilities in the concurrent library should be considered first before wait() and notify().<br />
Use ConcurrentHashMap in preference to Collections.synchronizedMap or Hashtable.<br />
Common synchronizers include CyclicBarrier, CountdownLatch and Semaphore.<br />
<b>Item 70: Document thread safety</b><br />
The presence of the synchronized modifierin a method declaration is an implementation detail, not a part of its exported API.<br />
To enable safe concurrent use, a class must clearly document what level of thread safety it supports.<br />
levels of thread safety:<br />
<ul>
<li>immutable</li>
<li>unconditionally thread-safe</li>
<li>conditionally thread-safe</li>
<li>not thread-safe</li>
</ul>
<b>Item 71: Use lazy initialization judiciously</b><br />
Lazy initialization decreases the cost of initializing a class or
creating an instance, at the expense of increasing the cost of accessing
the lazily initialized field. It may be worthwhile when only part of
instances will be initialized in practice.<br />
Use a synchronized accessor to the getfield method to ensure the concurrency.<br />
Use the lazy initialization holder class idiom for static field.<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_886758">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
<div class="line number5 index4 alt2">
5</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java comments">// Lazy initialization holder class idiom for static fields</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">private</code> <code class="java keyword">static</code> <code class="java keyword">class</code> <code class="java plain">FieldHolder {</code></div>
<div class="line number3 index2 alt2">
<code class="java keyword">static</code> <code class="java keyword">final</code> <code class="java plain">FieldType field = computeFieldValue();</code></div>
<div class="line number4 index3 alt1">
<code class="java plain">}</code></div>
<div class="line number5 index4 alt2">
<code class="java keyword">static</code> <code class="java plain">FieldType getField() { </code><code class="java keyword">return</code> <code class="java plain">FieldHolder.field; }</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
Use the double-check idiom for instance field.<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_669857">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
<div class="line number5 index4 alt2">
5</div>
<div class="line number6 index5 alt1">
6</div>
<div class="line number7 index6 alt2">
7</div>
<div class="line number8 index7 alt1">
8</div>
<div class="line number9 index8 alt2">
9</div>
<div class="line number10 index9 alt1">
10</div>
<div class="line number11 index10 alt2">
11</div>
<div class="line number12 index11 alt1">
12</div>
<div class="line number13 index12 alt2">
13</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java comments">// Double-check idiom for lazy initialization of instance fields</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">private</code> <code class="java keyword">volatile</code> <code class="java plain">FieldType field;</code></div>
<div class="line number3 index2 alt2">
<code class="java plain">FieldType getField() {</code></div>
<div class="line number4 index3 alt1">
<code class="java plain">FieldType result = field;</code></div>
<div class="line number5 index4 alt2">
<code class="java keyword">if</code> <code class="java plain">(result == </code><code class="java keyword">null</code><code class="java plain">) { </code><code class="java comments">// First check (no locking)</code></div>
<div class="line number6 index5 alt1">
<code class="java keyword">synchronized</code><code class="java plain">(</code><code class="java keyword">this</code><code class="java plain">) {</code></div>
<div class="line number7 index6 alt2">
<code class="java plain">result = field;</code></div>
<div class="line number8 index7 alt1">
<code class="java keyword">if</code> <code class="java plain">(result == </code><code class="java keyword">null</code><code class="java plain">) </code><code class="java comments">// Second check (with locking)</code></div>
<div class="line number9 index8 alt2">
<code class="java plain">field = result = computeFieldValue();</code></div>
<div class="line number10 index9 alt1">
<code class="java plain">}</code></div>
<div class="line number11 index10 alt2">
<code class="java plain">}</code></div>
<div class="line number12 index11 alt1">
<code class="java keyword">return</code> <code class="java plain">result;</code></div>
<div class="line number13 index12 alt2">
<code class="java plain">}</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
<b>Item 72: Don’t depend on the thread scheduler</b><br />
Do not rely on scheduler for correctness of program.<br />
Do not let the thread busy-wait.<br />
Use Thread.sleep(1) instead of Thread.yield() for increasing concurrency.<br />
<b>Item 73: Avoid thread groups</b><br />
Thread groups are obsolete.<br />
<b>Item 74: Implement Serializable judiciously</b><br />
Long term cost of implementing Serializable include:<br />
Decreases the flexi-bility to change a class’s implementation once it has been released.<br />
Increase the likelihood of bug and security holes.<br />
Increase the burden of testing.<br />
Classes designed for inheritance should rarely implement Serializable, and interfaces should rarely extend it.<br />
Exceptions: Throwable, Component, and HttpServlet, etc.<br />
<b>Item 75: Consider using a custom serialized form</b><br />
Use the default serialized form only when an object’s phys-ical representation is identical to its logical content.<br />
Disadvantages of inappropriate default serialized form:<br />
<ul>
<li>permanently ties the exported API to the current internal representation.</li>
<li>consume excessive space.</li>
<li>consume excessive time (graph traversal).</li>
<li>stack overflow.</li>
</ul>
Provide writeObject and readOb-ject methods implementing this
serialized form. The transient modifier indicates that an instance
field is to be omitted from a class’s default serialized form.<br />
Before deciding to make a field nontransient, convince yourself that its value is part of the logical state of the object.<br />
Declare an explicit serial version UID in every serializable class you write, to tackle the version problem.<br />
<b>Item 76: Write readObject methods defensively</b><br />
Make defensive copy of fields in readObject() method is necessary like in the constructor.<br />
For classes with object reference fields that must remain private, defensively copy each object in such a field.<br />
Check any invariants and throw an InvalidObjectException if a check fails.<br />
Do not invoke any overridable methods in the constructor or readObject() method.<br />
<b>Item 77: For instance control, prefer enum types to readResolve</b><br />
The instance control (e.g, Singleton) is violated without readResolve() method after serialization.<br />
All instance fields with object reference types must be
declared transient if using the readResolve() to do the instance
control.<br />
Instance control through Enum is preferred to the readResolve().<br />
<b>Item 78: Consider serialization proxies instead of serialized instances</b><br />
Serialization proxy pattern is implemented based on an inner static class with a single constructor.<br />
Use writeReplace() of enclosing class to write a proxy instance instead of the instance of enclosing class.<br />
Use readResolve() method to return a instance of enclosing class at
the time of deserialization, since the method in the inner class is able
to call the constructor of enclosing class.<br />
Two limitations of the serialization proxy pattern:<br />
It is not compatible with classes that are extendable by their
clients (in that time, the enclosing class has not been initialized).<br />
It is not compatible with some classes whose object graphs contain circularities.<br />
Serialization proxy pattern is more secure, but with higher expense.<br />
<br />
<a href="http://raysear.wordpress.com/2012/02/28/notes-of-effective-java-chapter-7-11/"><b>Source</b></a> </div>
Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-48077558655204182792013-10-14T16:13:00.001+05:302013-10-14T16:15:35.597+05:30Notes of “Effective Java” (Chapter 1-6)<div dir="ltr" style="text-align: left;" trbidi="on">
<b>Item 1: Consider static factory methods instead of constructors</b><br />
advantage:<br />
<ol>
<li>Customized meaningful names better than constructors.</li>
<li>Associated with class instead of creating new objects.</li>
<li>Able to return subtypes.</li>
</ol>
For the 2nd advantage, static factory methods form the basis of
Service provider Framework including service interface, provider
interface, provider registration API and service access API.<br />
<b>Item 2: Consider a builder when faced with many constructor </b><b>parameters</b><br />
Compare with telescoping constructors and JavaBean Style.<br />
Builder is set as a static inner class. Builder makes the object initialized immutable.<br />
<span id="more-82"></span><br />
<b>Item 3: Enforce the singleton property with a private constructor or an enum type</b><br />
Three ways to implement Singleton patter:<br />
<ul>
<li>Public field</li>
<li>Static factory method</li>
<li>Enum Singleton</li>
</ul>
Without Enum, readResovle() function needs to be added to avoid creating spurious instances when doing serialization.<br />
<b>Item 4: Enforce noninstantiability with a private constructor</b><br />
Some utility classes like java.lang.Math or java.util.Arrays are not
designed to be instantiated. For preventing them from instantiation and
subclassing, make the constructor to be private.<br />
<b>Item 5: Avoid creating unnecessary objects</b><br />
Creating new object especially heavy objects is expensive. Therefore, reusing object always increases efficiency.<br />
Example: String appending, Boxed primitives.<br />
<b>Item 6: Eliminate obsolete object references</b><br />
Although Java has garbage collector, memory leak can still happen. GC
reclaims the memory by inspecting the references of objects.<br />
Therefore, we need to null out the obsolete object references to release the unused object memory.<br />
Common memory leak scenarios: Objects constructed inside classes, Cache, Callbacks.<br />
Notice the Weak references and weakHashmap.<br />
<b>Item 7: Avoid finalizers</b><br />
In summary, don’t use finalizers except as a safety net or to
terminate noncritical native resources. In those rare instances where
you do use a finalizer, remember to invoke super.finalize.<br />
Explicit termination inside a “try finally” is preferable and reliable.<br />
<b>Item 8: Obey the general contract when overriding equals</b><br />
Conditions do not need overriding equals():<br />
<ol>
<li>Instances are distinguished by reference.</li>
<li>Equals() defined in superclass works.</li>
<li>You do not care the equals() function.</li>
</ol>
Contract when overriding equals():<br />
Reflexive, Symmetric, Transitive, Consistent.<br />
There is no perfect way to override equals() between the subclasses with additional value components and superclasses.<br />
Notice the @Override annotation.<br />
<b>Item 9: Always override hashCode when you override equals</b><br />
Principle: equal objects according the equals() function must produce the same hashcode.<br />
General recipe for hashCode():<br />
result = 31 * result + c;<br />
<ul>
<li>boolean: (f?1:0).</li>
<li> byte, char, short, or int: (int) f</li>
<li>long: (int) (f ^ (f >>> 32))</li>
<li>float: Float.floatToIntBits(f)</li>
<li>double: Double.doubleToLongBits(f)</li>
<li> null: 0</li>
</ul>
Note we could lazily initialize the hashCode value.<br />
<b>Item 10: Always override toString</b><br />
Faciliate the class client user by giving useful information in string.<br />
<b>Item 11: Override clone judiciously</b><br />
Once one class implements the Cloneable interface and overrides the
clone() method, invoking super.clone() will return a field-to-field copy
of this class object in which the method is called. If a class contains
only primitive fields or references to immutable objects, then it is
usually the case that no fields in the object returned by <tt>super.clone</tt> need to be modified. Otherwise, deep copy is needed.<br />
Be careful to use clone except for arrays. Usually it is better to use copy constructor and copy factory method.<br />
<ul>
<li>public Yum(Yum yum);</li>
<li>public static Yum newInstance(Yum yum);</li>
</ul>
<b>Item 12: Consider implementing Comparable</b><br />
<div>
<div class="syntaxhighlighter java" id="highlighter_525905">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java keyword">public</code> <code class="java keyword">interface</code> <code class="java plain">Comparable<T> {</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">int</code> <code class="java plain">compareTo(T t);</code></div>
<div class="line number3 index2 alt2">
<code class="java plain">}</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
Classes that depend on comparison include the sorted collections
TreeSet and TreeMap, and the utility classes Collections and Arrays,
which contain searching and sorting algorithms. General interfaces like
Set, Map, and Collection depend on equals() method.<br />
Principle:<br />
If the most significant fields are equal, go on to compare the
next-most-significant fields, and so on. If all fields are equal,
the objects are equal; return zero.<br />
<b>Item 13: Minimize the accessibility of classes and members</b><br />
The rule of thumb is simple: make each class or member as inaccessible as possible.<br />
Exported API: public, protected.<br />
If a method overrides a superclass method, it is not permitted to
have a lower access level in the subclass than it does in the
superclass. This is necessary to ensure that an instance of the subclass
is usable anywhere that an instance of the superclass is usable. A
special case of this rule is that if a class implements an interface,
all of the class methods that are also present in the interface must be
declared public. This is so because all members of an interface are
implicitly public.<br />
<ul>
<li>Instance fields should never be public</li>
<li>Classes with public mutable fields are not thread-safe</li>
<li>Public static final fields should be only used for constants</li>
</ul>
<b>Item 14: In public classes, use accessor methods, not public fields</b><br />
Class is package-private or is a private nested class, there is nothing inherently wrong with exposing its data fields.<br />
<b>Item 15: Minimize mutability</b><br />
<ol>
<li>Make the immutable class to be final.</li>
<li>Immutable objects are inherently thread-safe; they require no synchroni-zation.</li>
<li>Use companion class such as StringBuilder replacing String for performance.</li>
<li>Static factory is a good way for immutable class.</li>
<li>Classes should be immutable unless there’s a very good reason to make them mutable.</li>
<li>Make every field final unless there is a compelling reason to make it nonfinal.</li>
<li>Don’t provide a public initialization method separate from the
constructor or static factory unless there is a compelling reason to do
so.</li>
</ol>
<b>Item 16: Favor composition over inheritance</b><br />
For most cases, composition is better than inheritance.<br />
The keyword “super” is for calling overrided methods or
constructors in superclass. The invocation in super.method() still calls
the override methods but not overriden methods.<br />
<b>Item 17: Design and document for inheritance or else prohibit it</b><br />
<ul>
<li>The class must document or simply prohibit its self-use of overridable methods.</li>
<li>Constructors must not invoke overridable methods.</li>
<li>Neither clone() nor readObject() may invoke an overridable method, directly or indirectly, as they behave like constructors.</li>
<li>Prohibit subclassing in classes that are not designed and documented
to be safely subclassed by “final” or making the constructor “private”.</li>
</ul>
<b>Item 18: Prefer interfaces to abstract classes</b><br />
Interface is generally the better way to define a type that permits multiple implementations.<br />
Abstract class and Interface can be combined to generate skeletal
implementation, such as AbstractCollection, AbstractSet, AbstractList.<br />
<b>Item 19: Use interfaces only to define types</b><br />
Interfaces should only used to define type, representing some classes in hierarchy.<br />
Enum and Utility class are more appropriate for defining constants.<br />
<b>Item 20: Prefer class hierarchies to tagged classes</b><br />
Tagged classes are cluttered with tag fields, and switch
statements, messing the encapsulation and being prone to run-time
errors.<br />
Tagged class should be abandoned and replaced by abstract classes.<br />
<b>Item 21: Use function objects to represent strategies</b><br />
Features like function pointers, delegates, lambda expressions call functions in functions.<br />
Strategy pattern is built on these features typically on function pointers.<br />
Function pointers is not supported in java. However, it can be
emulated by a concrete class with only one method, as a “concrete
strategy class”.<br />
<ul>
<li>Strategy ==> Interface</li>
<li>Concrete strategy ==> Concrete class implementing the interface</li>
</ul>
Usually the concrete class is used as anonymous class. For class used
repeatedly, singleton pattern is applied to the concrete class with one
static and final instance.<br />
<b>Item 22: Favor static member classes over nonstatic</b><br />
Four kinds of nested classes: static member classes, nonstatic member classes, anonymous classes, and local classes.<br />
It is impossible to create an instance of a nonstatic member class without an enclosing instance.<br />
Declare a member class that does not require access to an enclosing instance, always make it to be static.<br />
Three common uses of anonymous classes:<br />
<ol>
<li>function objects</li>
<li>process objects, such asRunnable, Thread</li>
<li>static factory methods</li>
</ol>
<b>Item 23: Don’t use raw types in new code</b><br />
<ul>
<li>Do not use raw type to define variable, as the compiler will not
check the type of parameters and it loses the type safety and may
generate run-time error.</li>
<li>Generics like List<Object> can contain any arbitrary types but still with type safety.</li>
<li>Unbounded wildcard types like List<?> is capable to hold one of any type of element with type safety.</li>
<li>Generic type information is erased at runtime</li>
</ul>
<b>Item 24: Eliminate unchecked warnings</b><br />
Try to eliminate the unchecked warning, including:<br />
<ul>
<li>unchecked cast warnings</li>
<li>unchecked method invocation warnings</li>
<li>unchecked generic array creation warnings</li>
<li>unchecked conversion warnings</li>
</ul>
Suppress the warning with an @SuppressWarnings(“unchecked”) annotation in narrowest scope if you are sure about the type safety.<br />
<b>Item 25: Prefer lists to arrays</b><br />
Arrays are covariant and reifiable. Generics are invariant and erased in run-time.<br />
Arrays provide runtime type safety but not compile-time type safety and vice versa for generics.<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_909565">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java comments">// Fails at runtime!</code></div>
<div class="line number2 index1 alt1">
<code class="java plain">Object[] objectArray = </code><code class="java keyword">new</code> <code class="java plain">Long[</code><code class="java value">1</code><code class="java plain">];</code></div>
<div class="line number3 index2 alt2">
<code class="java plain">objectArray[</code><code class="java value">0</code><code class="java plain">] = </code><code class="java string">"I don't fit in"</code><code class="java plain">; </code><code class="java comments">// Throws ArrayStoreException</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
<div>
<div class="syntaxhighlighter java" id="highlighter_555985">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java comments">// Won't compile!</code></div>
<div class="line number2 index1 alt1">
<code class="java plain">List<Object> ol = </code><code class="java keyword">new</code> <code class="java plain">ArrayList<Long>(); </code><code class="java comments">// Incompatible types</code></div>
<div class="line number3 index2 alt2">
<code class="java plain">ol.add(</code><code class="java string">"I don't fit in"</code><code class="java plain">);</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
Generics enforce their type constraints only at compile time and discard (or erase) their element type information at runtime.<br />
it is illegal to create an array of a generic type such as “new List<String>[]” and “new List<E>[]“.<br />
Non-reifiable type is one whose runtime representation contains less information than its compile-time representa-tion.<br />
Casts to arrays of non-reifiable types should be used only under special circumstances. A better solution is to use list.<br />
<b>Item 26: Favor generic types</b><br />
Generics are safer. Suppress the warning when casting.<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_560389">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java color1">@SuppressWarnings</code><code class="java plain">(</code><code class="java string">"unchecked"</code><code class="java plain">)</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">public</code> <code class="java plain">Stack() {</code></div>
<div class="line number3 index2 alt2">
<code class="java plain">elements = (E[]) </code><code class="java keyword">new</code> <code class="java plain">Object[DEFAULT_INITIAL_CAPACITY];</code></div>
<div class="line number4 index3 alt1">
<code class="java plain">}</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
<b>Item 27: Favor generic methods</b><br />
Generic singleton factory:<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_302006">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
<div class="line number5 index4 alt2">
5</div>
<div class="line number6 index5 alt1">
6</div>
<div class="line number7 index6 alt2">
7</div>
<div class="line number8 index7 alt1">
8</div>
<div class="line number9 index8 alt2">
9</div>
<div class="line number10 index9 alt1">
10</div>
<div class="line number11 index10 alt2">
11</div>
<div class="line number12 index11 alt1">
12</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java comments">// Generic singleton factory pattern</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">private</code> <code class="java keyword">static</code> <code class="java plain">UnaryFunction<Object> IDENTITY_FUNCTION =</code></div>
<div class="line number3 index2 alt2">
<code class="java keyword">new</code> <code class="java plain">UnaryFunction<Object>()</code></div>
<div class="line number4 index3 alt1">
<code class="java plain">{</code></div>
<div class="line number5 index4 alt2">
<code class="java keyword">public</code> <code class="java plain">Object apply(Object arg) { </code><code class="java keyword">return</code> <code class="java plain">arg; }</code></div>
<div class="line number6 index5 alt1">
<code class="java plain">};</code></div>
<div class="line number7 index6 alt2">
<code class="java comments">// IDENTITY_FUNCTION is stateless and its type parameter is</code></div>
<div class="line number8 index7 alt1">
<code class="java comments">// unbounded so it's safe to share one instance across all types.</code></div>
<div class="line number9 index8 alt2">
<code class="java color1">@SuppressWarnings</code><code class="java plain">(</code><code class="java string">"unchecked"</code><code class="java plain">)</code></div>
<div class="line number10 index9 alt1">
<code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain"><T> UnaryFunction<T> identityFunction() {</code></div>
<div class="line number11 index10 alt2">
<code class="java keyword">return</code> <code class="java plain">(UnaryFunction<T>) IDENTITY_FUNCTION;</code></div>
<div class="line number12 index11 alt1">
<code class="java plain">}</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
Recursive type bound is usually used for Comparable<T>.<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_982658">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
<div class="line number5 index4 alt2">
5</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java keyword">public</code> <code class="java keyword">interface</code> <code class="java plain">Comparable<T>; {</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">int</code> <code class="java plain">compareTo(T o);</code></div>
<div class="line number3 index2 alt2">
<code class="java plain">}</code></div>
<div class="line number4 index3 alt1">
<code class="java comments">// Using a recursive type bound to express mutual comparability</code></div>
<div class="line number5 index4 alt2">
<code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain"><T </code><code class="java keyword">extends</code> <code class="java plain">Comparable<T>> T max(List<T> list) {...}</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
<b>Item 28: Use bounded wildcards to increase API flexibility</b><br />
Producer-extends, consumer-super(PECS)<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_303671">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
<div class="line number5 index4 alt2">
5</div>
<div class="line number6 index5 alt1">
6</div>
<div class="line number7 index6 alt2">
7</div>
<div class="line number8 index7 alt1">
8</div>
<div class="line number9 index8 alt2">
9</div>
<div class="line number10 index9 alt1">
10</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java comments">// Wildcard type for parameter that serves as an E producer</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">pushAll(Iterable<? </code><code class="java keyword">extends</code> <code class="java plain">E> src) {</code></div>
<div class="line number3 index2 alt2">
<code class="java keyword">for</code> <code class="java plain">(E e : src)</code></div>
<div class="line number4 index3 alt1">
<code class="java plain">push(e);</code></div>
<div class="line number5 index4 alt2">
<code class="java plain">}</code></div>
<div class="line number6 index5 alt1">
<code class="java comments">// Wildcard type for parameter that serves as an E consumer</code></div>
<div class="line number7 index6 alt2">
<code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">popAll(Collection<? </code><code class="java keyword">super</code> <code class="java plain">E> dst) {</code></div>
<div class="line number8 index7 alt1">
<code class="java keyword">while</code> <code class="java plain">(!isEmpty())</code></div>
<div class="line number9 index8 alt2">
<code class="java plain">dst.add(pop());</code></div>
<div class="line number10 index9 alt1">
<code class="java plain">}</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
Do not use wildcard types as return types. Rather than providing
additional flexibility for your users, it would force them to use
wildcard types in client code.<br />
Always use Comparable<? super T> in preference to
Comparable<T>, since the type may implements the Comparable
interface as an subinterface.<br />
If a type parameter appears only once in a method declaration, replace it with a wildcard.<br />
Can’t put any value except null into a List<?>, which means List of some particular type.<br />
<b>Item 29: Consider typesafe heterogeneous containers</b><br />
Place the type parameter on the key rather than the container to enable the container to include different types.<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_461400">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
<div class="line number5 index4 alt2">
5</div>
<div class="line number6 index5 alt1">
6</div>
<div class="line number7 index6 alt2">
7</div>
<div class="line number8 index7 alt1">
8</div>
<div class="line number9 index8 alt2">
9</div>
<div class="line number10 index9 alt1">
10</div>
<div class="line number11 index10 alt2">
11</div>
<div class="line number12 index11 alt1">
12</div>
<div class="line number13 index12 alt2">
13</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java comments">// Typesafe heterogeneous container pattern - implementation</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">Favorites {</code></div>
<div class="line number3 index2 alt2">
<code class="java keyword">private</code> <code class="java plain">Map<Class<?>, Object> favorites =</code></div>
<div class="line number4 index3 alt1">
<code class="java keyword">new</code> <code class="java plain">HashMap<Class<?>, Object>();</code></div>
<div class="line number5 index4 alt2">
<code class="java keyword">public</code> <code class="java plain"><T> </code><code class="java keyword">void</code> <code class="java plain">putFavorite(Class<T> type, T instance) {</code></div>
<div class="line number6 index5 alt1">
<code class="java keyword">if</code> <code class="java plain">(type == </code><code class="java keyword">null</code><code class="java plain">)</code></div>
<div class="line number7 index6 alt2">
<code class="java keyword">throw</code> <code class="java keyword">new</code> <code class="java plain">NullPointerException(</code><code class="java string">"Type is null"</code><code class="java plain">);</code></div>
<div class="line number8 index7 alt1">
<code class="java plain">favorites.put(type, instance);</code></div>
<div class="line number9 index8 alt2">
<code class="java plain">}</code></div>
<div class="line number10 index9 alt1">
<code class="java keyword">public</code> <code class="java plain"><T> T getFavorite(Class<T> type) {</code></div>
<div class="line number11 index10 alt2">
<code class="java keyword">return</code> <code class="java plain">type.cast(favorites.get(type));</code></div>
<div class="line number12 index11 alt1">
<code class="java plain">}</code></div>
<div class="line number13 index12 alt2">
<code class="java plain">}</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
<b>Item 30: Use enums instead of int constants</b><br />
Java’s enum types are full-fledged classes.<br />
Enums provide high-quality implementations of all the Object methods, Comparable and Serializable.<br />
Enums can also add methods or fields.<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_255856">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
<div class="line number5 index4 alt2">
5</div>
<div class="line number6 index5 alt1">
6</div>
<div class="line number7 index6 alt2">
7</div>
<div class="line number8 index7 alt1">
8</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java comments">// Enum type with constant-specific method implementations</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">public</code> <code class="java keyword">enum</code> <code class="java plain">Operation {</code></div>
<div class="line number3 index2 alt2">
<code class="java plain">PLUS { </code><code class="java keyword">double</code> <code class="java plain">apply(</code><code class="java keyword">double</code> <code class="java plain">x, </code><code class="java keyword">double</code> <code class="java plain">y){</code><code class="java keyword">return</code> <code class="java plain">x + y;} },</code></div>
<div class="line number4 index3 alt1">
<code class="java plain">MINUS { </code><code class="java keyword">double</code> <code class="java plain">apply(</code><code class="java keyword">double</code> <code class="java plain">x, </code><code class="java keyword">double</code> <code class="java plain">y){</code><code class="java keyword">return</code> <code class="java plain">x - y;} },</code></div>
<div class="line number5 index4 alt2">
<code class="java plain">TIMES { </code><code class="java keyword">double</code> <code class="java plain">apply(</code><code class="java keyword">double</code> <code class="java plain">x, </code><code class="java keyword">double</code> <code class="java plain">y){</code><code class="java keyword">return</code> <code class="java plain">x * y;} },</code></div>
<div class="line number6 index5 alt1">
<code class="java plain">DIVIDE { </code><code class="java keyword">double</code> <code class="java plain">apply(</code><code class="java keyword">double</code> <code class="java plain">x, </code><code class="java keyword">double</code> <code class="java plain">y){</code><code class="java keyword">return</code> <code class="java plain">x / y;} };</code></div>
<div class="line number7 index6 alt2">
<code class="java keyword">abstract</code> <code class="java keyword">double</code> <code class="java plain">apply(</code><code class="java keyword">double</code> <code class="java plain">x, </code><code class="java keyword">double</code> <code class="java plain">y);</code></div>
<div class="line number8 index7 alt1">
<code class="java plain">}</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
ValueOf(String) method can translate a constant’s name into the constant itself.<br />
Consider the strategy enum pattern if multiple enum constants share common behaviors.<br />
<b>Item 31: Use instance fields instead of ordinals</b><br />
Avoid using ordinal() method of enum.<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_941402">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
<div class="line number5 index4 alt2">
5</div>
<div class="line number6 index5 alt1">
6</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java comments">// Abuse of ordinal to derive an associated value - DON'T DO THIS</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">public</code> <code class="java keyword">enum</code> <code class="java plain">Ensemble {</code></div>
<div class="line number3 index2 alt2">
<code class="java plain">SOLO, DUET, TRIO, QUARTET, QUINTET,</code></div>
<div class="line number4 index3 alt1">
<code class="java plain">SEXTET, SEPTET, OCTET, NONET, DECTET;</code></div>
<div class="line number5 index4 alt2">
<code class="java keyword">public</code> <code class="java keyword">int</code> <code class="java plain">numberOfMusicians() { </code><code class="java keyword">return</code> <code class="java plain">ordinal() + </code><code class="java value">1</code><code class="java plain">; }</code></div>
<div class="line number6 index5 alt1">
<code class="java plain">}</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
<b>Item 32: Use EnumSet instead of bit fields</b><br />
Use general Set interface for input type.<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_93951">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
<div class="line number5 index4 alt2">
5</div>
<div class="line number6 index5 alt1">
6</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java comments">// EnumSet - a modern replacement for bit fields</code></div>
<div class="line number2 index1 alt1">
<code class="java keyword">public</code> <code class="java keyword">class</code> <code class="java plain">Text {</code></div>
<div class="line number3 index2 alt2">
<code class="java keyword">public</code> <code class="java keyword">enum</code> <code class="java plain">Style { BOLD, ITALIC, UNDERLINE, STRIKETHROUGH }</code></div>
<div class="line number4 index3 alt1">
<code class="java comments">// Any Set could be passed in, but EnumSet is clearly best</code></div>
<div class="line number5 index4 alt2">
<code class="java keyword">public</code> <code class="java keyword">void</code> <code class="java plain">applyStyles(Set<Style> styles) { ... }</code></div>
<div class="line number6 index5 alt1">
<code class="java plain">}</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
<b>Item 33: Use EnumMap instead of ordinal indexing</b><br />
It is better to use EnumMap to catalog relationship related with Enum type.<br />
<div>
<div class="syntaxhighlighter java" id="highlighter_347353">
<table border="0" cellpadding="0" cellspacing="0"><tbody>
<tr><td class="gutter"><div class="line number1 index0 alt2">
1</div>
<div class="line number2 index1 alt1">
2</div>
<div class="line number3 index2 alt2">
3</div>
<div class="line number4 index3 alt1">
4</div>
<div class="line number5 index4 alt2">
5</div>
<div class="line number6 index5 alt1">
6</div>
<div class="line number7 index6 alt2">
7</div>
<div class="line number8 index7 alt1">
8</div>
</td><td class="code"><div class="container">
<div class="line number1 index0 alt2">
<code class="java comments">// Using an EnumMap to associate data with an enum</code></div>
<div class="line number2 index1 alt1">
<code class="java plain">Map<Herb.Type, Set<Herb>> herbsByType =</code></div>
<div class="line number3 index2 alt2">
<code class="java keyword">new</code> <code class="java plain">EnumMap<Herb.Type, Set<Herb>>(Herb.Type.</code><code class="java keyword">class</code><code class="java plain">);</code></div>
<div class="line number4 index3 alt1">
<code class="java keyword">for</code> <code class="java plain">(Herb.Type t : Herb.Type.values())</code></div>
<div class="line number5 index4 alt2">
<code class="java plain">herbsByType.put(t, </code><code class="java keyword">new</code> <code class="java plain">HashSet<Herb>());</code></div>
<div class="line number6 index5 alt1">
<code class="java keyword">for</code> <code class="java plain">(Herb h : garden)</code></div>
<div class="line number7 index6 alt2">
<code class="java plain">herbsByType.get(h.type).add(h);</code></div>
<div class="line number8 index7 alt1">
<code class="java plain">System.out.println(herbsByType);</code></div>
</div>
</td></tr>
</tbody></table>
</div>
</div>
<b>Item 34: Emulate extensible enums with interfaces</b><br />
In general, extending enums is a bad idea. If you really want to do that, define an interface for expected behaviors.<br />
<b>Item 35: Prefer annotations to naming patterns</b><br />
Annotations do not directly affect program semantics, but they do
affect the way programs are treated by tools and libraries, which can in
turn affect the semantics of the running program. Annotations can be
read from source files, class files, or reflectively at run time.<br />
Annotations complement javadoc tags. In general, if the markup is
intended to affect or produce documentation, it should probably be a
javadoc tag; otherwise, it should be an annotation.<br />
<b>Item 36: Consistently use the Override annotation</b><br />
Use @Override annotation except for the abstract methods or methods of interfaces.<br />
<br />
<a href="http://raysear.wordpress.com/2012/01/30/note-of/"><b>Source</b></a> </div>
Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-7033778211295175002013-07-28T18:07:00.002+05:302013-07-28T18:07:55.544+05:30Javapocalypse video <div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen='allowfullscreen' webkitallowfullscreen='webkitallowfullscreen' mozallowfullscreen='mozallowfullscreen' width='320' height='266' src='https://www.youtube.com/embed/E3418SeWZfQ?feature=player_embedded' frameborder='0'></iframe></div>
<br /></div>
Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-20647157260578316302011-12-27T06:19:00.001+05:302014-04-12T01:15:01.847+05:30Extend Thread vs implement Runnable<div dir="ltr" style="text-align: left;" trbidi="on">
There are two ways to create your own thread type: subclass <code>java.lang.Thread</code> class, or implementing <code>java.lang.Runnable</code> and pass it to <code>Thread</code> constructor or <code>java.util.concurrent.ThreadFactory</code>. What is the difference, and which one is better?<br />
<ol style="text-align: left;">
<li>The practical reason is, a Java class can have only one superclass. So if your thread class extends <code>java.lang.Thread</code>, it cannot inherit from any other classes. This limits how you can reuse your application logic.</li>
<li>From a design point of view, there should be a clean separation between how a task is identified and defined, between how it is executed. The former is the responsibility of a <code>Runnalbe</code> impl, and the latter is job of the <code>Thread</code> class.</li>
<li>A <code>Runnable</code> instance can be passed to other libraries that accept task submission, e.g., <code>java.util.concurrent.Executors</code>. A Thread subclass inherits all the overhead of thread management and is hard to reuse.</li>
<li>Their instances also have different lifecycle. Once a thread is started and completed its work, it's subject to garbage collection. An instance of <code>Runnalbe</code> task can be resubmitted or retried multiple times, though usually new tasks are instantiated for each submission to ease state management.</li>
</ol>
</div>
Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-68068156725439052902011-12-23T00:40:00.000+05:302011-12-31T11:02:11.629+05:30O(n) for operations on Java collections<div dir="ltr" style="text-align: left;" trbidi="on"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2WYoxr8QN_nmp9etMoubf3cbVvAvlmQ-ac7e9imcqWXDu7ARIkyaOUF62nEDNdib6m0vojYaKAINKDVu5WxXoEm79CKLT6eAUCrt8BuZqMyOsHxSx9BMhSLLdl03GK2N1e_qK3ioIbkmj/s1600/collectiononotaion1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2WYoxr8QN_nmp9etMoubf3cbVvAvlmQ-ac7e9imcqWXDu7ARIkyaOUF62nEDNdib6m0vojYaKAINKDVu5WxXoEm79CKLT6eAUCrt8BuZqMyOsHxSx9BMhSLLdl03GK2N1e_qK3ioIbkmj/s320/collectiononotaion1.png" width="287" /></a></div><br />
</div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-68293037339048010422011-12-23T00:35:00.000+05:302011-12-31T11:02:11.651+05:30Collection Interfaces - Java Collection Diagrams<div dir="ltr" style="text-align: left;" trbidi="on"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVjAm-WxdA5h3boaCf_tiBOpiIN-nDhwq1eRXvN2oosjcSupCRZm5hX-e8218DXnyHlyi_mVAzlwKsFRbl9lpCTcdk3WU5PSQmdrrkjQu72zRJCMfh8WEnk2zS02skg8JgkWCZ4bZtkWBt/s1600/java-collection+without+map.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="496" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVjAm-WxdA5h3boaCf_tiBOpiIN-nDhwq1eRXvN2oosjcSupCRZm5hX-e8218DXnyHlyi_mVAzlwKsFRbl9lpCTcdk3WU5PSQmdrrkjQu72zRJCMfh8WEnk2zS02skg8JgkWCZ4bZtkWBt/s640/java-collection+without+map.jpg" width="640" /></a></div><br />
And when we include maps:<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCbsiuYFqUqt05UH7ZwBPkZE6MujIbgbkao2bPvSuUaTttRfe5tRDg1h8SQ-UzYDcjrnH5MUBSyHmZ4NJHxQQXZl0Q5-GYnf1F03f1m76BVzXDYa22usDfrIcIoX5TawzomEYC0KWXL4g/s1600/collections-map.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="242" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCbsiuYFqUqt05UH7ZwBPkZE6MujIbgbkao2bPvSuUaTttRfe5tRDg1h8SQ-UzYDcjrnH5MUBSyHmZ4NJHxQQXZl0Q5-GYnf1F03f1m76BVzXDYa22usDfrIcIoX5TawzomEYC0KWXL4g/s400/collections-map.jpg" width="400" /></a></div><br />
</div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com1tag:blogger.com,1999:blog-7703735018951306032.post-69562979550099301182011-12-23T00:21:00.001+05:302011-12-31T11:02:11.675+05:30Avoid memory leaks using Weak&Soft references<p>Some Java developers believe that there is no such a thing as memory leak in Java (thanks to the fabulous automatic Garbage Collection concept) <p>Some others had met the OutOfMemoryError and understood that the JVM has encountered some memory issue but they are not sure if it’s all about the code or maybe even an OS issue… <p>The<a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/OutOfMemoryError.html"> OutOfMemoryError API docs</a> reveals that it “Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. “ <p>As we know, the JVM has a parameter that represents the maximum heap size(-Xmx), hence we can defiantly try to increase the heap size. yet some code can generate new instances all the time, if those instances are accessible(being referenced by the main program – in a recursive manner) for the entire program life span, then the GC won’t reclaim those instances. hence the heap will keep increasing and eventually a OutOfMemoryError will be thrown <- we call that memory leak. <p>Our job as Java developers is to release references (that are accessible by the main program) that we won’t use in the future. by doing that we are making sure that the GC will reclaim those instances (free the memory that those instances occupying in the heap). <p>In some cases we reference an instance from 2 different roots. one root represent a fast-retrieval space(e.g. HashMap) and the other manages the real lifespan of that instance. Sometimes we would like to remove the reference of that instance from one root and get the other root(fast retrieval) reference removed automatically. <p>We wouldn’t want to do it manually due to the fact that we are not C++ developers and we wouldn’t like to manage the memory manually.. <p><strong>Weak references</strong> <p>In order to solve that we can use <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ref/WeakReference.html">WeakReference.</a> <p>Instances that are being referenced by <strong>only</strong> Weak references will get collected on the next collection! (<a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ref/package-summary.html#reachability">Weakly reachable</a>), in other words those references don’t protect their value from the garbage collector. <p>Hence if we would like to manage the life span of an instance by one reference only, we will use the WeakReference object to create all the other references. <p> ( usage: WeakReference wr = new WeakReference(someObject);) <p>In some apps we would like to add all our existing references to some static list, those references should not be strong, otherwise we would have to clean those references manually, we would add those references to the list using this code. <div id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 8pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> addWeakReference(Object o){<br> refList.add(<span style="color: #0000ff">new</span> WeakReference(o));<br>}<br></pre><br></div><br /><p>since most of the WeakReferences use cases needs a Map data structure, there is an implementation of Map that add a WeakReference automatically for you – <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/WeakHashMap.html">WeakHashMap</a><br /><p><strong>Soft References</strong><br /><p>I saw few implementations of Cache using weak references (e.g. the cache is just a WeakHashMap => the GC is cleaning old objects in the cahce), without WeakReferences naive cache can easily cause memory leaks and therefor weak references might be a solution for that.<br /><p>The main problem is that the GC will clean the cached-object probably and most-likely faster then you need.<br /><p>Soft references solve that, those references are exactly like weak references, yet the GC won’t claim them as fast. we can be sure that the JVM won’t throw an OutOfMemory before it will claim all the soft and weak references!<br /><p>using a<a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ref/SoftReference.html"> soft references</a> in order to cache considered the naive generic cache solution. (poor’s men cache)<br /><p>( usage:SoftReference sr = new SoftReference(someObject);)<br /> Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-81734538449790203482011-12-23T00:11:00.001+05:302013-07-28T18:01:05.034+05:30Java Forever - Official Video <div dir="ltr" style="text-align: left;" trbidi="on">
<iframe allowfullscreen="" frameborder="0" height="315" src="http://www.youtube.com/embed/kLO1djacsfg" width="560"></iframe></div>
Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-28039004218497223492011-12-22T23:58:00.001+05:302011-12-31T11:02:11.718+05:30One java - 2 compilers (Javac and JIT)<p>It seems like that for students there is a lot of confusion regarding how Java/The JVM works because there are TWO compilers involve, so when someone mentions a compiler or the Just In Time compiler some of them would imagine it’s the same one, the Java Compiler.. <p><strong>So how does it really works?</strong> <p>It’s simple.. <p>1) You write Java code (file.java) which compiles to “<a href="http://en.wikipedia.org/wiki/Java_bytecode">bytecode</a>“, this is done using the <strong>‘<a href="http://download.oracle.com/javase/1.4.2/docs/tooldocs/windows/javac.html">javac</a>” </strong>the 1st compiler. <p>It’s well known fact that Java can be written once get compiled and run anywhere (on any platform) which mean that different types of JVM can get installed over any type of platform and read the same good old <a href="http://en.wikipedia.org/wiki/Java_bytecode">byte code</a> <p>2) Upon execution of a Java program (the class file or Jar file that consists of some classes and other resources) the JVM should somehow execute the program and somehow translate it to the specific platform <a href="http://en.wikipedia.org/wiki/Machine_code">machine code</a>. <p>In the first versions of Java, the JVM was a “stupid” interprater that executes byte-code line by line….that was extremely slow…people got mad, there were a lot of “lame-java, awesome c” talks…and the JVM guys got irratated and reinvented the JVM. <p>the “new” JVM initially was available as an add-on for Java 1.2 later it became the default Sun JVM (1.3+). <p>So what did they do? they added a second compiler.. Just In Time compiler(aka JIT).. <p>Instead of interpreting line by line, the <a href="http://en.wikipedia.org/wiki/Just-in-time_compilation">JIT</a> compiler compiles the byte-code to machine-code right after the execution.. <p>Moreover, the <a href="http://en.wikipedia.org/wiki/Java_Virtual_Machine">JVM </a>is getting smarter upon every release, it “knows” when it should interpat the code line-by-line and what parts of the code should get compiled beforehand (still on runtime). <p>It does that by taking real-usage statistics, and a long-list of super-awesome heuristics.. <p>The <a href="http://en.wikipedia.org/wiki/Java_Virtual_Machine">JVM </a>can get configured by the user in order to disable/enable some of those heuristics.. <p><strong>To summarize</strong>, In order to execute java code, you use two different compilers, the first one(<a href="http://download.oracle.com/javase/1.4.2/docs/tooldocs/windows/javac.html">javac</a>) is generic and compiles java to <a href="http://en.wikipedia.org/wiki/Java_bytecode">bytecode</a>, the second(<a href="http://en.wikipedia.org/wiki/Just-in-time_compilation">jit</a>) is platform-dependent and compiles some portions of the <a href="http://en.wikipedia.org/wiki/Java_bytecode">bytecode </a>to machine-code in runtime! Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-33091220130417304842011-12-22T23:55:00.001+05:302011-12-31T11:02:11.739+05:30Optimizing and Speeding up the code in Java<p><strong>Finalizers: </strong>object that overwrites the finalize() method (“Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.”) is slower!(for both allocation and collection) if it’s not a must, do clean ups in other ways ( e.g. in JDBC close the connection using the try-catch-finally block instead) <p><strong>New is expensive</strong>: creating new heavy object() on the heap is expensive!, it’s recommended to recycle old objects (by changing their fields) or use the <a href="http://k2java.blogspot.com/2011/02/flyweight-pattern.html">flyweight design pattern</a>. <p><strong>Strings : </strong>(1) Strings are immutable which mean that upon usage of the + operator between 2 strings the JVM will generate a new String(s1+s2) on the heap (expensive as I just mentioned), in order to avoid that, it’s recommended to use the StringBuffer.(Update) since JDK 1.5 was introduced <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder </a>is a better option than Stringbuffer in a single-threaded environment. <p>(2) Don’t convert your strings to lower case in order to compare them, use String.equalIgnoreCase() instead. <p>(3) String.startswith() is more expensive than String.charat(0) for the first character. <p><strong>Inline method: </strong>inline is a compiler feature, when you call a method from anywhere in your code, the compiler copies the content of the inline method and replace the line that calls the method with it. <p>Obviously,It saves runtime time: (1) there is no need to call a method (2) no dynamic dispatch. <p>In some languages you can annotate a method to be inline, yet in Java it’s impossible, it’s the compiler decision. <p>the compiler will consider inline a method if the method is <strong>private</strong>. <p>My recommendation is to search in your code for methods that are heavily used(mostly in loops) and annotate those method as private if possible. <p><strong>Don’t invent the wheel: </strong>the java api is smart and sophisticated and in some cases use native implementation, code that you probably can’t compete with. unless you know what you are doing (performance wise) don’t rewrite methods that already exists in the java API. e.g. benchmarks showed that coping and array using a for loop is at least n/4 times slower than using System.arraycopy() <p><strong>Reflection:</strong> reflection became much faster for those of you who use the most recent JVMs, yet using reflection is most certainly slower than not using it. which mean that you better avoid reflection if there is no need. <p><strong>Synchronization:</strong> Some data structures auto-support concurrency, in case of a single thread application don’t use those to avoid overhead e.g. use ArrayList instead of a Vector <p><strong>Multithreads:</strong> in case of a multi processor use threads, it will defiantly speed up your code, if you are not a thread expert some <a href="http://www.aartbik.com/JAVAR/index.html">compilers </a>know how to restructure your code to thread automatically for you. you can always read a <a href="http://java.sun.com/docs/books/tutorial/essential/concurrency/">java threads tutorial</a> as well <p><strong>Get familiar with the standard data structures</strong>: e.g. if you need a dast for puting and retriving objects use HashMap and not an ArrayList. (O(1)) <p><strong>Add an id field, for faster equals(): </strong>object that contains many fields are hard to compare ( equals() wise), to avoid that add an id(unique) field to your object and overwrite the equals() method to compare ids only. <p><strong>Be careful, In case your code already works, optimizing it is a sure way to create new bugs and make your code less maintainable!</strong> <p>it’s highly recommended to time your method before and after an optimization. Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-2485954736092760492011-10-09T16:13:00.000+05:302011-12-31T11:02:11.761+05:30101 reasos why java is better than .net<div dir="ltr" style="text-align: left;" trbidi="on">I was once reading the interesting article and so I decided to share on this blog:<br />
<a href="http://www.helpdesk-software.ws/it/29-04-2004.htm"><b>link</b></a></div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-5519346888434197352011-10-09T16:08:00.000+05:302011-12-31T11:02:11.783+05:30Divide by Zero in case of Java<div dir="ltr" style="text-align: left;" trbidi="on">One of the good interview questions I found was related to divide by zero.<br />
Lets take the case:<br />
<br />
What will be the output of this code snippet?<br />
<br />
<pre style="background: #f6f8ff; color: #000020;"><span style="color: #200080; font-weight: bold;">public</span> <span style="color: #200080; font-weight: bold;">class</span> NaN <span style="color: #406080;">{</span>
<span style="color: #200080; font-weight: bold;">public</span> <span style="color: #200080; font-weight: bold;">static</span> <span style="color: #7779bb;">void</span> main<span style="color: #308080;">(</span><span style="color: #6679aa; font-weight: bold;">String</span><span style="color: #308080;">[</span><span style="color: #308080;">]</span> args<span style="color: #308080;">)</span> <span style="color: #406080;">{</span>
<span style="color: #7779bb;">double</span> d <span style="color: #308080;">=</span> <span style="color: green;">2.0</span> <span style="color: #308080;">/</span> <span style="color: green;">0.0</span><span style="color: #406080;">;</span>
<span style="color: #6679aa; font-weight: bold;">System</span><span style="color: #308080;">.</span>out<span style="color: #308080;">.</span>println<span style="color: #308080;">(</span>d<span style="color: #308080;">)</span><span style="color: #406080;">;</span>
<span style="color: #406080;">}</span>
<span style="color: #406080;">}</span>
</pre><br />
What's the answer: The code will not compile or will it throw a DivideByZero error? Both are wrong. The code compiles fine and the output is,<br />
<div style="background-color: #cfe2f3; font-family: "Courier New",Courier,monospace;">Infinity</div><br />
Let's check another code snippet,<br />
<br />
<pre style="background: #f6f8ff; color: #000020;"><span style="color: #200080; font-weight: bold;">public</span> <span style="color: #200080; font-weight: bold;">class</span> NaN <span style="color: #406080;">{</span>
<span style="color: #200080; font-weight: bold;">public</span> <span style="color: #200080; font-weight: bold;">static</span> <span style="color: #7779bb;">void</span> main<span style="color: #308080;">(</span><span style="color: #6679aa; font-weight: bold;">String</span><span style="color: #308080;">[</span><span style="color: #308080;">]</span> args<span style="color: #308080;">)</span> <span style="color: #406080;">{</span>
<span style="color: #7779bb;">double</span> d <span style="color: #308080;">=</span> <span style="color: green;">0.0</span> <span style="color: #308080;">/</span> <span style="color: green;">0.0</span><span style="color: #406080;">;</span>
<span style="color: #6679aa; font-weight: bold;">System</span><span style="color: #308080;">.</span>out<span style="color: #308080;">.</span>println<span style="color: #308080;">(</span>d<span style="color: #308080;">)</span><span style="color: #406080;">;</span>
<span style="color: #406080;">}</span>
<span style="color: #406080;">}</span>
</pre><br />
The output in this case is,<br />
<pre style="background-color: #cfe2f3;">NaN</pre><br />
</div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-24349014135221242702011-10-08T23:49:00.000+05:302011-12-31T11:02:11.806+05:30Hello World in Ruby using Netbeans<div dir="ltr" style="text-align: left;" trbidi="on"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgG0G2ZewpwuFR2HJZn_dB8izUNv8jOv2dbTBCpq3t3jr4zW77JBEAzuVSBFgbUtytQIZXqfEx3hyxlEGl-INqM6Gy_ae2zc6XyeX_Dbfg3npDbH-UeDHAYLTZkGQVMER_cg3xHegyralxD/s1600/Netbeans%252Band%252BRuby.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="267" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgG0G2ZewpwuFR2HJZn_dB8izUNv8jOv2dbTBCpq3t3jr4zW77JBEAzuVSBFgbUtytQIZXqfEx3hyxlEGl-INqM6Gy_ae2zc6XyeX_Dbfg3npDbH-UeDHAYLTZkGQVMER_cg3xHegyralxD/s320/Netbeans%252Band%252BRuby.png" width="320" /></a></div>After getting a decent knowledge of <a href="http://www.technicalypto.com/2010/05/lets-ruby.html">what Ruby is</a> and the <a href="http://www.technicalypto.com/2010/06/useful-books-on-ruby-and-ruby-on-rails.html">useful resources</a> that are available, lets get into action by creating our first hello world program.<br />
<br />
Ruby and Ruby on Rails development becomes amazingly easy using Netbeans IDE where you can perform almost all the tasks in one single IDE. <a href="http://netbeans.org/downloads/index.html">Download</a> and install the Netbeans-Ruby version. You should be having JDK installed in your box, thats pretty much the pre-requisite for Netbeans to install.<br />
<br />
OR you can simply download the complete version of netbeans and install ruby plugins.<br />
<br />
Download the ruby from <a href="http://www.ruby-lang.org/en/downloads/"><b>here</b></a>. Extract it to some location, Say C:\\ruby<br />
Now create new project.<br />
Launch Netbeans go to File --> New Project. A new project wizard should come up. Select Ruby Application i.e. C:ruby\bin., click Next and click Finish. Thats it!!!!<br />
You dont even have to type a Hello World. The new project template does it for you! So sweet isnt it? Now, click on the big green Run button and the console should print out Hello World without a hitch. <br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgG0G2ZewpwuFR2HJZn_dB8izUNv8jOv2dbTBCpq3t3jr4zW77JBEAzuVSBFgbUtytQIZXqfEx3hyxlEGl-INqM6Gy_ae2zc6XyeX_Dbfg3npDbH-UeDHAYLTZkGQVMER_cg3xHegyralxD/s1600/Netbeans%252Band%252BRuby.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="267" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgG0G2ZewpwuFR2HJZn_dB8izUNv8jOv2dbTBCpq3t3jr4zW77JBEAzuVSBFgbUtytQIZXqfEx3hyxlEGl-INqM6Gy_ae2zc6XyeX_Dbfg3npDbH-UeDHAYLTZkGQVMER_cg3xHegyralxD/s320/Netbeans%252Band%252BRuby.png" width="320" /></a></div>Now just run the program :)</div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-85452796298956444502011-10-08T23:34:00.000+05:302011-12-31T11:02:11.828+05:30installing RadRails on Eclipse<div dir="ltr" style="text-align: left;" trbidi="on"><div class="entry"> I could not find a proper answer when i wanted to install RadRails on eclipse . This is how it is done , .... in the Eclipse menu go to<br />
<span style="color: #3333ff;">Help-->Software Updates --> Find and Install....</span><br />
then in the pop - up window which appears ,..<br />
<span style="color: #3333ff;">Search for new features to install</span><br />
and then click next and then u will have to add 2 new remote sites, .. the details for the sites are the ones which were very difficult to obtain , they are<br />
<span style="color: #000066;">site 1 :</span><br />
<span style="color: #3333ff;">Name :RadRails</span><br />
<span style="color: #3333ff;">URL : http://radrails.sourceforge.net/update</span><br />
<span style="color: #000066;">site 2 :</span><br />
<span style="color: #3333ff;">Name :RDT</span><br />
<span style="color: #3333ff;">URL : http://updatesite.rubypeople.org/release</span><br />
then click on <span style="color: #3333ff;">finish</span> , u are almost done with the installation , u have to just follow the instructions from here on to finish the installation .<br />
</div><div class="ping-track"> This entry was posted on Friday, May 16, 2008 at 8:37 PM and is filed under <a href="http://satisheerpini.blogspot.com/search/label/eclipse" rel="tag">eclipse</a>, <a href="http://satisheerpini.blogspot.com/search/label/linux" rel="tag">linux</a>, <a href="http://satisheerpini.blogspot.com/search/label/ruby" rel="tag">ruby</a> . You can follow any responses to this entry through the <a href="http://satisheerpini.blogspot.com/feeds/9055556815792700955/comments/default" target="_blank" type="application/atom+xml">comments feed</a> . </div></div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-73422238178947386802011-10-03T17:57:00.000+05:302011-12-31T11:02:11.850+05:30Making collections final<div dir="ltr" style="text-align: left;" trbidi="on">Once we write final<br />
<div style="background-color: #cfe2f3;">ArrayList list = new ArrayList();</div><br />
We can add, delete objects from this list, but I can not<br />
<div style="background-color: #cfe2f3;">list = new ArrayList() or list = list1.</div><br />
So declaring the <code>list</code> final means that you cannot reassign the <code>list</code> variable to another object.<br />
<br />
There are two situations in which this can be useful. <br />
<ol><li>You want to make sure that no-one <b>reassigns</b> your <code>list</code> variable once it has received its value. This can reduce complexity and helps in understanding the semantics of your class/method. In this case you are usually better off by using good naming conventions and reducing method length (the class/method is already too complex to be easily understood).</li>
<li>When using <b>inner classes</b> you need to declare variables as <code>final</code> in an enclosing scope so that you can access them in the inner class. This way, Java can copy your <code>final</code> variable into the inner class object (it will never change its value) and the inner class object does not need to worry what happens to the outer class object while the inner class object is alive and needs to access the value of that variable.</li>
</ol><br />
<br />
</div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-35121635228849339112011-09-27T23:55:00.000+05:302011-12-31T11:02:11.872+05:30Difference between Proxy, Decorator, Adaptor, and Bridge Patterns ?<div dir="ltr" style="text-align: left;" trbidi="on"><div class="post-text">Proxy, Decorator, Adapter, and Bridge are all variations on "wrapping" a class. But their uses are different.<br />
<ul><li><b>Proxy</b> could be used when you want to lazy-instantiate an object, or hide the fact that you're calling a remote service, or control access to the object.<br />
See <a href="http://k2java.blogspot.com/2011/03/proxy-pattern.html"><b>proxy pattern</b></a> with details.</li>
<li><b>Decorator</b> is also called "Smart Proxy." This is used when you want to add functionality to an object, but not by extending that object's type. This allows you to do so at runtime.</li>
<li><b>Adapter / Wrapper</b> is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.<br />
In particular Decorator looks very close to Adapter but still there is basic difference:<br />
<table border="1" cellpadding="1" cellspacing="1" style="text-align: center; width: 500px;"><thead>
<tr><th scope="col"> </th> <th scope="col"> Adapter / Wrapper</th> <th scope="col"> Decorator</th> </tr>
</thead> <tbody>
<tr> <td> <span style="color: blue;">Composes </span>"origin" class</td> <td> True</td> <td> True</td> </tr>
<tr> <td> <span style="color: blue;">Modifies </span>original interface</td> <td> <span style="color: blue;">True</span></td> <td> False</td> </tr>
<tr> <td> <div> Modifies <span style="color: blue;">behavior </span>of interface</div></td> <td> False</td> <td> <span style="color: blue;">True</span></td> </tr>
<tr> <td> Proxies method calls</td> <td> True</td> <td> True</td> </tr>
</tbody> </table><div> </div>See <a href="http://k2java.blogspot.com/2011/03/adapter-pattern-wrapper-pattern.html"><b>Adapter pattern</b></a> and <a href="http://k2java.blogspot.com/2011/02/decorator-pattern.html"><b>Decorator Pattern</b></a> with examples.</li>
<li><b>Bridge</b> is very similar to Adapter, but we call it Bridge when you define both the abstract interface and the underlying implementation. I.e. you're not adapting to some legacy or third-party code, you're the designer of all the code but you need to be able to swap out different implementations.<br />
See <a href="http://k2java.blogspot.com/2011/05/bridge-pattern.html"><b>bridge pattern</b></a> with example.</li>
<li><b>Facade</b> is a higher-level (read: simpler) interface to a subsystem of one or more classes. Think of Facade as a sort of container for other objects, as opposed to simply a wrapper. So you don't have to worry about so many things, just call the facade to do all the stuff.<br />
See <a href="http://k2java.blogspot.com/2011/03/facade-pattern.html"><b>Facade pattern</b></a> with example.</li>
</ul></div></div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-48610774073511741122011-09-27T19:17:00.000+05:302011-12-31T11:02:11.893+05:30Interface And Abstraction – Spiritual Explanation<div dir="ltr" style="text-align: left;" trbidi="on"><div style="text-align: justify;">“What is the difference between interface and abstract class?”, a typical interview question . Answer is so obvious, and we can list at least 3 differences. Here is an attempt to correlate Object Oriented world with spiritual world, and explain abstraction and interface.</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">“Soul is an abstract notion realized by concrete living being”. So as per OO world, if you got “Soul” as abstract class, you got to have a concrete class “Life”. Soul can not operate without Life.</div><div style="text-align: justify;">Just like I said object is an entity with an objective to live, abstract class can live through concrete class. Inheritance is the only mechanism for an abstract class to live. Spiritually, Soul operates through life. Life is an object with a process thread running in it.</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">In Spiritual world, it is said that “Soul carries the karma (good or bad actions) from previous life, which has influences in the new life”. If you consider this statement, karma is the action log recorded into the abstract class.</div><div style="text-align: justify;">Body is an interface to life (and hence interface to Soul) and real world. so IBody can be implemented by body of human, bird or any living creature. Once the objective is complete in this real world, destructor is called on life object. However actions are kept recorded (like log files) in the abstract class through out this new life.</div><div style="text-align: justify;">In every new life actions recorded in abstract class is not revealed, as it is private declaration . Only the ultimate object builder (God) has access to it. Object builder reads this private variable, and makes the decision of choosing a new interface for Soul. Dispose method is programmed to be called in a timer function. When timer event fires, dispose is called, and the Life object is disposed terminating the process thread.</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">After thread is terminated and Life is disposed, Object builder reads the record log from Soul class. Based on the karma recorded in the log, a new object with the suitable interface (body) is created, and Life is induced into it with a process thread. And a timer is started in the Life class, which when fires Thread Abort is called. </div></div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-74089727654589332422011-09-22T18:20:00.001+05:302011-12-31T11:02:11.914+05:30Shallow Copy and Deep Copy<div dir="ltr" style="text-align: left;" trbidi="on">There are two ways to make a copy of an object called shallow copy and deep copy.<br />
Here is what they mean:<br />
<br />
<span class="Apple-style-span" style="font-size: large;">Shallow Copy</span><br />
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same subobjects.<br />
<br />
<span class="Apple-style-span" style="font-size: large;">Deep Copy</span><br />
Deep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all subobjects as well, all the way to the bottom. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object.<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><img align="center" alt="Shallow Copy" height="132" src="http://www.jusfortechies.com/images/core-java/shallow_copy.png" style="border-style: none; margin: 0px auto; padding: 0px;" width="400" /></td></tr>
<tr style="color: #0b5394;"><td class="tr-caption" style="text-align: center;"><b><span class="Apple-style-span" style="font-size: small;">Shallow Copy</span></b></td></tr>
</tbody></table><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><img align="center" alt="Deep Copy" height="139" src="http://www.jusfortechies.com/images/core-java/deep_copy.png" style="border-style: none; margin: 0px auto; padding: 0px;" width="400" /></td></tr>
<tr style="color: #0b5394;"><td class="tr-caption" style="text-align: center;"><b><span class="Apple-style-span" style="font-size: small;">Deep Copy</span></b></td></tr>
</tbody></table><br />
<b>You may like : </b><br />
<a href="http://k2java.blogspot.com/2011/05/prototype-pattern.html">Design patterns using shallow copy and deep copy - Prototype pattern</a><br />
<a href="http://k2java.blogspot.com/2011/04/java-clone-shallow-copy-and-deep-copy.html">Shallow and deep copy using clone</a></div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-3593980508445933002011-09-22T18:06:00.000+05:302011-09-22T18:06:08.753+05:30MVC Pattern Basics<div dir="ltr" style="text-align: left;" trbidi="on"><span style="font-size: large;">Definition</span><br />
The Model-View-Controller (MVC) architectural pattern is used in software engineering to allow for the separation of three common features in GUI applications: <br />
<ul class="smallmargin notes"><li>the data access (typically via a database)</li>
<li>the business logic (how the data will be used)</li>
<li>user interaction (how the data and actions will be visually presented)</li>
</ul><br />
MVC pattern differenciates all the 3 aspects of application in 3 difft tiers.<br />
<br />
<span style="font-size: large;">Modal</span><br />
It incorporates following point<br />
<ul style="text-align: left;"><li> Holds the business logic of the application.</li>
<li> holds data sent between different. tiers like JSP to servlet and handler classes.</li>
<li>One of the goals of the model is to give a presentation which does not directly refer to any specific DBMS. </li>
</ul><div style="text-align: left;"><br />
<span style="font-size: large;">View</span></div><ul style="text-align: left;"><li>This represents the visible user interface, so handles presentation tier of the application.</li>
<li> it knows enough about the data to create a coherent presentation, but does not actually do the work of presenting the data. Instead, it provides the ability to manipulate data <b>outside</b> the View through event handlers defined within. </li>
<li>handles presentation logic, client side validation.</li>
<li><b>e.g.</b> HTML, JSP</li>
</ul><div style="text-align: left;"><br />
<span style="font-size: large;">Controller</span></div><ul style="text-align: left;"><li>handles the flow of the application</li>
<li> Joins the Model with the View and is the heart of the business logic. </li>
<li>It is the source of activity when an event occurs and defines the event handling actions which access data (from the Model) and are presented to the user (in the View). </li>
<li>e.g. Servlets, Action Class in Struts, ActionServlet is using struts-config.xml as front controller to handle each request and redirect it to appropriate destination.</li>
</ul><div style="text-align: left;"><br />
<span style="font-size: large;">Advantages</span></div><ul style="text-align: left;"><li> Increases modularity of the application.</li>
<li> Increases Maintainability of the application, i.e. the data presentation can be changed without any notion of how the data is obtained and conversely, the data access can be changed without any knowledge of how it is to be presented. </li>
</ul><span style="font-size: large;">Example</span><br />
to be added soon<br />
<ul style="text-align: left;"></ul></div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-68992473503358061482011-09-22T16:47:00.000+05:302011-12-31T11:02:11.935+05:30Feelings today<div dir="ltr" style="text-align: left;" trbidi="on"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlWQ8lnIbK9Z8z2jwcNjd6CLRdSO2p-j-04HWctZ5OyDtwN_leJKWbfnYY-GvnwafAarCTqb5a7dx9ucaU18wLe49zKxA3jmcaEh1-P0UO-3RxkIr-N8bS5xXZO_tX0UQaf8M_LOmZ7XSy/s1600/feelings-poster-2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlWQ8lnIbK9Z8z2jwcNjd6CLRdSO2p-j-04HWctZ5OyDtwN_leJKWbfnYY-GvnwafAarCTqb5a7dx9ucaU18wLe49zKxA3jmcaEh1-P0UO-3RxkIr-N8bS5xXZO_tX0UQaf8M_LOmZ7XSy/s640/feelings-poster-2.jpg" width="420" /></a></div><br />
</div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-73544296679030611272011-09-22T16:34:00.000+05:302011-12-31T11:02:11.959+05:30Java: Rounding off to 2 decimal places<div dir="ltr" style="text-align: left;" trbidi="on">Seeking the simplest way to round off a float value to 2 decimal places, i found these:<br />
<br />
<strong>Method 1:</strong><br />
x = (double)int((x+0.005)*100.0)/100.0;<br />
<br />
<strong>Method 2:</strong><br />
x = Math.round(x*100.0) / 100.0;<br />
<br />
<strong>Method 3:</strong><br />
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );<br />
double dd = 100.2397;<br />
double dd2dec = new Double(df2.format(dd)).doubleValue();<br />
<br />
<strong>Method 4:</strong><br />
f = (float) (Math.round(n*100.0f)/100.0f);<br />
<br />
<strong>Method 5:</strong><br />
double r = 5.1234;<br />
System.out.println(r); // r is 5.1234<br />
int decimalPlaces = 2;<br />
BigDecimal bd = new BigDecimal(r);<br />
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP); // setScale is immutable<br />
r = bd.doubleValue();<br />
System.out.println(r); // r is 5.12<br />
<br />
[source:<a href="http://www.thescripts.com/"> www.thescripts.com</a>, accuracy unchecked]<br />
<br />
<strong>How I did it:</strong><br />
float percentage = score.floatValue()/(qapairs.length*10)*100; //my float value<br />
percentage = Float.valueOf((new DecimalFormat("###.00").format(percentage))); </div>Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-74536035722754554572011-07-15T04:37:00.000+05:302011-12-31T11:02:11.983+05:30The Value of String.valueOf<p> Most Java developers have probably had their <a href="http://jeremy.zawodny.com/blog/archives/000422.html">fill</a> of <a href="http://java.sun.com/javase/6/docs/api/java/lang/NullPointerException.html">NullPointerException</a>. <a href="http://runtime32.blogspot.com/2009/02/javalangnullpointerexception.html">Most of us</a> have learned the value of doing <a href="http://ozgwei.blogspot.com/2008/12/preventing-nullpointerexception.html">certain things</a> to reduce our "<a href="http://www.urbandictionary.com/define.php?term=builds%20character">opportunities</a>" of <a href="http://blog.reindel.com/2007/12/19/preventing-the-nullpointerexception-in-java/">encountering the NullPointerException</a>. Indeed, there is a Wiki page dedicated to <a href="http://en.wikibooks.org/wiki/Java_Programming/Preventing_NullPointerException">preventing or reducing NullPointerExceptions</a>.<br><br>Several people have argued for additional language support for improved and easier handling of potential null. These include <a href="http://www.jroller.com/scolebourne/entry/java_7_null_default_and">Java SE 7 proposals</a>, <a href="http://jonasboner.com/2006/04/04/the-optimized-null-check-pattern.html">Optimized Null Check</a>, and <a href="http://www.cs.virginia.edu/%7Eweimer/students/kinga-ms-pres.pdf">Kinga Dobolyi</a>'s thesis <a href="http://www.cs.virginia.edu/%7Eweimer/students/kinga-ms-paper.pdf">Changing Java’s Semantics for Handling Null Pointer Exceptions</a>.<br><br>Among the <a href="http://www.codemonkeyism.com/archives/2009/02/04/better-null-handling-strategies-for-java/">many things we can already do</a> rather easily to reduce our encounters with NullPointerException, one particular easy thing to do is to apply <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#valueOf%28java.lang.Object%29">String.valueOf(Object)</a> when appropriate. The <code>String.valueOf(Object)</code> method, as its <a href="http://java.sun.com/j2se/javadoc/">Javadoc</a>-generated <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#valueOf%28java.lang.Object%29">documentation</a> states, returns "null" if the passed in object is <code>null</code> and returns the results on the passed-in <code>Object</code>'s <a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#toString%28%29">toString()</a> call if the passed-in <code>Object</code> is not null. In other words, <code>String.valueOf(String)</code> does the null checking for you.<br><br>The use of <code>String.valueOf(Object)</code> is particularly useful when implementing <code>toString</code> methods on custom classes. Because most <code>toString</code> implementations provide the class's data members in String format, <code>String.valueOf(Object)</code> is a natural fit. All Java objects based on classes that extend <a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html">Object</a> provide a <code>toString()</code> implementation even if it is simply their parent's (or even <code>Object</code>'s) implementation of <code>toString()</code>. However, if a member class implements <code>toString</code> but the member itself is null rather than an instance of the class, then the <code>toString()</code> does no good (and actually leads to a <code>NullPointerException</code> when called).<br><br>This is demonstrated with the following example code.</p> <p>Consider a class called PersonName, which holds last name and first name of the person:</p> <p id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">package</span> com.vaani.string;<br><br><span style="color: #008000">/**</span><br><span style="color: #008000"> * Class upon which to call toString.</span><br><span style="color: #008000"> */</span><br><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> PersonName<br>{<br> <span style="color: #0000ff">private</span> String lastName;<br> <span style="color: #0000ff">private</span> String firstName;<br><br> <span style="color: #0000ff">public</span> PersonName(<span style="color: #0000ff">final</span> String newLastName, <span style="color: #0000ff">final</span> String newFirstName)<br> {<br> lastName = newLastName;<br> firstName = newFirstName;<br> }<br><br> <span style="color: #008000">/**</span><br><span style="color: #008000"> * Provide String representation of me.</span><br><span style="color: #008000"> *</span><br><span style="color: #008000"> * @return My String representation.</span><br><span style="color: #008000"> */</span><br> @Override<br> <span style="color: #0000ff">public</span> String toString()<br> {<br> <span style="color: #0000ff">return</span> firstName + <span style="color: #006080">" "</span> + lastName;<br> }<br>}<br></pre><br></p><br /><p>Person.java<br></p><br /><p id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">package</span> com.vaani.string;<br><br><br><br><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> Person<br>{<br> <span style="color: #0000ff">private</span> PersonName name;<br><br> <span style="color: #0000ff">public</span> Person( PersonName newName)<br> {<br> name = newName;<br> }<br><br><br><br><span style="color: #008000">/**</span><br><span style="color: #008000"> * Provide String representation of me.</span><br><span style="color: #008000"> *</span><br><span style="color: #008000"> * @return My String representation.</span><br><span style="color: #008000"> */</span><br> <span style="color: #0000ff">public</span> String toString()<br> {<br> <span style="color: #008000">//to be implemented</span><br> }<br>}<br></pre><br></p><br /><p>Now this person.java has toString() which is to be implemented, but we will see how it throws NPE. Consider the main method:</p><br /><div id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet">PersonName personName = <span style="color: #0000ff">new</span> PersonName(<span style="color: #006080">"Flintstone"</span>, null);<br><span style="color: #008000">//print personname as string</span><br>System.out.println(<span style="color: #006080">"Person's Name [DIRECT]: "</span> + personName);<br>System.out.println(<span style="color: #006080">"Person's Name [TOSTRING]: "</span> + personName.toString());<br>System.out.println(<span style="color: #006080">"Person's Name [STRING.VALUEOF]: "</span> + String.valueOf(personName));<br> </pre>Output will be:<br><br /><div id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet">Person<span style="color: #006080">'s Name [DIRECT]: null Flintstone<br>Person'</span>s Name [TOSTRING]: null Flintstone<br>Person's Name [STRING.VALUEOF]: null Flintstone</pre><br></div>Now consider the toString() func is represented as <br><br>Also if we call Person's constructor with personName(instance created above), everything will still be fine:<br><br /><div id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet">PersonName name;<br><span style="color: #008000">//code skipped</span><br><span style="color: #0000ff">public</span> String toString()<br>{<br> <span style="color: #008000">// Don't use -- can lead to runtime error (NullPointerException)</span><br> <span style="color: #0000ff">return</span> name.toString();<br>}</pre><br></div>Now as we did earlier:<br><br /><div id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet">PersonName personName = <span style="color: #0000ff">new</span> PersonName(<span style="color: #006080">"Flintstone"</span>, null);<br> <br> <span style="color: #008000">//create next object from personName</span><br>Person personOne = <span style="color: #0000ff">new</span> Person(personName);<br>System.out.println(<span style="color: #006080">"Person One [DIRECT]: "</span> + personOne);<br>System.out.println(<span style="color: #006080">"Person One [TOSTRING]: "</span> + personOne.toString());<br>System.out.println(<span style="color: #006080">"Person One [STRING.VALUEOF]: "</span> + String.valueOf(personOne));</pre><br></div>This will work fine because of personName will return its toString() func, and dont throw any NPE. But this will result in bang:<br><br /><div id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet">Person personTwo = <span style="color: #0000ff">new</span> Person(null);<br>System.out.println(<span style="color: #006080">"Person Two [DIRECT]: "</span> + personTwo);<br>System.out.println(<span style="color: #006080">"Person Two [TOSTRING]: "</span> + personTwo.toString());<br>System.out.println(<span style="color: #006080">"Person Two [STRING.VALUEOF]: "</span> + String.valueOf(personTwo));<br> </pre>Each of this above line throws exception. So please be aware of this. To avoid null pointer exception you can implement toString() func of Person like this:<br><br /><div id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">public</span> String toString()<br>{<br> <span style="color: #008000">// It's all good</span><br> <span style="color: #0000ff">return</span> String.valueOf(name);<br>}</pre>Now the personTwo will be printed as null.<br>Full code listing for Person.java(personName.java is already covered):<br><br /><div id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">package</span> com.vaani.string;<br><br><br><br><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> Person<br>{<br> <span style="color: #0000ff">private</span> PersonName name;<br><br> <span style="color: #0000ff">public</span> Person( PersonName newName)<br> {<br> name = newName;<br> }<br><br><br><br><span style="color: #008000">/**</span><br><span style="color: #008000"> * Provide String representation of me.</span><br><span style="color: #008000"> *</span><br><span style="color: #008000"> * @return My String representation.</span><br><span style="color: #008000"> */</span><br> <span style="color: #0000ff">public</span> String toString()<br> {<br> <span style="color: #008000">// Don't use -- leads to compiler time error (incompatible types)</span><br> <span style="color: #008000">//return name;</span><br><br> <span style="color: #008000">// Don't use -- can lead to runtime error (NullPointerException)</span><br> <span style="color: #008000">//return name.toString();</span><br><br> <span style="color: #008000">// It's all good</span><br> <span style="color: #0000ff">return</span> String.valueOf(name);<br> }<br>}<br></pre><br></div>main method to run this code:<br><br /><div id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">package</span> com.vaani.string;<br><br><span style="color: #0000ff">import</span> java.io.IOException;<br><span style="color: #0000ff">import</span> java.io.OutputStream;<br><span style="color: #0000ff">import</span> java.util.logging.Logger;<br><br><span style="color: #008000">/**</span><br><span style="color: #008000"> * Example class demonstrating use of String representations available through</span><br><span style="color: #008000"> * implicit String, toString(), and String.valueOf().</span><br><span style="color: #008000"> */</span><br><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> StringValueFunc<br>{<br> <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">final</span> String NEW_LINE = System.getProperty(<span style="color: #006080">"line.separator"</span>);<br><br> <span style="color: #008000">/** Using java.util.logging. */</span><br> <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> Logger LOGGER = Logger.getLogger(<br> StringValueFunc.<span style="color: #0000ff">class</span>.getName());<br><br> <span style="color: #008000">/**</span><br><span style="color: #008000"> * Main function for running tests/demonstrations.</span><br><span style="color: #008000"> *</span><br><span style="color: #008000"> * @param arguments Command-line arguments; none anticipated.</span><br><span style="color: #008000"> */</span><br> <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> main(<span style="color: #0000ff">final</span> String[] arguments)<br> {<br> <span style="color: #008000">//takes last name and first name</span><br> PersonName personName = <span style="color: #0000ff">new</span> PersonName(<span style="color: #006080">"Flintstone"</span>, null);<br> <br> <span style="color: #008000">//create next object from personName</span><br> Person personOne = <span style="color: #0000ff">new</span> Person(personName);<br> <span style="color: #008000">//just initiate to null</span><br> Person personTwo = <span style="color: #0000ff">new</span> Person(null);<br> printHeader(<span style="color: #006080">"String representation of direct Strings"</span>, System.out);<br> <br> System.out.println(<span style="color: #006080">"Person's Name [DIRECT]: "</span> + personName);<br> System.out.println(<span style="color: #006080">"Person's Name [TOSTRING]: "</span> + personName.toString());<br> System.out.println(<span style="color: #006080">"Person's Name [STRING.VALUEOF]: "</span> + String.valueOf(personName));<br> printBlankLine(System.out);<br><br> printHeader(<span style="color: #006080">"String representation of non-null complex object"</span>, System.out);<br> <br> System.out.println(<span style="color: #006080">"Person One [DIRECT]: "</span> + personOne);<br> System.out.println(<span style="color: #006080">"Person One [TOSTRING]: "</span> + personOne.toString());<br> System.out.println(<span style="color: #006080">"Person One [STRING.VALUEOF]: "</span> + String.valueOf(personOne));<br> printBlankLine(System.out);<br><br> printHeader(<span style="color: #006080">"String representation of null complex object"</span>, System.out);<br> <br> System.out.println(<span style="color: #006080">"Person Two [DIRECT]: "</span> + personTwo);<br> System.out.println(<span style="color: #006080">"Person Two [TOSTRING]: "</span> + personTwo.toString());<br> System.out.println(<span style="color: #006080">"Person Two [STRING.VALUEOF]: "</span> + String.valueOf(personTwo));<br> printBlankLine(System.out);<br> }<br><br> <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> printHeader(<span style="color: #0000ff">final</span> String message, <span style="color: #0000ff">final</span> OutputStream out)<br> {<br> <span style="color: #0000ff">final</span> String headerSeparator =<br> <span style="color: #006080">"===================================================================="</span>;<br><br> <span style="color: #0000ff">try</span><br> {<br> out.write((headerSeparator + NEW_LINE + message + NEW_LINE).getBytes());<br> out.write((headerSeparator + NEW_LINE).getBytes());<br> }<br> <span style="color: #0000ff">catch</span> (IOException ioEx)<br> {<br> System.out.println(headerSeparator);<br> System.out.println(message);<br> System.out.println(headerSeparator);<br> LOGGER.warning(<span style="color: #006080">"Could not write header information to provided OutputStream."</span>);<br> }<br> }<br><br> <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> printBlankLine(<span style="color: #0000ff">final</span> OutputStream out)<br> {<br> <span style="color: #0000ff">try</span><br> {<br> out.write(NEW_LINE.getBytes());<br> }<br> <span style="color: #0000ff">catch</span> (IOException ioEx)<br> {<br> System.out.println(NEW_LINE);<br> LOGGER.warning(<span style="color: #006080">"Could not write blank line to provided OutputStream."</span>);<br> }<br> }<br><br><br> }<br></pre><br>The above code can be used to demonstrate building of a <code>toString</code> method on a complex object and how its behaves when called by an owning class. The method of most interest is at the bottom of the code shown above. Two return values are commented out because of problems associated with them. The final example, using <code>String.valueOf(Object)</code> is NOT commented out because it works the best each time it is run whether or not the complex <code>PersonName</code> object is null. The next three images show the output for each of these presentations of the Person objects' String representations.</div></div></div></div><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><p>Finally, the <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html">String</a> class provides many overloaded valueOf methods. In addition to the version that was the focus of this blog post (<a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#valueOf%28java.lang.Object%29">accepts an Object</a>), the other overloaded versions of valueOf accept primitive data types and arrays of primitive data types.<br><strong>Conclusion</strong><br>Regardless of what the future brings in terms of improved null handling in Java, there are many tactics we can take today to reduce the unwanted (sometimes we actually do want them thrown!) <a href="http://www.java-tips.org/java-se-tips/java.lang/a-small-tip-on-string-to-avoid-nullpointerexce.html">occurrences</a> of <a href="http://c2.com/cgi/wiki?NullPointerException">NullPointerException</a>. One of these is to use <code>String.valueOf(Object)</code> when appropriate.<br /><p><strong>Additional Resources</strong><br /><ul><br /><li><a href="http://www.devx.com/tips/Tip/16234">String.valueOf or Integer.toString()?</a><br /><li><a href="http://stackoverflow.com/questions/328661/explicit-vs-implicit-call-of-tostring">Explicit versus Implicit Call of toString</a><br /><li><a href="http://www.java2s.com/Code/Java/Data-Type/TheValueofaStringwithStringvalueOfmethod.htm">The Value of a String with String.valueOf() Method</a><br /><li><a href="http://www.roseindia.net/java/java-conversion/convert-number-to-string.shtml">Convert Number to String</a></li></ul> Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-41081339176321911122011-07-15T04:10:00.000+05:302011-09-18T01:59:37.539+05:30Effective Java : How to Avoid NPE / Null Pointer Exception in java?It doesn't take much Java development experience to learn firsthand what the NullPointerException is about. In fact, one person has highlighted dealing with this as the <a href="http://www.javacoffeebreak.com/articles/toptenerrors.html">number one mistake Java developers make</a>. I <a href="http://k2java.blogspot.com/2011/07/value-of-stringvalueof.html">blogged previously</a> on use of <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#valueOf%28java.lang.Object%29">String.value(Object)</a> to reduce unwanted <a href="http://java.sun.com/javase/6/docs/api/java/lang/NullPointerException.html">NullPointerException</a>s. There are <a href="http://en.wikibooks.org/wiki/Java_Programming/Preventing_NullPointerException">several other</a> simple <a href="http://blog.reindel.com/2007/12/19/preventing-the-nullpointerexception-in-java/">techniques</a> one can use to reduce or eliminate the <a href="http://www.roseindia.net/software-tutorials/detail/22289">occurrences</a> of this common type of <a href="http://java.sun.com/javase/6/docs/api/java/lang/RuntimeException.html">RuntimeException</a> that has been with us since <a href="http://user.cs.tu-berlin.de/%7Ejutta/ht/JDK-1.0-quickref.html">JDK 1.0</a>. This blog post collects and summarizes some of the most popular of these techniques.<br><br><b>Check Each Object For Null Before Using</b><br><br>The most sure way to avoid a <a href="http://basicsuncovered.blogspot.com/2005/11/null-pointer-exception.html">NullPointerException</a> is to check all object references to ensure that they are not null before accessing one of the object's fields or methods. As the following example indicates, this is a very simple technique.<br><br><pre style="background: rgb(246,248,255); color: #000020"><span style="color: #200080; font-weight: bold">final</span> String causeStr = "adding String to Deque that is set to null."<span style="color: #308080">;</span><br><span style="color: #200080; font-weight: bold">final</span> String elementStr = "Fudd"<span style="color: #308080">;</span><br>Deque<String> deque = null<span style="color: #308080">;</span><br><br>try<br><span style="color: #406080">{</span><br> deque<span style="color: #308080">.</span>push<span style="color: #308080">(</span>elementStr<span style="color: #308080">)</span><span style="color: #406080">;</span><br> log<span style="color: #308080">(</span><span style="color: #1060b6">"Successful at "</span> <span style="color: #308080">+</span> causeStr<span style="color: #308080">,</span> <span style="color: #6679aa; font-weight: bold">System</span><span style="color: #308080">.</span>out<span style="color: #308080">)</span><span style="color: #406080">;</span><br><span style="color: #406080">}</span><br>catch (NullPointerException nullPointer)<br><span style="color: #406080">{</span><br> log<span style="color: #308080">(</span>causeStr<span style="color: #308080">,</span> nullPointer<span style="color: #308080">,</span> <span style="color: #6679aa; font-weight: bold">System</span><span style="color: #308080">.</span>out<span style="color: #308080">)</span><span style="color: #406080">;</span><br><span style="color: #406080">}</span><br><br>try<br><span style="color: #406080">{</span><br> <span style="color: #200080; font-weight: bold">if</span> <span style="color: #308080">(</span>deque <span style="color: #308080">=</span><span style="color: #308080">=</span> <span style="color: #200080; font-weight: bold">null</span><span style="color: #308080">)</span><br> <span style="color: #406080">{</span><br> deque <span style="color: #308080">=</span> <span style="color: #200080; font-weight: bold">new</span> LinkedList<span style="color: #308080"><</span><span style="color: #6679aa; font-weight: bold">String</span><span style="color: #308080">></span><span style="color: #308080">(</span><span style="color: #308080">)</span><span style="color: #406080">;</span><br> <span style="color: #406080">}</span><br> deque<span style="color: #308080">.</span>push<span style="color: #308080">(</span>elementStr<span style="color: #308080">)</span><span style="color: #406080">;</span><br> log<span style="color: #308080">(</span> <span style="color: #1060b6">"Successful at "</span> <span style="color: #308080">+</span> causeStr<br> <span style="color: #308080">+</span> <span style="color: #1060b6">" (by checking first for null and instantiating Deque implementation)"</span><span style="color: #308080">,</span><br> <span style="color: #6679aa; font-weight: bold">System</span><span style="color: #308080">.</span>out<span style="color: #308080">)</span><span style="color: #406080">;</span><br><span style="color: #406080">}</span><br>catch (NullPointerException nullPointer)<br><span style="color: #406080">{</span><br> log<span style="color: #308080">(</span>causeStr<span style="color: #308080">,</span> nullPointer<span style="color: #308080">,</span> <span style="color: #6679aa; font-weight: bold">System</span><span style="color: #308080">.</span>out<span style="color: #308080">)</span><span style="color: #406080">;</span><br><span style="color: #406080">}</span><br></pre><br>In the code above, the <a href="http://java.sun.com/javase/6/docs/api/java/util/Deque.html">Deque</a> used is intentionally initialized to null to facilitate the example. The code in the first <code>try</code> block does not check for null before trying to access a <a href="http://marxsoftware.blogspot.com/2008/10/java-se-6-deque.html">Deque</a> method. The code in the second <code>try</code> block does check for null and instantiates an implementation of the <code>Deque</code> (<a href="http://java.sun.com/javase/6/docs/api/java/util/LinkedList.html">LinkedList</a>) if it is null. The output from both examples looks like this:<br><br><pre style="font-size: 9pt; overflow: auto" name="code">ERROR: NullPointerException encountered while trying to adding </pre><pre style="font-size: 9pt; overflow: auto" name="code">String to Deque that is set to null.<br>java.lang.NullPointerException<br>INFO: Successful at adding String to Deque that is set to null. </pre><pre style="font-size: 9pt; overflow: auto" name="code">(by checking first for null and instantiating Deque implementation)</pre><br>The message following ERROR in the output above indicates that a <code>NullPointerException</code> is thrown when a method call is attempted on the null <code>Deque</code>. The message following INFO in the output above indicates that by checking <code>Deque</code> for null first and then instantiating a new implementation for it when it is null, the exception was avoided altogether.<br><br>This approach is often used and, as shown above, can be very useful in avoiding unwanted (unexpected) <code>NullPointerException</code> instances. However, it is not without its costs. Checking for null before using every object can bloat the code, can be tedious to write, and opens more room for problems with development and maintenance of the additional code. For this reason, there has been talk of introducing Java language support for <a href="http://tech.puredanger.com/java7/#null">built-in null detection</a>, <a href="http://www.cs.virginia.edu/colloquia/event730.html">automatic adding</a> of these checks for null after the initial coding, <a href="http://www.jroller.com/scolebourne/entry/java_7_null_safe_types">null-safe types</a>, use of <a href="http://www.developer.com/design/article.php/3308941">Aspect-Oriented Programming</a> (<a href="http://www.onjava.com/pub/a/onjava/2004/01/14/aop.html">AOP</a>) to add <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=43091">null checking to byte code</a>, and other <a href="http://www.dcs.gla.ac.uk/%7Ehuttona/npd/">null-detection tools</a>.<br><br><a href="http://groovy.codehaus.org/">Groovy</a> already provides a <a href="http://jlorenzen.blogspot.com/2007/10/using-groovy-to-easily-avoid-nasty.html">convenient mechanism</a> for dealing with object references that are potentially null. Groovy's <a href="http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28%3F.%29">safe navigation operator</a> (<code>?.</code>) returns null rather than throwing a <code>NullPointerException</code> when a null object reference is accessed.<br><br>Because checking null for every object reference can be tedious and does bloat the code, many developers choose to judiciously select which objects to check for null. This typically leads to checking of null on all objects of <a href="http://en.wikibooks.org/wiki/Java_Programming/Preventing_NullPointerException#Check_all_references_obtained_from_.27untrusted.27_methods">potentially unknown origins</a>. The idea here is that objects can be checked at exposed interfaces and then be assumed to be safe after the initial check.<br><br>This is a situation where the <a href="http://www.devdaily.com/java/edu/pj/pj010018/">ternary operator</a> can be particularly useful. Instead of<br><pre style="background: rgb(246,248,255); color: #000020"><span style="color: #595979">// retrieved a BigDecimal called someObject</span><br>String returnString<span style="color: #308080">;</span><br>if (someObject != null)<br><span style="color: #406080">{</span><br> returnString <span style="color: #308080">=</span> someObject<span style="color: #308080">.</span>toEngineeringString<span style="color: #308080">(</span><span style="color: #308080">)</span><span style="color: #406080">;</span><br><span style="color: #406080">}</span><br>else<br><span style="color: #406080">{</span><br> returnString <span style="color: #308080">=</span> <span style="color: #1060b6">""</span><span style="color: #406080">;</span><br><span style="color: #406080">}</span><br></pre><br>the ternary operator supports this more concise syntax<br><br><pre style="background: rgb(246,248,255); color: #000020"><span style="color: #595979">// retrieved a BigDecimal called someObject</span><br><span style="color: #200080; font-weight: bold">final</span> String returnString = (someObject != null)<br> ? someObject.toEngineeringString()<br> : ""<span style="color: #308080">;</span><br>}<br></pre><br><b>Check Method Arguments for Null</b><br><br>The technique just discussed can be used on all objects. As stated in that technique's description, many developers choose to only check objects for null when they come from "untrusted" sources. This often means testing for null first thing in methods exposed to external callers. For example, in a particular class, the developer might choose to check for null on all objects passed to <code>public</code> methods, but not check for null in <code>private</code> methods.<br><br>The following code demonstrates this checking for null on method entry. It includes a single method as the demonstrative method that turns around and calls two methods, passing each method a single null argument. One of the methods receiving a null argument checks that argument for null first, but the other just assumes the passed-in parameter is not null.<br><br><pre style="background: rgb(246,248,255); color: #000020"><span style="color: #3f7f8f">/**</span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"> Append predefined text String to the provided StringBuilder.</span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"></span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">@param</span><span style="color: #3f7f8f"> builder The StringBuilder that will have text appended to it</span><span style="color: #7f9fbf; font-weight: bold">;</span><span style="color: #3f7f8f"> should</span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"> be non</span><span style="color: #7f9fbf; font-weight: bold">-</span><span style="color: #3f7f8f">null.</span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">@throws</span><span style="color: #3f7f8f"> IllegalArgumentException Thrown if the provided StringBuilder is</span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"> null.</span><br><span style="color: #3f7f8f"> */</span><br> <span style="color: #200080; font-weight: bold">private</span> void appendPredefinedTextToProvidedBuilderCheckForNull(<br> <span style="color: #200080; font-weight: bold">final</span> StringBuilder builder)<br> <span style="color: #406080">{</span><br> <span style="color: #200080; font-weight: bold">if</span> <span style="color: #308080">(</span>builder <span style="color: #308080">=</span><span style="color: #308080">=</span> <span style="color: #200080; font-weight: bold">null</span><span style="color: #308080">)</span><br> <span style="color: #406080">{</span><br> <span style="color: #200080; font-weight: bold">throw</span> <span style="color: #200080; font-weight: bold">new</span> <span style="color: #6679aa; font-weight: bold">IllegalArgumentException</span><span style="color: #308080">(</span><br> <span style="color: #1060b6">"The provided StringBuilder was null; non-null value must be provided."</span><span style="color: #308080">)</span><span style="color: #406080">;</span><br> <span style="color: #406080">}</span><br> builder<span style="color: #308080">.</span>append<span style="color: #308080">(</span><span style="color: #1060b6">"Thanks for supplying a StringBuilder."</span><span style="color: #308080">)</span><span style="color: #406080">;</span><br> <span style="color: #406080">}</span><br><br> <span style="color: #3f7f8f">/**</span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"> Append predefined text String to the provided StringBuilder.</span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"></span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">@param</span><span style="color: #3f7f8f"> builder The StringBuilder that will have text appended to it</span><span style="color: #7f9fbf; font-weight: bold">;</span><span style="color: #3f7f8f"> should</span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"> be non</span><span style="color: #7f9fbf; font-weight: bold">-</span><span style="color: #3f7f8f">null.</span><br><span style="color: #3f7f8f"> */</span><br> <span style="color: #200080; font-weight: bold">private</span> void appendPredefinedTextToProvidedBuilderNoCheckForNull(<br> <span style="color: #200080; font-weight: bold">final</span> StringBuilder builder)<br> <span style="color: #406080">{</span><br> builder<span style="color: #308080">.</span>append<span style="color: #308080">(</span><span style="color: #1060b6">"Thanks for supplying a StringBuilder."</span><span style="color: #308080">)</span><span style="color: #406080">;</span><br> <span style="color: #406080">}</span><br><br> <span style="color: #3f7f8f">/**</span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"> Demonstrate effect of checking parameters for null before trying to use</span><br><span style="color: #3f7f8f"> </span><span style="color: #7f9fbf; font-weight: bold">*</span><span style="color: #3f7f8f"> passed</span><span style="color: #7f9fbf; font-weight: bold">-</span><span style="color: #3f7f8f">in parameters that are potentially null.</span><br><span style="color: #3f7f8f"> */</span><br> <span style="color: #200080; font-weight: bold">public</span> void demonstrateCheckingArgumentsForNull()<br> <span style="color: #406080">{</span><br> <span style="color: #200080; font-weight: bold">final</span> <span style="color: #6679aa; font-weight: bold">String</span> causeStr <span style="color: #308080">=</span> <span style="color: #1060b6">"provide null to method as argument."</span><span style="color: #406080">;</span><br> logHeader<span style="color: #308080">(</span><span style="color: #1060b6">"DEMONSTRATING CHECKING METHOD PARAMETERS FOR NULL"</span><span style="color: #308080">,</span> <span style="color: #6679aa; font-weight: bold">System</span><span style="color: #308080">.</span>out<span style="color: #308080">)</span><span style="color: #406080">;</span><br><br> <span style="color: #200080; font-weight: bold">try</span><br> <span style="color: #406080">{</span><br> appendPredefinedTextToProvidedBuilderNoCheckForNull<span style="color: #308080">(</span><span style="color: #200080; font-weight: bold">null</span><span style="color: #308080">)</span><span style="color: #406080">;</span><br> <span style="color: #406080">}</span><br> <span style="color: #200080; font-weight: bold">catch</span> <span style="color: #308080">(</span><span style="color: #6679aa; font-weight: bold">NullPointerException</span> nullPointer<span style="color: #308080">)</span><br> <span style="color: #406080">{</span><br> log<span style="color: #308080">(</span>causeStr<span style="color: #308080">,</span> nullPointer<span style="color: #308080">,</span> <span style="color: #6679aa; font-weight: bold">System</span><span style="color: #308080">.</span>out<span style="color: #308080">)</span><span style="color: #406080">;</span><br> <span style="color: #406080">}</span><br><br> <span style="color: #200080; font-weight: bold">try</span><br> <span style="color: #406080">{</span><br> appendPredefinedTextToProvidedBuilderCheckForNull<span style="color: #308080">(</span><span style="color: #200080; font-weight: bold">null</span><span style="color: #308080">)</span><span style="color: #406080">;</span><br> <span style="color: #406080">}</span><br> <span style="color: #200080; font-weight: bold">catch</span> <span style="color: #308080">(</span><span style="color: #6679aa; font-weight: bold">IllegalArgumentException</span> illegalArgument<span style="color: #308080">)</span><br> <span style="color: #406080">{</span><br> log<span style="color: #308080">(</span>causeStr<span style="color: #308080">,</span> illegalArgument<span style="color: #308080">,</span> <span style="color: #6679aa; font-weight: bold">System</span><span style="color: #308080">.</span>out<span style="color: #308080">)</span><span style="color: #406080">;</span><br> <span style="color: #406080">}</span><br> <span style="color: #406080">}</span><br></pre><br>When the above code is executed, the output appears as shown next.<br><pre style="font-size: 9pt" name="code">ERROR: NullPointerException encountered while trying to provide null to </pre><pre style="font-size: 9pt" name="code">method as argument.<br>java.lang.NullPointerException<br>ERROR: IllegalArgumentException encountered while trying to provide null </pre><pre style="font-size: 9pt" name="code">to method as argument.<br>java.lang.IllegalArgumentException: The provided StringBuilder was null;</pre><pre style="font-size: 9pt" name="code">non-null value must be provided.</pre><br><br>In both cases, an error message was logged. However, the case in which a null was checked for threw an advertised <a href="http://java.sun.com/javase/6/docs/api/java/lang/IllegalArgumentException.html">IllegalArgumentException</a> that included additional context information about when the null was encountered. Alternatively, this null parameter could have been handled in a variety of ways. For the case in which a null parameter was not handled, there were no options for how to handle it. Many people prefer to throw a <code>NullPolinterException</code> with the additional context information when a null is explicitly discovered (see Item #60 in the Second Edition of <i>Effective Java</i> or Item #42 in First Edition), but I have a slight preference for <code>IllegalArgumentException</code> when it is explicitly a method argument that is null because I think the very exception adds context details and it is easy to include "null" in the subject.<br><br>The technique of checking method arguments for null is really a subset of the more general technique of checking all objects for null. However, as outlined above, arguments to publicly exposed methods are often the least trusted in an application and so checking them may be more important than checking the average object for null.<br><br>Checking method parameters for null is also a subset of the more general practice of checking method parameters for general validity as discussed in Item #38 of the Second Edition of <i>Effective Java</i> (Item 23 in First Edition).<br><br><br><b>Consider Primitives Rather than Objects</b><br><br>I don't think it is a good idea to select a primitive data type (such as <code>int</code>) over its corresponding object reference type (such as <a href="http://java.sun.com/javase/6/docs/api/java/lang/Integer.html">Integer</a>) simply to avoid the possibility of a <code>NullPointerException</code>, but there is no denying that one of the advantages of primitive types is that they do not lead to <code>NullPointerException</code>s. However, primitives still must be checked for validity (a month cannot be a negative integer) and so this benefit may be small. On the other hand, primitives cannot be used in <a href="http://java.sun.com/docs/books/tutorial/collections/index.html">Java Collections</a> and there are times one wants the ability to set a value to null.<br><br>The most important thing is to be very cautious about the combination of primitives, reference types, and autoboxing. There is a warning in <i>Effective Java</i> (Second Edition, Item #49) regarding the dangers, including throwing of <code>NullPointerException</code>, related to careless mixing of primitive and reference types.<br><br><br><b>Carefully Consider Chained Method Calls</b><br><br>A <code>NullPointerException</code> can be very easy to find because a line number will state where it occurred. For example, a stack trace might look like that shown next:<br><br><pre class="text" name="code" 9pt;="">java.lang.NullPointerException<br> at dustin.examples.AvoidingNullPointerExamples.</pre><pre class="text" name="code" 9pt;="">demonstrateNullPointerExceptionStackTrace(AvoidingNullPointerExamples.java:222)<br> at dustin.examples.</pre><pre class="text" name="code" 9pt;="">AvoidingNullPointerExamples.main(AvoidingNullPointerExamples.java:247)</pre><br>The stack trace makes it obvious that the <code>NullPointerException</code> was thrown as a result of code executed on line 222 of <code>AvoidingNullPointerExamples.java</code>. Even with the line number provided, it can still be difficult to narrow down which object is null if there are multiple objects with methods or fields accessed on the same line.<br><br>For example, a statement like <code>someObject.getObjectA().getObjectB().getObjectC().toString();</code> has four possible calls that might have thrown the <code>NullPointerException</code> attributed to the same line of code. Using a debugger can help with this, but there may be situations when it is preferable to simply break the above code up so that each call is performed on a separate line. This allows the line number contained in a stack trace to easily indicate which exact call was the problem. Furthermore, it facilitates explicit checking each object for null. However, on the downside, breaking up the code increases the line of code count (<a href="http://marxsoftware.blogspot.com/2008/09/lines-of-code-and-unintended.html">to some that's a positive!</a>) and may not always be desirable, especially if one is certain none of the methods in question will ever be null.<br><br><br><b>Make NullPointerExceptions More Informative</b><br><br>In the above recommendation, the warning was to consider carefully use of method call chaining primarily because it made having the line number in the stack trace for a <code>NullPointerException</code> less helpful than it otherwise might be. However, the line number is only shown in a stack trace when the code was compiled with the debug flag turned on. If it was compiled without debug, the stack trace looks like that shown next:<br><br><pre style="font-size: 9pt" class="text" name="code">java.lang.NullPointerException<br> at dustin.examples.AvoidingNullPointerExamples.</pre><pre style="font-size: 9pt" class="text" name="code">demonstrateNullPointerExceptionStackTrace(Unknown Source)<br> at dustin.examples.AvoidingNullPointerExamples.main(Unknown Source)</pre><br>As the above output demonstrates, there is a method name, but not no line number for the <code>NullPointerException</code>. This makes it more difficult to immediately identify what in the code led to the exception. One way to address this is to provide context information in any thrown <code>NullPointerException</code>. This idea was demonstrated earlier when a <code>NullPointerException</code> was caught and re-thrown with additional context information as a <code>IllegalArgumentException</code>. However, even if the exception is simply re-thrown as another <code>NullPointerException</code> with context information, it is still helpful. The context information helps the person debugging the code to more quickly identify the true cause of the problem.<br><br>The following example demonstrates this principle.<br><br><pre style="background: rgb(246,248,255); color: #000020"><span style="color: #200080; font-weight: bold">final</span> Calendar nullCalendar = null<span style="color: #308080">;</span><br><br>try<br><span style="color: #406080">{</span><br> <span style="color: #200080; font-weight: bold">final</span> <span style="color: #6679aa; font-weight: bold">Date</span> date <span style="color: #308080">=</span> nullCalendar<span style="color: #308080">.</span>getTime<span style="color: #308080">(</span><span style="color: #308080">)</span><span style="color: #406080">;</span><br><span style="color: #406080">}</span><br>catch (NullPointerException nullPointer)<br><span style="color: #406080">{</span><br> log<span style="color: #308080">(</span><span style="color: #1060b6">"NullPointerException with useful data"</span><span style="color: #308080">,</span> nullPointer<span style="color: #308080">,</span> <span style="color: #6679aa; font-weight: bold">System</span><span style="color: #308080">.</span>out<span style="color: #308080">)</span><span style="color: #406080">;</span><br><span style="color: #406080">}</span><br><br>try<br><span style="color: #406080">{</span><br> <span style="color: #200080; font-weight: bold">if</span> <span style="color: #308080">(</span>nullCalendar <span style="color: #308080">=</span><span style="color: #308080">=</span> <span style="color: #200080; font-weight: bold">null</span><span style="color: #308080">)</span><br> <span style="color: #406080">{</span><br> <span style="color: #200080; font-weight: bold">throw</span> <span style="color: #200080; font-weight: bold">new</span> <span style="color: #6679aa; font-weight: bold">NullPointerException</span><span style="color: #308080">(</span><span style="color: #1060b6">"Could not extract Date from provided Calendar"</span><span style="color: #308080">)</span><span style="color: #406080">;</span><br> <span style="color: #406080">}</span><br> <span style="color: #200080; font-weight: bold">final</span> <span style="color: #6679aa; font-weight: bold">Date</span> date <span style="color: #308080">=</span> nullCalendar<span style="color: #308080">.</span>getTime<span style="color: #308080">(</span><span style="color: #308080">)</span><span style="color: #406080">;</span><br><span style="color: #406080">}</span><br>catch (NullPointerException nullPointer)<br><span style="color: #406080">{</span><br> log<span style="color: #308080">(</span><span style="color: #1060b6">"NullPointerException with useful data"</span><span style="color: #308080">,</span> nullPointer<span style="color: #308080">,</span> <span style="color: #6679aa; font-weight: bold">System</span><span style="color: #308080">.</span>out<span style="color: #308080">)</span><span style="color: #406080">;</span><br><span style="color: #406080">}</span><br></pre><br>The output from running the above code looks as follows.<br><br><pre style="font-size: 9pt" class="text" name="code">ERROR: NullPointerException encountered while trying to NullPointerException </pre><pre style="font-size: 9pt" class="text" name="code">with useful data<br>java.lang.NullPointerException<br>ERROR: NullPointerException encountered while trying to</pre><pre style="font-size: 9pt" class="text" name="code">NullPointerException with useful data<br>java.lang.NullPointerException: Could not extract Date from provided Calendar</pre><br>The first error does not provide any context information and only conveys that it is a <code>NullPointerException</code>. The second error, however, had explicit context information added to it which would go a long way in helping identify the source of the exception.<br><br><br><b>Use String.valueOf Rather than toString</b><br><br>As described previously, one of the surest methods for avoiding <code>NullPointerException</code> is to check the object being referenced for null first. The <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#valueOf%28java.lang.Object%29">String.valueOf(Object)</a> method is a good example of a case where this check for null can be done implicitly without any additional effort on the developer's part. I <a href="http://marxsoftware.blogspot.com/2009/04/value-of-stringvalueof.html">blogged on this previously</a>, but include a brief example of its use here.<br /><p> </p><br /><p>Source : <a href="http://marxsoftware.blogspot.com/2009/04/effective-java-nullpointerexception.html">Inspired by actual events</a></p> Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com1tag:blogger.com,1999:blog-7703735018951306032.post-2812017665939499802011-07-15T04:07:00.000+05:302011-07-15T04:13:27.264+05:30Stringifying Java Arrays<a href="http://www.oracle.com/technetwork/java/javase/index-jsp-135232.html">J2SE 5</a> provided <a href="http://java.sun.com/developer/technicalArticles/releases/j2se15/">significant new language features</a> that made Java significantly easier to use and more expressive than it had ever been. Although "big" <a href="http://download.oracle.com/javase/1.5.0/docs/relnotes/features.html">new J2SE 5 features</a> such as <a href="http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html">enums</a>, <a href="http://download.oracle.com/javase/1.5.0/docs/guide/language/generics.html">generics</a>, and <a href="http://download.oracle.com/javase/1.5.0/docs/guide/language/annotations.html">annotations</a>, there was a plethora of new APIs and methods that have made our lives easier ever since. In this post, I briefly look at two of my favorites when <a href="http://www.devarticles.com/c/a/Java/Whats-New-in-Java-15-Tiger/">dealing with Java arrays</a>: the <a href="http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#toString%28java.lang.Object[]%29">Arrays.toString(Object[])</a> method and the <a href="http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#deepToString%28java.lang.Object[]%29">Arrays.deepToString(Object[])</a> method.<br><br>The <a href="http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html">Arrays class</a> has been around since JDK 1.2, but the methods for conveniently and simply converting arrays to a readable String including relevant array content without using <a href="http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList%28T...%29">Arrays.asList()</a> were added with J2SE 5. Both <code>Arrays.toString(Object[])</code> and <code>Arrays.deepToString(Object[])</code> are static methods that act upon the arrays provided to them. The former, <code>Arrays.toString(Object[])</code>, is intended for single-dimension arrays while the latter, <code>Arrays.deepToString(Object[])</code>, is intended for multi-dimensional arrays. As my example later in this post will demonstrate, the multi-dimension <code>deepToString</code> will produce expected results even for single-dimension arrays. The two methods also provide easy and safe null handling, <a href="http://k2java.blogspot.com/2011/07/effective-java-how-to-avoid-npe-null.html">something that I appreciate</a>.<br><br>The next code listing is for a simple demonstration class that demonstrates trying to put the contents of various types of Java arrays into a String format. The types of arrays demonstrated are a single dimension array, a double dimensional array representing multi-dimensional arrays of various sizes, and an array that is really just null. The three methods demonstrated for getting a String out of these three types of arrays are (1) simple <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#toString%28%29">Object.toString()</a> on each array (implicitly in case of null array to avoid the dreaded <a href="http://download.oracle.com/javase/6/docs/api/java/lang/NullPointerException.html">NullPointerException</a>), (2) <code>Arrays.toString(Object[])</code>, and (3) <code>Arrays.deepToString(Object[])</code>.<br> <div id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">package</span> com.vaani.arraytest;<br><br><span style="color: #0000ff">import</span> java.util.Arrays;<br><span style="color: #0000ff">import</span> <span style="color: #0000ff">static</span> java.lang.System.out;<br><br><span style="color: #008000">/**</span><br><span style="color: #008000"> * Simple demonstration of Arrays.toString(Object[]) method and the</span><br><span style="color: #008000"> * Arrays.deepToString(Object[]) method.</span><br><span style="color: #008000"> */</span><br><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> Array2String<br>{<br> <span style="color: #008000">/**</span><br><span style="color: #008000"> * Demonstrate usage and behavior of Arrays.toString(Object[]).</span><br><span style="color: #008000"> */</span><br> <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> demonstrateArraysToString()<br> {<br> out.println(<br> <span style="color: #006080">"Single Dimension Arrays.toString: "</span><br> + Arrays.toString(prepareSingleDimensionArray()));<br> out.println(<br> <span style="color: #006080">"Double Dimension Arrays.toString: "</span><br> + Arrays.toString(prepareDoubleDimensionArray()));<br> out.println(<br> <span style="color: #006080">"Null Array Arrays.toString: "</span><br> + Arrays.toString(prepareNullArray()));<br> }<br><br> <span style="color: #008000">/**</span><br><span style="color: #008000"> * Demonstrate usage and behavior of Arrays.deepToString(Object[]).</span><br><span style="color: #008000"> */</span><br> <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> demonstrateArraysDeepToString()<br> {<br> out.println(<br> <span style="color: #006080">"Single Dimension Arrays.deepToString: "</span><br> + Arrays.deepToString(prepareSingleDimensionArray()));<br> out.println(<br> <span style="color: #006080">"Double Dimension Arrays.deepToString: "</span><br> + Arrays.deepToString(prepareDoubleDimensionArray()));<br> out.println(<br> <span style="color: #006080">"Null Array Arrays.deepToString: "</span><br> + Arrays.deepToString(prepareNullArray()));<br> }<br><br> <span style="color: #008000">/**</span><br><span style="color: #008000"> * Demonstrate attempting to get String version of array with simple toString()</span><br><span style="color: #008000"> * call (not using Arrays class).</span><br><span style="color: #008000"> */</span><br> <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> demonstrateDirectArrayString()<br> {<br> out.println(<span style="color: #006080">"Single Dimension toString(): "</span> + prepareSingleDimensionArray().toString());<br> out.println(<span style="color: #006080">"Double Dimension toString(): "</span> + prepareDoubleDimensionArray());<br> out.println(<span style="color: #006080">"Null Array toString(): "</span> + prepareNullArray());<br> }<br><br> <span style="color: #008000">/**</span><br><span style="color: #008000"> * Prepare a single-dimensional array to be used in demonstrations.</span><br><span style="color: #008000"> *</span><br><span style="color: #008000"> * @return Single-dimensional array.</span><br><span style="color: #008000"> */</span><br> <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> Object[] prepareSingleDimensionArray()<br> {<br> <span style="color: #0000ff">final</span> String[] names = {<span style="color: #006080">"Aaron"</span>, <span style="color: #006080">"Bianca"</span>, <span style="color: #006080">"Charles"</span>, <span style="color: #006080">"Denise"</span>, <span style="color: #006080">"Elmer"</span>};<br> <span style="color: #0000ff">return</span> names;<br> }<br><br> <span style="color: #008000">/**</span><br><span style="color: #008000"> * Prepare a double-dimension array to be used in demonstrations.</span><br><span style="color: #008000"> *</span><br><span style="color: #008000"> * @return Double-dimensional array.</span><br><span style="color: #008000"> */</span><br> <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> Object[] prepareDoubleDimensionArray()<br> {<br> <span style="color: #0000ff">final</span> Object[][] namesAndAges = {<br> {<span style="color: #006080">"Aaron"</span>, 10}, {<span style="color: #006080">"Bianca"</span>, 25}, {<span style="color: #006080">"Charles"</span>, 32}, {<span style="color: #006080">"Denise"</span>, 29}, {<span style="color: #006080">"Elmer"</span>, 67}};<br> <span style="color: #0000ff">return</span> namesAndAges;<br> }<br><br> <span style="color: #008000">/**</span><br><span style="color: #008000"> * Prepare a null array.</span><br><span style="color: #008000"> *</span><br><span style="color: #008000"> * @return Array that is really null.</span><br><span style="color: #008000"> */</span><br> <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> Object[] prepareNullArray()<br> {<br> <span style="color: #0000ff">return</span> null;<br> }<br><br> <span style="color: #008000">/**</span><br><span style="color: #008000"> * Main executable function for demonstrating Arrays.toString(Object[]) and</span><br><span style="color: #008000"> * Arrays.deepToString(Object[]) methods.</span><br><span style="color: #008000"> */</span><br> <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> main(<span style="color: #0000ff">final</span> String[] arguments)<br> {<br> out.println(<span style="color: #006080">"\n\n\nDemonstrating direct array to string using toString():"</span>);<br> demonstrateDirectArrayString();<br> <br> out.println(<span style="color: #006080">"\n\n\nDemonstrating Arrays.toString() to get arrays as String:"</span>);<br> demonstrateArraysToString();<br> <br> out.println(<span style="color: #006080">"\n\n\nDemonstrating Arrays.deepToString() to get the String:"</span>);<br> demonstrateArraysDeepToString();<br> }<br>}<br><br></pre><br></div>The above code exercises the three mentioned approaches for getting a String out of an array on the three different types of arrays: single dimension, multi dimension, and null array. The output from running this code demonstrates the utility of the different approaches. That output is shown next. <br><br /><div id="codeSnippetWrapper"><pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; background-color: #f4f4f4; margin: 0em; border-left-style: none; padding-left: 0px; width: 100%; padding-right: 0px; font-family: 'Courier New', courier, monospace; direction: ltr; border-top-style: none; color: black; border-right-style: none; font-size: 10pt; overflow: visible; padding-top: 0px" id="codeSnippet">Demonstrating direct array to string using toString():<br>Single Dimension toString(): [Ljava.lang.String;@3e25a5<br>Double Dimension toString(): [[Ljava.lang.Object;@19821f<br>Null Array toString(): null<br><span style="color: #008000">///////////</span><br>Demonstrating Arrays.toString() to get arrays as String:<br>Single Dimension Arrays.toString: [Aaron, Bianca, Charles, Denise, Elmer]<br>Double Dimension Arrays.toString: [[Ljava.lang.Object;@addbf1, [Ljava.lang.Object;@42e816, [Ljava.lang.Object;@9304b1, [Ljava.lang.Object;@190d11, [Ljava.lang.Object;@a90653]<br>Null Array Arrays.toString: null<br><br><br><span style="color: #008000">///////////</span><br>Demonstrating Arrays.deepToString() to get the String:<br>Single Dimension Arrays.deepToString: [Aaron, Bianca, Charles, Denise, Elmer]<br>Double Dimension Arrays.deepToString: [[Aaron, 10], [Bianca, 25], [Charles, 32], [Denise, 29], [Elmer, 67]]<br>Null Array Arrays.deepToString: null<br></pre><br></div>The code above and its corresponding output lead to several observations:<br><br><br /><ol><br /><li>Simple <code>Object.toString()</code> on arrays is seldom what we want as it only prints the String representation of the array itself and not of its contents.<br /><li><code>Arrays.toString(Object[])</code> will print a String representation for multi-dimensional arrays, but this representation suffers the same drawbacks as <code>Object.toString()</code> after the first dimension. The first dimension (and only dimension for a single dimension array) gets put into an expected String, but deeper dimensions have the same <code>Object.toString()</code> treatment.<br /><li><code>Arrays.deepToString(Object[])</code>, while intended for multi-dimensional arrays, produces the expected results for both single and multi-dimensional arrays.<br /><li>Both <code>Arrays.toString(Object[])</code> and <code>Arrays.deepToString(Object[])</code> handle null array gracefully, simply returning a String "null".</li></ol><br /><div>I tend to use <a href="http://download.oracle.com/javase/tutorial/collections/index.html">Java Collections</a> far more than I use <a href="http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html">Java arrays</a>. However, when I do need to work with arrays, it is nice to have the many useful features of the <code>java.util.Arrays</code> class. As this post has demonstrated, <code>Arrays.toString(Object[])</code> and <code>Arrays.deepToString(Object[])</code> are particularly valuable in obtaining a useful String representation of an array's contents. The <a href="http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html">java.util.Arrays</a> class provides similar "deep" methods for performing equals and hashCode functionality on multi-dimensional arrays: <a href="http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#deepEquals%28java.lang.Object[],%20java.lang.Object[]%29">Arrays.deepEquals</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#deepHashCode%28java.lang.Object[]%29">Arrays.deepHashCode</a>.</div> Kinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0tag:blogger.com,1999:blog-7703735018951306032.post-38256884062830687132011-07-15T03:32:00.000+05:302011-07-15T03:32:04.108+05:30javac's -Xprint OptionKinshuk Chandrahttp://www.blogger.com/profile/01344610750518430564noreply@blogger.com0