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

前端 未结 2 1609
心在旅途
心在旅途 2020-12-21 12:12
    StringBuffer sb = new StringBuffer(\'A\');
    System.out.println(\"sb = \" + sb.toString());
    sb.append(\"Hello\");
    System.out.println(\"sb = \" + sb.toS         


        
相关标签:
2条回答
  • 2020-12-21 12:43

    There is no constructor which accepts a char. You end up with the int constructor due to Java automatically converting your char to an int, thus specifying the initial capacity.

    /**
     * Constructs a string buffer with no characters in it and
     * the specified initial capacity.
     *
     * @param      capacity  the initial capacity.
     * @exception  NegativeArraySizeException  if the <code>capacity</code>
     *               argument is less than <code>0</code>.
     */
    public StringBuffer(int capacity) {
        super(capacity);
    }
    

    Cf. this 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 an initial capacity of 17.

    You might have confused char with CharSequence (for which there is indeed a constructor), but these are two completely different things.

    0 讨论(0)
  • 2020-12-21 12:49

    U have used below mentioned constructor.

    public StringBuffer(int capacity)

    Constructs a string buffer with no characters in it and the specified initial capacity.

    Parameters: capacity - the initial capacity.

    see the java doc u don't have any constructor which takes char input param.

    0 讨论(0)
提交回复
热议问题