enTropy
enTropy

Reputation: 621

Why new StringBuffer(new StringBuilder("foo")) does work?

I'm studying for the SCJP certificate and while playing with the StringBuilder and StringBuffer API's I found some situations I can't understand what is happening there.

Here is my example code:

    StringBuffer sb1 = new StringBuffer("sb1");
    StringBuilder sb2 = new StringBuilder("sb2");

    StringBuffer sb11 = new StringBuffer(sb1);
    StringBuilder sb22 = new StringBuilder(sb2);

    StringBuffer sb12 = new StringBuffer(sb2);
    StringBuilder sb21 = new StringBuilder(sb1);

    System.out.println(sb1);
    System.out.println(sb2);
    System.out.println(sb11);
    System.out.println(sb22);
    System.out.println(sb12);
    System.out.println(sb21);

    System.out.println();
    sb1.append("a1");
    sb2.append("a2");

    System.out.println(sb1);
    System.out.println(sb2);
    System.out.println(sb11);
    System.out.println(sb22);
    System.out.println(sb12);
    System.out.println(sb21);

And here is the result of running the code above:

sb1
sb2
sb1
sb2
sb2
sb1

sb1a1
sb2a2
sb1
sb2
sb2
sb1

The constructors used for sb11, sb22, sb12 and sb21 are not documented in the API. Furthermore, looking at the results it seems like for those 4 cases the constructor that admits a String or CharSequence is the one used.

If it is true, why is Java automatically converting a StringBuffer in a String? As far as I know Autoboxing does not go that far.

What am I missing?

Upvotes: 0

Views: 261

Answers (3)

PermGenError
PermGenError

Reputation: 46428

both of them implement CharSequence. the only difference between them is StringBuffer methods are synchronized whereas stringBuilder is not

Upvotes: 0

Ian Roberts
Ian Roberts

Reputation: 122414

Both StringBuilder and StringBuffer implement the CharSequence interface, and both have a constructor that takes a CharSequence parameter.

Upvotes: 6

David Grant
David Grant

Reputation: 14243

StringBuilder and StringBuffer both implement CharSequence.

Upvotes: 3

Related Questions