Java Reference
In-Depth Information
Table 3.2
Useful
String
methods
Return type
Method
Description
length()
Returns the length, i.e. number of characters,
in the
String
.
int
equals(Object obj)
Returns
true
if the object is a
String
object and is equal to the
String
. (Aside:
the argument takes a generic
Object
type
rather than only a
String
object because it's
meant to override the
equals()
method in
the class
Object
of which
String
is a
descendant.) This is the way to compare two
String
s to see if they are both holding the
same sequence of characters. Using
stringA
== stringB
will only tell you if
stringA
and
stringB
are referencing the same object
(pointing to the same location in memory).
What you typically want is
stringA.equals(stringB)
.
boolean
equalsIgnoreCase(String str)
Similar to
equals()
, but this one only
allows a
String
parameter, and it ignores
the upper/lower case distinction between
letters. For example:
boolean
String sample = "abcdefg";
String sample2 = "AbCdEfG";
sample.equalsIgnoreCase(sample2)
returns
true
.
toLowerCase()
Returns a string with all characters converted
to lowercase.
String
toUpperCase()
Returns a string with all characters converted
to uppercase.
String
startsWith(String substr)
Returns
true
if the
String
starts with the
given substring.
boolean
endsWith(String substr)
Returns
true
if the
String
ends with the
given substring.
boolean
substring(int index)
Returns a string starting at position
index
to the end of the
String
.
String