-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 ) {
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:
Post a Comment