Reputation: 671
The class StringBuilder
defines four constructors, and none of them accepts a StringBuilder
, yet the following compiles:
StringBuilder sb = new StringBuilder(new StringBuilder("Hello"));
Does this mean that the anonymous StringBuilder
object gets somehow converted to a String internally by the compiler?
Upvotes: 10
Views: 927
Reputation: 137084
A StringBuilder
is a CharSequence
(it implements that interface), and there is a constructor taking a CharSequence
. This is why the given code compiles:
StringBuilder sb = new StringBuilder(new StringBuilder("Hello"));
What this constructor does is simply initialize the new StringBuilder
with the content of the given CharSequence
. The result will be the same as having
StringBuilder sb = new StringBuilder("Hello");
Upvotes: 10
Reputation: 1731
There is a constructor that takes in a CharSequence
which is an interface that is implemented by StringBuilder and by String (among other classes).
http://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html
Upvotes: 5