Igor Soudakevitch
Igor Soudakevitch

Reputation: 671

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?

Upvotes: 10

Views: 927

Answers (2)

Tunaki
Tunaki

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

Aaron Davis
Aaron Davis

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

Related Questions