Java Reference
In-Depth Information
BASIC TYPE WRAPPER CLASS
boolean
Boolean
char
Character
The classes in the table are called wrapper classes because objects of each of these class types
wrap
a
value of the corresponding primitive type. Whenever a value of one of the basic types appears as an op-
erand to
+
and the other operand is a
String
object, the compiler arranges to pass the value of the basic
type as the argument to the
toString()
method that is defined in the corresponding wrapper class. The
toString()
method returns the
String
equivalent of the value. All of this happens automatically when
you are concatenating strings using the
+
operator. As you see later, these are not the only classes that
have a
toString()
method — all classes do. I won't go into the significance of these classes now, as I
cover these in more detail in Chapter 5.
The
String
class also defines a method,
valueOf()
, that creates a
String
object from a value of any
type. You just pass the value you want converted to a string as the argument to the method. For example
String doubleString = String.valueOf(3.14159);
You call the
valueOf()
method using the name of the class
String
, as shown in the preceding line. This
is because the method is a
static
member of the
String
class. You learn what
static
means in this
context in Chapter 5.
Comparing Strings
Here's where the difference between the
String
variable and the string it references becomes apparent. To
compare values stored in variables of the primitive types for equality, you use the
==
operator. This does
not
apply to
String
objects (or any other objects). The expression
string1 == string2
checks whether the two
String
variables refer to the same string. If they reference separate strings, this ex-
pression has the value
false
, regardless of whether or not the strings happen to be identical. In other words,
the preceding expression does not compare the strings themselves; it compares the references to the strings,
so the result is
true
only if
string1
and
string2
both refer to one and the same string. You can demon-
strate this with a little example.
TRY IT OUT: Two Strings, Identical but Not the Same
In the following code, you test to see whether
string1
and
string3
refer to the same string:
public class MatchStrings {
public static void main(String[] args) {