the string class (1)
TRANSCRIPT
-
8/8/2019 The String Class (1)
1/46
The String Class
-
8/8/2019 The String Class (1)
2/46
Objectives:
Learn about literal strings
Learn about String constructors Learn about commonly used
methods
Understand immutability ofstrings Learn toformat numbers into
strings
-
8/8/2019 The String Class (1)
3/46
String class facts
In java a string is a sequence of
characters.But unlike many other
languages that implement strings as
character arrays, java implements
strings as objects of type String.
When you create a String object,youare creating a string that cannot be
changed.
-
8/8/2019 The String Class (1)
4/46
String class facts An object ofthe String class represents a
string ofcharacters.
The String class belongs to the java.langpackage, which does not require an importstatement.
Like other classes, String has constructorsand methods.
Unlike other classes, String has twooperators, + and += (used forconcatenation).
-
8/8/2019 The String Class (1)
5/46
Literal Strings are anonymous objects ofthe String class
are defined by enclosing text in double
quotes. This is a literal String
dont have tobe constructed.
can be assigned to String variables.
can be passed tomethods and constructorsas parameters.
have methods you can call.
-
8/8/2019 The String Class (1)
6/46
Literal String examples//assign a literal to a String variable
String name = Robert;
//calling a method on a literal String
char firstInitial = Robert.charAt(0);
//calling a method on a String variable
char firstInitial = name.charAt(0);
-
8/8/2019 The String Class (1)
7/46
Immutability Once created, a string cannot be changed:
none of its methods changes the string.
Such objects are called immutable. To say that the strings within objects oftype
String are unchangeable means that thecontents ofthe String instance cannot be
changed after it has been created. However, a variable declared as a String
reference can be changed topoint at someother String object any time.
-
8/8/2019 The String Class (1)
8/46
Empty Strings
An empty String has no characters. Its
length is 0.
Not the same as an uninitialized String.
String word1 = "";String word2 = new String();
private String errorMsg; errorMsg
is null
Empty strings
-
8/8/2019 The String Class (1)
9/46
No Argument Constructors
No-argument constructor creates an
empty String. Rarely used.
A more common approach is to
reassign the variable to an empty
literal String. (Often done to reinitialize a variableused to store input.)
String empty = ;//nothing between quotes
String empty = new String();
-
8/8/2019 The String Class (1)
10/46
Constructors String(char chars[])
char chars[]={a,b,c};
String s=new String(chars);This constructor initializes s with the stringabc
String(char chars[], int startIndex,int
numchars)
char chars[]={a,b,c,d,e};
String s=new String(chars,2,3);
This initializes s with the characters cde.
-
8/8/2019 The String Class (1)
11/46
Constructors
] String(String strobj)strobj is a String object
class Makestring{
public static void main(String args[])
{
char c[]={j,a,v,a};
String s1=new String(c);
String s2=new String(s2);
System.out.println(s1);
System.out.println(s2);
}
}
-
8/8/2019 The String Class (1)
12/46
Constructors String(byte asciichars[])
String(byte asciichars[],int
startIndex,int numchars)Class Substring{public static void main(String args[])
{ byte ascii[]={65,66,67,68,69,70};
String s1=new String (ascii);System.out.println(s1);
String s2= new String(ascii,2,3);
System.out.println(s2);
}}
-
8/8/2019 The String Class (1)
13/46
The contents of the array are copies
whenever you create a String object
from an array.
Ifyoumodify the contents of the array
after you have created the string, the
String will be unchanged.
-
8/8/2019 The String Class (1)
14/46
Copy Constructors Copy constructor creates a copy ofan existing
String. Also rarely used.
Not the same as an assignment.
String word = new String(Java);
String word2 = new String(word);
word
word2
Java"
Java"
Copy Constructor: Each variable points to a different copy of the String.
String word = Java;
String word2 = word;
wordJava"
word2
Assignment: Both variables point to the same String.
-
8/8/2019 The String Class (1)
15/46
Other Constructors
Most other constructors take an array as
a parameter to create a String.
char[] letters = {J, a, v, a};
String word = new String(letters);//Java
-
8/8/2019 The String Class (1)
16/46
Methods length, charAtint length();
char charAt(i);
Returns the numberofcharacters in
the string
Returns the char at position i.
7
n'
Problem".length();
Window".charAt (2);
Returns:
Characterpositions in strings are numbered
starting from 0 just like arrays.
-
8/8/2019 The String Class (1)
17/46
char chars[]={J,a,v,a};
String s = new String(chars);
System.out.println(s.length));
String literal
char chars[]={J,a,v,a};
String s = new String(chars);
String s2=abc;
System.out.println(abc.length());
-
8/8/2019 The String Class (1)
18/46
CharacterE
xtraction charcharAt(int where)
Where is the index of the character that u want.
The value ofwhere must be nonnegative andspecify a location within the string
charAt() returns the character at the specified
location
char ch;ch=abc.charAt(1);
-
8/8/2019 The String Class (1)
19/46
CharacterE
xtraction void getChars( int sourcestart,int sourceend,char
target[], int targetstart)
Sourcestart specifies the index of the beginning ofthe substring
Sourceend specifies an index that is one past the
end ofthe desired substring.
The array that will receive the characters is
specified by target
The index within target at which the ststring will be
copied is passed in targetstart
-
8/8/2019 The String Class (1)
20/46
Class getchardemo{ public static void main(String args[])
{
String s=demoofthe getcharmethod;
int start=10;
int end=14;
Charbuf[]=new char[end-start];
s.getChars(start, end,buf,0);
System.out.println(buf);
}
}
-
8/8/2019 The String Class (1)
21/46
Changing the case
String toLowerCase()
String toUpperCase()
String upper= s.toUpperCase();
String l=s.toUpperCase();
-
8/8/2019 The String Class (1)
22/46
Modifying a String
String substring(int startindex)
String substring(int startindex, int
endindex)
-
8/8/2019 The String Class (1)
23/46
Methods substring
lev"
mutable"
"" (empty string)
television".substring (2,5);
immutable".substring (2);
bob".substring (9);
Returns:
television
i k
television
i
String subs = word.substring (i, k);
returns the substring ofchars in
positions fromi tok-1
String subs = word.substring (i);
returns the substring from the i-th
char to the end
Returns a new String by copying characters from an existing String.
-
8/8/2019 The String Class (1)
24/46
Concatenation
String concat(String str)
String s1=one;
String s2= s1.concat(andtwo);
It can alsobe written as
String s1=one;String s2=s1+ two;
-
8/8/2019 The String Class (1)
25/46
Methods Concatenation
String word1 = re, word2 = think; word3 = ing;
int num = 2;
String result = word1 + word2;//concatenates word1 and word2 rethink
String result = word1.concat(word2);//the same as word1 + word2 rethink
result += word3;//concatenates word3 to result rethinking
-
8/8/2019 The String Class (1)
26/46
Replace
To replace all occurrences ofone
character in the invoking string with
another character.
String replace(charoriginal, char
replacement);
String s= Hello.replace(l,w);
-
8/8/2019 The String Class (1)
27/46
Trim
Trimmethod returns a copy of the
invoking string from which any leading
and trailing white space has beenremoved.
String trim()
String s= Hello world .trim();
-
8/8/2019 The String Class (1)
28/46
Searching Strings
String class provides twomethods that
allow you to search a string for a
specified characteror substring.
indexOf() ---searches forfirst
occurrence ofa characteror substring
lastIndexof()---- searches for lastoccurrence ofa characteror substring
-
8/8/2019 The String Class (1)
29/46
Methods Find (indexOf)
String name =President George Washington";
name.indexOf (P'); 0name.indexOf (e'); 2
name.indexOf (George"); 10
name.indexOf (e', 3); 6
name.indexOf (rock"); -1
name.lastIndexOf (e'); 15
Returns:
(not found)
(starts searching
at position 3)
0 2 6 10 15
-
8/8/2019 The String Class (1)
30/46
String comparison
Equals and EqualsIgnoreCase
String s1=Hello;
String s1=Hello;
String s3=HELLO;
s1.equals(s2);s1.equalsIgnoreCase(s3);
-
8/8/2019 The String Class (1)
31/46
Methods Equality
boolean b = word1.equals(word2);
returns true if the string word1 is equal toword2
boolean b = word1.equa
lsIgnoreCa
se(word2);returns true if the string word1matches word2,
case-blind
b = Raiders.equals(Raiders);//true
b = Raiders.equals(raiders);//false
b = Raiders.equalsIgnoreCase(raiders);//true
if(team.equalsIgnoreCase(raiders))
System.out.println(Go You + team);
-
8/8/2019 The String Class (1)
32/46
Function comparTo
To know which is less than, or greater
than the next.
A string is less than another if it comes
before the other in dictionary order
A string is greater than another if it
comes after the other in dictionaryorder.
-
8/8/2019 The String Class (1)
33/46
int compareTo(String str)
Value= Zeromeans the two strings are
same
Less than zero then the invoking string
is less than str
Greater than zeromeans the invoking
string is greater than str
-
8/8/2019 The String Class (1)
34/46
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 dont 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) orpositive(word1 comes after word2). Often used in conditional statements.
if(word1.compareTo(word2) > 0){
//word1 comes after word2
}
-
8/8/2019 The String Class (1)
35/46
Equals versus ==
equals() method compares the
characters inside a String object.
The == operator compares twoobject
references to see whether they refer to
the same instance.
-
8/8/2019 The String Class (1)
36/46
class Equals{
public static void main(String args[]){
String s1=Hello;
String s2= new String(s1);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s2));System.out.println(s1==s2);}}
Output
True
False
-
8/8/2019 The String Class (1)
37/46
Comparison Examples
//negative differences
diff = apple.compareTo(berry);//a before b
diff = Zebra.compareTo(apple);//Z before a
diff = dig.compareTo(dug);//i before u
diff = dig.compareTo(digs);//dig is shorter
//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
-
8/8/2019 The String Class (1)
38/46
Methods trim
String word2 = word1.trim ();
returns a new string formed fromword1 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
-
8/8/2019 The String Class (1)
39/46
Methods replace
String word2 = word1.replace(oldCh, newCh);
returns a new string formed fromword1 by
replacing all occurrences ofoldCh with newCh
String word1 = rare;
String word2 = rare.replace(r, d);
//word2 is dade, but word1 is still rare
-
8/8/2019 The String Class (1)
40/46
Methods Changing Case
String word2 = word1.toUpperCase();
String word3 = word1.toLowerCase();
returns a new string formed fromword1 by
converting its characters toupper (lower) case
String word1 = HeLLo;
String word2 = word1.toUpperCase();//HELLO
String word3 = word1.toLowerCase();//hello
//word1 is still HeLLo
-
8/8/2019 The String Class (1)
41/46
Replacements
Example: to convert word1 toupper case, replace
the reference with a new reference.
A common bug:
word1 = word1.toUpperCase();
word1.toUpperCase();word1
remains
unchanged
-
8/8/2019 The String Class (1)
42/46
Numbers to Strings
Three ways to convert a number into a string:
1. String s = "" + num;
2. String s = Integer.toString (i);
String s = Double.toString (d);
3. String s = String.valueOf (num);
Integerand Double
are wrapper classes
fromjava.lang that
represent numbers as
objects. They also
provide useful static
methods.
s = String.valueOf(123);//123
s = + 123;//123
s = Integer.toString(123);//123
s = Double.toString(3.14); //3.14
-
8/8/2019 The String Class (1)
43/46
Review Questions:
1. The String class is part ofwhatpackage?
2. What does the String class have thatother classes do not have?
3. Text enclosed in quotes is called ?
4. What is the returned value forRumplestiltskin.length()?
5. Define immutable objects.
-
8/8/2019 The String Class (1)
44/46
Review (contd):
6. How does immutability ofStrings
make Java more efficient?
7. How does immutability ofStringsmake Java less efficient?
8. How do you declare an empty string?
9. Why are String constructors not usedvery often?
10. Bob + + Smith is called ____ ?
-
8/8/2019 The String Class (1)
45/46
Review (contd):
11. String city = "Bloomington;
What is returned by city.charAt (2)?
12. By city.substring(2, 4)?
13. By city.lastIndexOf(o)?
14. By city.indexOf(3)?
15. What does the trimmethod do?
-
8/8/2019 The String Class (1)
46/46
Review (contd):
16. sam.equals(Sam) returns ?
17. What kind ofvalue does
sam.compareTo(Sam) return?18. What will be stored in s?
s = mint.replace(t, e);
19. What does s.toUpperCase() do to s?20. Name a simple way to convert a
number into a string.