Java Reference
In-Depth Information
How does the computer know that one letter “comes before” another? All characters
are represented in the computer as numeric codes (see Appendix B). When the computer
compares
String
s, it actually compares the numeric codes of the characters in the
String
s.
Figure 14.3 demonstrates
String
methods
equals
,
equalsIgnoreCase
,
compareTo
and
regionMatches
and using the equality operator
==
to compare
String
objects.
1
// Fig. 14.3: StringCompare.java
2
// String methods equals, equalsIgnoreCase, compareTo and regionMatches.
3
4
public
class
StringCompare
5
{
6
public
static
void
main(String[] args)
7
{
8
String s1 =
new
String(
"hello"
);
// s1 is a copy of "hello"
9
String s2 =
"goodbye"
;
10
String s3 =
"Happy Birthday"
;
11
String s4 =
"happy birthday"
;
12
13
System.out.printf(
14
"s1 = %s%ns2 = %s%ns3 = %s%ns4 = %s%n%n"
, s1, s2, s3, s4);
15
16
// test for equality
17
if
(
s1.equals(
"hello"
)
)
// true
18
System.out.println(
"s1 equals \"hello\""
);
19
else
20
System.out.println(
"s1 does not equal \"hello\""
);
21
22
// test for equality with ==
23
if
(
s1 ==
"hello"
)
// false; they are not the same object
24
System.out.println(
"s1 is the same object as \"hello\"")
;
25
else
26
System.out.println(
"s1 is not the same object as \"hello\""
);
27
28
// test for equality (ignore case)
29
if
(
s3.equalsIgnoreCase(s4)
)
// true
30
System.out.printf(
"%s equals %s with case ignored%n"
, s3, s4);
31
else
32
System.out.println(
"s3 does not equal s4"
);
33
34
// test compareTo
35
System.out.printf(
36
"%ns1.compareTo(s2) is %d"
,
s1.compareTo(s2)
);
37
System.out.printf(
38
"%ns2.compareTo(s1) is %d"
,
s2.compareTo(s1)
);
39
System.out.printf(
40
"%ns1.compareTo(s1) is %d"
,
s1.compareTo(s1)
);
41
System.out.printf(
42
"%ns3.compareTo(s4) is %d"
,
s3.compareTo(s4)
);
43
System.out.printf(
44
"%ns4.compareTo(s3) is %d%n%n"
,
s4.compareTo(s3)
);
Fig. 14.3
|
String
methods
equals
,
equalsIgnoreCase
,
compareTo
and
regionMatches
.
(Part 1 of 2.)