Java Reference
In-Depth Information
state that you need to be able to “discuss differences between the
String
,
StringBuilder
,
and
StringBuffer
classes.” The main differences between these classes are as follows:
String
String
represents an immutable sequence of characters. The string literals in your
code are of type
String
.
StringBuilder
StringBuilder
represents a mutable sequence of characters.
String-
Builder
is like
String
except the individual characters can be modified and the length can
change. The methods in this class are not synchronized, so do not use an instance of this
class in a situation where multiple threads can access the instance.
StringBuffer
StringBuffer
represents a thread-safe, mutable sequence of characters. The
methods in this class are exactly identical to the methods of
StringBuilder
. The only dif-
ference between the two classes is that the methods in
StringBuffer
are synchronized.
The simplest class to use is
String
, but it tends to be ineffi cient when working with
character sequences that need to be changed often because a
String
object is immutable.
Use
StringBuilder
and
StringBuffer
in situations where you need to manipulate strings,
because they contain methods like
append
,
insert
, and
concat
that change the string with-
out creating a new object each time.
This section discusses each of these classes in detail, starting with the
String
class.
The
String
Class
The
String
class represents an immutable array of characters. String literals are automati-
cally instantiated into
String
objects. For example,
”Hello”
in the following statement is a
String
object:
String s = “Hello”;
You can also instantiate a
String
dynamically using one of the
String
constructors:
char [] abc = {'a', 'b', 'c'};
String s2 = new String(abc);
The JVM stores string literals in a special memory called the string pool. Because
String
objects are immutable, instances in the string pool can be shared. For example, the
following two
String
references point to the same instance, and the output is
”true“
:
String one = “today”;
String two = “today”;
if(one == two)
System.out.println(“true”);
else
System.out.println(“false”);
Search WWH ::
Custom Search