0

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?

enTropy
  • 621
  • 4
  • 14

3 Answers3

6

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

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
3

StringBuilder and StringBuffer both implement CharSequence.

David Grant
  • 13,929
  • 3
  • 57
  • 63
0

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

PermGenError
  • 45,977
  • 8
  • 87
  • 106