Monday 16 January 2012

Literals

Look at the long value 5432l.

Note the subtle difference in shape between the digit 1 at the beginning of the left operand and the lowercase letter el at the end of the right operand. The digit 1 has an acute angle between the horizontal stroke, or arm, and the vertical stroke, or stem. The lowercase letter el, by contrast, has a right angle between the arm and the stem.
Before you cry “foul,” note that this issue has caused real confusion. So its better to use "L" rather than l

Java IO Overview

We can diagrammatically cover how java io looks like from bird eye view.

So this is basic java IO :
Now looking at the class hierarchy :

Sunday 15 January 2012

Playing with double datatype using Java

Do you guess the output values of the following code snippets (in  Java) ? .


                        double d5 =99999.99;
                        double d6 =999999.99;
                        double d7 =9999999.99;
                        double d8 =99999999.99;
                        double d9 =999999999.99;
                        double d10=9999999999.99;

                        System.out.println("d5 ="+d5);
                        System.out.println("d6 ="+d6);
                        System.out.println("d7 ="+d7);
                        System.out.println("d8 ="+d8);
                        System.out.println("d9 ="+d9);
                        System.out.println("d10="+d10);

Here is the output:




d5 =99999.99
d6 =999999.99
d7 =9999999.99
d8 =9.999999999E7
d9 =9.9999999999E8
d10=9.99999999999E9

Have you noticed the values of d8, d9 and d10?. The output value is in  E (exponential) format. Java is internally doing this conversion while convert the datatype double to String.  If the value is  greater than or equal to 10-3 but less than 107, then the output will be normal. Otherwise the value will be in Exponential.

To print the values all in normal format, use the "java.text.DecimalFormat" class. Check the following code snippet.


                        DecimalFormat d = new DecimalFormat("##.##");
                        System.out.println("d5 ="+d.format(d5));
                        System.out.println("d6 ="+d.format(d6));
                        System.out.println("d7 ="+d.format(d7));
                        System.out.println("d8 ="+d.format(d8));
                        System.out.println("d9 ="+d.format(d9));
                        System.out.println("d10="+d.format(d10));
The output is


d5 =99999.99
d6 =999999.99
d7 =9999999.99
d8 =99999999.99
d9 =999999999.99
d10=9999999999.99

Refer the following URL to get the more details about the Double,.

Saturday 14 January 2012

Generic class names to avoid

Overview

Java (Oracle Java update 2) has many classes with the same generic name. To avoid further confusion, I suggest avoiding these names if you can.

Most repeated

The following class names are repeated, 19 Handler, 16 Messages, 13 Util, 10 Element, 8 Attribute, 7 SecuritySupport, 7 Node, 6 Provider, 6 Header, 6 FactoryFinder, 6 Document. 5 SOAPBinding, 5 Repository, 5 Ref, 5 ORB, 5 Name, 5 Constants, 5 Connection, 5 Comment, 5 Binding, 5 Attributes,
This excludes the Apache XML library which repeats many names. If you include these libraries there are 26 classes called SecuritySupport.

Four times

Window, Version, Utility, Timer, Text, State, Signature, ServiceName, ServiceConfigurationError, Service, ResourceLoader, Queue, Policy, Parser, Operation, NativeLibLoader, Message, Label, JSObject, GetPropertyAction, FactoryFinder$ConfigurationError, Event, ConstantPool, AppletAudioClip, Action,

Three times

XMLWriter, Wrapper, WildcardTypeImpl, Visitor, Validator, Types, TypeMismatch, TypeInfo, Type, Trace, Token, Timestamp, Target, Symbol, StyleSheet, SOAPFault, SOAPConstants, Scope, Schema, ResourceManager, Resource, Resolver, Request, Reference, Properties, ProgressMonitor, PrincipalImpl, Principal, Port, PooledConnection, Pool, Pipe, Patcher, ParseException, OutputStream, ObjectStreamField, Navigator, NamespaceSupport$Context, NamespaceSupport, MimeType, MemoryCache, MarshalException, Manifest, Main, Location, List, JarVerifier, IOR, Invoker, InvalidName, Introspector, InputStream, Import, ImageCache, HTMLDocument, HTMLCollection, Headers, FinalArrayList, Filter, FileSystem, FactoryImpl, Extension, EventListener, ErrorHandler, Entity, EncryptedPrivateKeyInfo, Delegate, DataSource, CurrentOperations, CurrentHelper, Current, Counter, Context, ContentType, Config, Code, CharacterData, Certificate, CacheTable, Cache, Bridge, Base64, Authenticator, AttributeList, ArrayType, Array, AppletAudioClip$1, Annotation,

Appearing twice

Too many to mention.

Java Puzzler - double chars

The following compiles and produces an output. Can you explain why?

char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'

Here is a hint for a simpler example.

byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40

Friday 13 January 2012

Exception Wrapping for persistence

Data can be stored in various ways, for example:
  • a relational database
  • text files
  • on the web (for example, fetching the weather forecast from a web site)
If the storage method changes, then the low level Exception objects thrown by the data access layer can also change. For example, when the data store is moved from text files to a relational database, IOException is replaced with SQLException. Otherwise there will be compilation errors throughout the code.

