COMP 1020 - A02
More on Strings
and ArrayLists
WINTER 2019
1

2
More String methods
•
We’ve seen:
•
length(), charAt(), equals(), equalsIgnoreCase()
•
Some other useful instance methods:
•
String toLowerCase( ) - letters become lower case
String s = "Hello, Person."
s.toLowerCase( )
would give
"hello, person."
•
String toUpperCase( )
–
letters become upper case
s.toUpperCase( )
would give
"HELLO, PERSON
.“
•
String trim()
–
removes
leading/trailing
whitespace (including tabs and newlines)

3
More String methods
•
Remember: these methods
don’t
change the original
•
That's impossible. String objects are "
immutable
".
•
They create a
new String
and return a reference to it
System.out.println(s.toLowerCase( ));
//s not changed
s = s.toLowerCase( );
//changes s

4
Example
•
Check to see if a String is a palindrome
•
Reads the same forward and backward
•
We want to do this while ignoring non-letters,
leading/trailing space, and case
•
Palindromes:
•
"detartrated"
•
"redivider"
•
"If I had a Hi-Fi"
•
"
Was it a car or a cat I saw? "
•
"Able was I ere I saw Elba."
See Palindrome.java

5
Another String method
•
String1.compareTo(String2)
•
Gives
•
Some negative value if String1 is “less” than
String2
•
A zero if they are the same
•
Some positive value if String1 is “greater” than
String2
