The String Class Stud
The String Class Stud
Objectives:
word “java"
“Java"
Empty Strings
An empty String has no characters. It’s
length is 0.
String word1 = ""; Empty strings
String word2 = new String();
result += word3;
//concatenates word3 to result “rethinking”
if(team.equalsIgnoreCase(“raiders”))
System.out.println(“Go You “ + team);
Methods — Comparisons
int diff = word1.compareTo(word2);
returns the “difference” word1 - word2
int diff = word1.compareToIgnoreCase(word2);
returns the “difference” word1 - word2,
case-blind
Usually programmers don’t care what the numerical “difference” of
word1 - word2 is, just whether the difference is negative (word1
comes before word2), zero (word1 and word2 are equal) or positive
(word1 comes after word2). Often used in conditional statements.
//zero differences
diff = “apple”.compareTo(“apple”);//equal
diff = “dig”.compareToIgnoreCase(“DIG”);//equal
//positive differences
diff = “berry”.compareTo(“apple”);//b after a
diff = “apple”.compareTo(“Apple”);//a after A
diff = “BIT”.compareTo(“BIG”);//T after G
diff = “huge”.compareTo(“hug”);//huge is longer
Methods — trim
String word2 = word1.trim ();
returns a new string formed from word1 by
removing white space at both ends
does not affect whites space in the middle
String word1 = “ Hi Bob “;
String word2 = word1.trim();
//word2 is “Hi Bob” – no spaces on either end
//word1 is still “ Hi Bob “ – with spaces
Methods — replace
String word2 = word1.replace(oldCh, newCh);
returns a new string formed from word1 by
replacing all occurrences of oldCh with newCh
A common bug:
word1
word1.toUpperCase();
remains
unchanged
Numbers to Strings
Three ways to convert a number into a string:
1. String s = "" + num; Integer and Double
s = “” + are “wrapper” classes
123;//”123” from java.lang that
2. String s = Integer.toString (i);
represent numbers as
String s = Double.toString (d); objects. They also
s = Integer.toString(123);//”123” provide useful static
s = Double.toString(3.14); methods.
//”3.14”
3. String s = String.valueOf (num);
s=
String.valueOf(123);//”123”