jitan
jitan

Reputation: 21

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 i pass a String instead of character, it appends to Hello . Why is this strange behavior with char ?

Upvotes: 2

Views: 372

Answers (2)

Bacteria
Bacteria

Reputation: 8616

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.

Upvotes: 0

Marvin
Marvin

Reputation: 14415

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.

Upvotes: 6

Related Questions