Java Reference
In-Depth Information
String doubleString = String.valueOf(3.14159);
You call the
valueOf()
method using the name of the class,
String
, as shown above. This is because
the method is a
static
member of the
String
class. You will learn what this means in Chapter 5. A
literal or variable of any of the basic types can be passed to the
valueOf()
method, and it will return a
String
representation of the value.
Comparing Strings
Here is where the difference between the
String
variable and the string it references will become
apparent. To compare variables of the basic types for equality you use the
==
operator. This does
not
apply to
String
objects (or any other objects). The expression:
string1 == string2
will check whether the two
String
variables refer to the same string. If they reference separate strings,
this expression will have the value
false
, regardless of whether or not the strings happen to be
identical. In other words, the expression above does not compare the strings themselves, it compares
the references to the strings, so the result will be true only if
string1
and
string2
both refer to one
and the same string. We can demonstrate this with a little example.
Try It Out - Two Strings, Identical but not the Same
In the following code, we test to see whether
string1
and
string3
refer to the same string.
public class MatchStrings {
public static void main(String[] args) {
String string1 = "Too many ";
String string2 = "cooks";
String string3 = "Too many cooks";
// Make string1 and string3 refer to separate strings that are identical
string1 += string2;
// Display the contents of the strings
System.out.println("Test 1");
System.out.println("string3 is now: " + string3);
System.out.println("string1 is now: " + string1);
if(string1 == string3) // Now test for identity
System.out.println("string1 == string3 is true." +
" string1 and string3 point to the same string");
else
System.out.println("string1 == string3 is false." +
" string1 and string3 do not point to the same string");
// Now make string1 and string3 refer to the same string
string3 = string1;