Strings
We’ll start by taking a closer look at the Java String class (or, more specifically, java.lang.String). Because working with Strings is so fundamental, it’s important to
understand how they are implemented and what you can do with them. A
String object encapsulates a sequence
of Unicode characters. Internally, these characters are stored in a
regular Java array, but the String
object guards this array jealously and gives you access to it only through
its own API. This is to support the idea that Strings are immutable; once you create a String object, you can’t change its value. Lots
of operations on a String object appear
to change the characters or length of a string, but what they really do is
return a new String object that copies
or internally references the needed characters of the original. Java
implementations make an effort to consolidate identical strings used in
the same class into a shared-string pool and to share parts of Strings where possible.
The original motivation for all of this was performance. Immutable
Strings can save memory and be
optimized for speed by the Java VM. The flip side is that a programmer
should have a basic understanding of the String class in order to avoid creating an
excessive number of String objects in
places where performance is an issue. That was especially true in the
past, when VMs were slow and handled memory poorly. Nowadays, string usage
is not usually an issue in the overall performance of a real
application.[29]
Constructing ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access