Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder constructor accepts a StringBuilder object - why?

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?

like image 854
Igor Soudakevitch Avatar asked Aug 14 '16 15:08

Igor Soudakevitch


People also ask

What is the difference between constructor and StringBuilder in Java?

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.

How to use StringBuilder class in net?

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.

How to call StringBuilder constructor with initial string and specified capacity?

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)

How do I create a new StringBuilder in Java?

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.


2 Answers

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");
like image 141
Tunaki Avatar answered Oct 13 '22 06:10

Tunaki


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

like image 25
Aaron Davis Avatar answered Oct 13 '22 05:10

Aaron Davis