Return or Print StringBuilder? Java -
i bit confused stringbuilder. seems when print stringbuilder, there no need add .tostring() because automatically give me string representation. however, when return stringbuilder object, have add .tostring(). true? , why?
also, bit confused following code:
package com.tutorialspoint; import java.lang.*; public class stringbuilderdemo { public static void main(string[] args) { stringbuilder str = new stringbuilder("india "); system.out.println("string = " + str); // append character stringbuilder str.append('!'); // convert string object , print system.out.println("after append = " + str.tostring()); str = new stringbuilder("hi "); system.out.println("string = " + str); // append integer stringbuilder str.append(123); // convert string object , print system.out.println("after append = " + str.tostring()); } }
for different println, code use tostring , other times didn't. why? tried deleting tostring , results same. still necessary use tostring in println?
thanks helping newbie out!
when print object print stream, string
representation of object printed, hence tostring
invoked.
some classes override object#tostring
, amongst stringbuilder
does.
hence explicitly invoking tostring
stringbuilder
unnecessary.
on other hand, other objects don't override tostring
. instance, arrays.
when print array, unless using utility such arrays.tostring
, you're getting array's class type @
hash code, opposed human-readable representation of contents.
Comments
Post a Comment