Yes, this would work. But it would be tedious.
The reversed String
could be built up character by character in an array.
Since arrays can be altered,
only one new object would
be constructed.
This is essentially the idea of the StringBuffer
class.
A StringBuffer
object holds a sequence of characters,
like a String
.
But it is not immutable.
The characters in a StringBuffer
object can be changed.
Characters can be inserted, deleted, and replaced.
Also, a StringBuffer
object includes
many useful character manipulation methods.
If you insert characters into a StringBuffer
,
it automatically grows to the length you need.
This relieves much of the tedium that directly using an array would involve.
Constructors for StringBuffer
are:
StringBuffer constructors | |
---|---|
public StringBuffer() | create an empty StringBuffer |
public StringBuffer(int capacity) | create a StringBuffer with initial room for capacity number of characters |
public StringBuffer(String str) | create a StringBuffer containing the characters from str |
Why would you ever want a StringBuffer
with length zero?