java - How StringBuffer behaves When Passing Char as argument to its Overloaded Constructor? -


    stringbuffer sb = new stringbuffer('a');     system.out.println("sb = " + sb.tostring());     sb.append("hello");     system.out.println("sb = " + sb.tostring()); 

output:

sb =

sb = hello

but if pass string instead of character, appends hello . why strange behavior char ?

there no constructor accepts char. end int constructor due java automatically converting char int, specifying initial capacity.

/**  * constructs string buffer no characters in ,  * specified initial capacity.  *  * @param      capacity  initial capacity.  * @exception  negativearraysizeexception  if <code>capacity</code>  *               argument less <code>0</code>.  */ public stringbuffer(int capacity) {     super(capacity); } 

cf. minimal example:

public class stringbuffertest {     public static void main(string[] args) {         stringbuffer buf = new stringbuffer('a');         system.out.println(buf.capacity());         system.out.println((int) 'a');         stringbuffer buf2 = new stringbuffer('b');         system.out.println(buf2.capacity());         system.out.println((int) 'b');     } } 

output:

97 97 98 98 

whereas

stringbuffer buf3 = new stringbuffer("a"); system.out.println(buf3.capacity()); 

results in initial capacity of 17.

you might have confused char charsequence (for there indeed constructor), these 2 different things.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -