Java Reference
In-Depth Information
Use
equals
to Compare Strings
You should use the
equals
method when comparing if two
String
objects are identi-
cal because not all
String
objects appear in the string pool. For example, see if you can
determine the output of the following code:
String one = “today”;
String three = new String(“today”);
if(one == three)
System.out.println(”true”);
else
System.out.println(“false”);
The
one
reference points to a
String
object in the string pool while the
three
reference
points to a dynamically created
String
object on the heap, so
one
and
three
do not point
to the same instance and the output of the previous code is
”false”
.
One nice feature of using
String
objects is the simple way they are concatenated using
the + operator. For example, the following statements create a
”Tooth Fairy”
string:
String first = “Tooth”;
first += “ “ + “Fai” + “ry”;
It is valid to concatenate a
String
to any primitive type or
Object
. Primitive types are
converted to a
String
object internally by the JVM. Object types have their
toString
method invoked automatically. For example, the following statements are valid. See if you
can determine their output:
String prefix = “x = “;
int x = 123;
System.out.println(prefix + x);
java.util.Date d = new java.util.Date();
System.out.println(“The date is “ + d);
The
int x
is converted to a
String
before the concatenation occurs. Similarly, the
toString
method is invoked on
d
before concatenating to the
String
object
“The date is“
.
The output of the code is
x = 123
The date is Mon Oct 06 08:26:47 MDT 2008
You should be aware that
String
objects tend to be ineffi cient when they are concate-
nated. Remember, a
String
object is immutable, meaning it cannot be changed. Therefore,
Search WWH ::
Custom Search