Thursday, February 5, 2009

-C-O-N-C-E-P-T- Series : Java

Difference between using "" and toString() method for converting object value to String:

Case I - Using "":

-----------------------------------------------------------------
BigDecimal dec = new BigDecimal("1234567");
String str = "" + dec; // converting dec to String
System.out.println("str: "+str);

o/p:
str: 1234567
-----------------------------------------------------------------

-----------------------------------------------------------------
BigDecimal dec = null;
String str = "" + dec; // converting dec to String
System.out.println("str: "+str);

o/p:
str: null
-----------------------------------------------------------------


Case II - Using toString() method:

-----------------------------------------------------------------
BigDecimal dec = new BigDecimal("1234567");
String str = null;

if( dec!=null ) {
str = dec.toString(); // converting dec to String
}

System.out.println("str: "+str);

o/p:
str: 1234567
-----------------------------------------------------------------

-----------------------------------------------------------------
BigDecimal dec = null;
String str = null;

if( dec!=null ) {

str = dec.toString(); // converting dec to String
}

System.out.println("str: "+str);

o/p:
str: null
-----------------------------------------------------------------

In first case, we don't require null check, but doesn't has readability.
In second case, we require null check, but has readability.

Each one has its own ease of use.

No comments:


_________________________________________________________________________________________________________________

"Look at the sky. We are not alone. The whole Universe is friendly to us and conspires only to give the best to those who dream and work."

- Dr. A P J Abdul Kalam
_________________________________________________________________________________________________________________