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.