Java Reference
In-Depth Information
strings
2.3
Strings in Java are handled with the String reference type. The language does
make it appear that the String type is a primitive type because it provides the +
and += operators for concatenation. However, this is the only reference type
for which any operator overloading is allowed. Otherwise, the String behaves
like any other reference type.
The String behaves
like a reference
type.
2.3.1 basics of string manipulation
There are two fundamental rules about a String object. First, with the excep-
tion of the concatenation operators, it behaves like an object. Second, the
String is immutable . This means that once a String object is constructed, its
contents may not be changed.
Because a String is immutable, it is always safe to use the = operator with
it. Thus a String may be declared as follows:
Strings are
immutable ; that is, a
String object will
not be changed.
String empty = "";
String message = "Hello";
String repeat = message;
After these declarations, there are two String objects. The first is the empty
string, which is referenced by empty . The second is the String "Hello" which is
referenced by both message and repeat . For most objects, being referenced by
both message and repeat could be a problem. However, because String s are
immutable, the sharing of String objects is safe, as well as efficient. The only
way to change the value that the string repeat refers to is to construct a new
String and have repeat reference it. This has no effect on the String that mes-
sage references.
2.3.2 string concatenation
Java does not allow operator overloading for reference types. However, a spe-
cial language exemption is granted for string concatenation.
The operator + , when at least one operand is a String , performs concatenation.
The result is a reference to a newly constructed String object. For example,
String concatena-
tion is performed
with + (and += ).
"this" + " that"
// Generates "this that"
"abc" + 5
// Generates "abc5"
5 + "abc"
// Generates "5abc"
"a" + "b" + "c"
// Generates "abc"
 
 
Search WWH ::




Custom Search