Operators and Assignments - String Operators
- the + and += operators both work on Strings
- operators actually signfy concatenation
- the result of the operation is a new string
- Strings are objects, not primitive types, and are read-only and immutable; the contents never change
- String variables store references to a string object NOT the string itself
String str = "Hello";
String str1 = "Universe!";
String str2 = str + str1; // join the two strings together
String str3 = "";
str3 += str; // += only works with an initialized var
String str4 = str2;
- in the above code a reference to the string "Hello" is stored in the variable str
- a reference to the string "Universe!" is stored in the variable str1
- a reference to a new string "Hello Universe!" is stored in the variable str2
- the reference for a new string "Hello" is stored in variable str3
str3 == str // false (ref to different String objects)
- the reference for str2 is stored in variable str4
str4 == str2 // true (references are the same)
Where it can get confusing
- the String class creates a pool of Strings
- when you create a String by using the new operator or by using the + and += operators (the string is computed at runtime) you are implicitly telling the compiler to create a new String object
- when you create a String by assigning a string literal the compiler searches the existing string pool for an exact match. If it finds one, a new string is NOT created. Instead the variable is assigned a reference to the existing pooled string.
String str5 = "Hello Universe!"; // created in the string pool
String str6 = "Hello Universe!";
str5 == str2 // false (str2 is not part of the pool, created
// using '+' operator)
str5 == str6 // true (matched an existing string found
// in the pool)
- to actually compare the contents of String objects use the String method equals()
str5.equals(str2); // true (both objects hold the same string
// characters)
Strings and primitive types
- by the rules of String Conversion (see Conversion) any type can be converted to a string
- this includes the primitive types
- for primitive types, conversion occurs by the compiler calling Type.toString(x) behind the scenes.
int x = 10;
System.out.println("Result: " + x);
is the same as
System.out.println("Result: " + (Integer.toString(x)) );
Also see:
Example Code
Tips
- String operations whose result does not alter the original string (ie calling toUpperCase() on a String that is already in uppercase) return the original string reference; otherwise they return a reference to a new String
- Strings are immutable; the original String value can never be changed
Traps
- using == to compare the contents of two different String objects
|