Removing the compilation point of view, lets look at the design point. Then consider a typical J2EE application that has a simple web layer, a business layer and a database layer. If some SQL query in the database layer goes completely wrong I will get an SQLException of some sort. In your point of view the web application (being the topmost layer) will catch this exception in the end.

This defeats the entire purpose of having a multitier (3+) architecture. I'm now dependent on the database layer in the web layer, because all exceptions are thrown all the way upwards.

The point of the PersistenceException is that it keeps the tiers independent from each other, except for the tier beneath it. The web layer doesn't care if it's an SQLException. It only needs to know something went wrong with the business logic, and more specifically with the persistence of business data objects.

In any case, the 'business code' knows more of what to do than the layers above it. If it can't do anything meaningful with it, you can either log it or perform some other action. The question is: what would a layer above it (eg. the web layer) know more of what to do than the business layer?

Exceptions Methods

 ollowing is the list of important medthods available in the Throwable class.
SNMethods with Description
1public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3public String toString()
Returns the name of the class concatenated with the result of getMessage()
4public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Effective Java Exception handling

1. Use checked exceptions when you know that or you can recover  from the exception without any side affects.
2. The best use of exceptions is to translate exception in the calling method to the exception which is more appropriate for it and you should let the cause of the exception flow from the called methods to the calling methods.
For this you should have one of the constructors of your Exception classes like
 1: // Exception with chaining-aware constructor
 2:   class HigherLevelException extends Exception {
 3:       HigherLevelException(Throwable cause) {
 4:           super(cause);
 5:       }
 6:   }
You can also use the Throwable.initCause method for this if you don’t have the constructor like the one above.
3. Don’t use the 2nd point too much if the lower level method can get away with the exception, then you should do that. Don’t overload the calling methods too much to handle the exceptions thrown by the lower methods.
4. If you are declaring your own exception class you can always include some methods or attributes which can be used to convey more about the exception when it occurs.
5. Try to reuse exceptions (comes generally when you are creating your own API). The most reusabel exceptions are
IllegalArgumentException, IllegalStateException, NullPointerException, IndexArrayOutOfBounds and some more.
6. Most importantly, use Exceptions only for Exceptional conditions. Don’t write your logic which is based on exceptions. For example, don’t do like this
 1: // wrong usage of exception handling
 2: try {
 3:     someObject.someMethod();
 4: } catch (NullPointerException npe)
 5: {
 6:     // other code
 7: }
7. If rather than Exception you can have state testing method before actually using a state-dependent method like checking iterator.hasNext() before executing the iterator.next() method is more appropriate.
8. All of the unchecked throwables you implement should subclass  RuntimeException (directly or indirectly).
9. Use runtime exceptions to indicate programming errors. The great majority of runtime exceptions indicate precondition violations. A precondition violation is simply a failure by the client of an API to adhere to the contract established by the API specification. For example, the contract for array access specifies that the array index must be between zero and the array length minus one. ArrayIndexOutOfBoundsException indicates that this precondition was violated.
10. Always declare checked exceptions individually, and document precisely the conditions under which each one is thrown using the Javadoc @throws tag. Don’t take the shortcut of declaring that a method throws some superclass of multiple exception classes that it can throw. As an extreme example, never declare that a method “throws Exception” or, worse yet, “throws Throwable.”
11.Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration.  It is important that the programmers using your API be aware of which exceptions are checked and which are unchecked, as their responsibilities differ in these two cases. The documentation    generated by the Javadoc @throws tag in the absence of the method header generated by the throws declaration provides a strong visual clue to help the programmer distinguish checked exceptions from unchecked.
12. If an exception is thrown by many methods in a class for the same reason, it is acceptable to document the exception in the class’s documentation comment rather than documenting it individually for each method. A common example is NullPointerException. It is fine for a class’s documentation comment to say, “All methods in this class throw a NullPointerException if a null object reference is passed in any parameter,” or words to that effect.
13. To capture the failure, the detail message of an exception should contain the values of all parameters and fields that “contributed to the exception. You must write the toString() method of your exception carefully.
14. Failure Atomicity(Object remains in consistence state after a failure)-
ways to achieve failure atomicity:
a. A closely related approach to achieving failure atomicity is to order the computation so that any part that may fail takes place before any part that modifies the object.
b. This approach is a natural extension of the previous one when arguments cannot be checked without performing a part of the computation.
c. A third and far less common approach to achieving failure atomicity is to write recovery code that intercepts a failure that occurs in the midst of an operation and causes the object to roll back its state to the point before the operation began. This approach is used mainly for durable (disk-based) data structures.
d.A final approach to achieving failure atomicity is to perform the operation on a temporary copy of the object and to replace the contents of the object with the temporary copy once the operation is complete. This approach occurs naturally when the computation can be performed more quickly  once the data has been stored in a temporary data structure. For example, Collections.sort dumps its
input list into an array prior to sorting to reduce the cost of accessing elements in the inner loop of the sort. This is done for performance, but as an added benefit, it ensures that the input list will be untouched if the sort fails.
As a rule, any generated exception that is part of a method’s specification should leave the object in the same state it was in prior to the method invocation. Where this rule is violated, the API documentation should clearly indicate what state the object will be left in.
15. An empty catch block defeats the purpose of exceptions, which is to force you to handle exceptional conditions. At the very
least, the catch block should contain a comment explaining why it is appropriate to ignore the exception.