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?
Constructors in Java StringBuilder: StringBuilder (): Constructs a string builder with no characters in it and an initial capacity of 16 characters. StringBuilder (int capacity): Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
Using the StringBuilder Class in .NET. The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object.
The following example demonstrates how to call the StringBuilder constructor with an initial string and a specified capacity. Dim initialString As String = "Initial string. " Dim capacity As Integer = 255 Dim stringBuilder As New StringBuilder (initialString, capacity)
To avoid having to provide a fully qualified type name in your code, you can import the System.Text namespace: You can create a new instance of the StringBuilder class by initializing your variable with one of the overloaded constructor methods, as illustrated in the following example.
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");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With