The String Class Objectives n n n Learn
The String Class
Objectives: n n n Learn about literal strings Learn about String constructors Learn about commonly used methods Understand immutability of strings Learn to format numbers into strings
String class facts n n An object of the String class represents a string of characters. The String class belongs to the java. lang package, which does not require an import statement. Like other classes, String has constructors and methods. Unlike other classes, String has two operators, + and += (used for concatenation).
Literal Strings n n n are anonymous objects of the String class are defined by enclosing text in double quotes. “This is a literal String” don’t have to be constructed. can be assigned to String variables. can be passed to methods and constructors as parameters. have methods you can call.
Literal String examples //assign a literal to a String variable String name = “Robert”; //calling a method on a literal String char first. Initial = “Robert”. char. At(0); //calling a method on a String variable char first. Initial = name. char. At(0);
Immutability n n n Once created, a string cannot be changed: none of its methods changes the string. Such objects are called immutable. Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change.
Advantages Of Immutability Uses less memory. String word 1 = "Java"; String word 2 = word 1; word 1 “Java" word 2 OK String word 1 = “Java"; String word 2 = new String(word 1); word 1 “Java" word 2 “Java" Less efficient: wastes memory
Disadvantages of Immutability Less efficient — you need to create a new string and throw away the old one even for small changes. String word = “Java"; char ch = Character. to. Upper. Case(word. char. At (0)); word = ch + word. substring (1); word “java" “Java"
Empty Strings n An empty String has no characters. It’s length is 0. String word 1 = ""; String word 2 = new String(); n Empty strings Not the same as an uninitialized String. private String error. Msg; error. Msg is null
No Argument Constructors n No-argument constructor creates an empty String. Rarely used. String empty = new String(); n A more common approach is to reassign the variable to an empty literal String. (Often done to reinitialize a variable used to store input. ) String empty = “”; //nothing between quotes
Copy Constructors n n Copy constructor creates a copy of an existing String. Also rarely used. Not the same as an assignment. Copy Constructor: Each variable points to a different copy of the String word = new String(“Java”); String word 2 = new String(word); word 2 “Java" Assignment: Both variables point to the same String word = “Java”; String word 2 = word; word 2 “Java"
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”
Methods — length, char. At int length(); n Returns the number of characters in the string char. At(i); n Returns the char at position i. Character positions in strings are numbered starting from 0 – just like arrays. Returns: ”Problem". length(); 7 ”Window". char. At (2); ’n'
Methods — substring Returns a new String by copying characters from an existing String. n n String subs = word. substring (i, k); ¡ returns the substring of chars in positions from i to k-1 String subs = word. substring (i); ¡ returns the substring from the i-th char to the end ”television". substring (2, 5); “immutable". substring (2); “bob". substring (9); television i k television i Returns: “lev" “mutable" "" (empty string)
Methods — Concatenation String word 1 = “re”, word 2 = “think”; word 3 = “ing”; int num = 2; n String result = word 1 + word 2; //concatenates word 1 and word 2 “rethink“ n String result = word 1. concat (word 2); //the same as word 1 + word 2 “rethink“ n result += word 3; //concatenates word 3 to result “rethinking” n result += num; //converts num to String //and concatenates it to result “rethinking 2”
Methods — Find (index. Of) 0 2 6 10 15 String name =“President George Washington"; date. index. Of (‘P'); date. index. Of (‘e'); date. index. Of (“George"); date. index. Of (‘e', 3); Returns: 0 2 10 (starts searching 6 at position 3) date. index. Of (“Bob"); -1 date. last. Index. Of (‘e'); 15 (not found)
Methods — Equality boolean b = word 1. equals(word 2); returns true if the string word 1 is equal to word 2 boolean b = word 1. equals. Ignore. Case(word 2); returns true if the string word 1 matches word 2, case-blind b = “Raiders”. equals(“Raiders”); //true b = “Raiders”. equals(“raiders”); //false b = “Raiders”. equals. Ignore. Case(“raiders”); //true if(team. equals. Ignore. Case(“raiders”)) System. out. println(“Go You “ + team);
Methods — Comparisons int diff = word 1. compare. To(word 2); returns the “difference” word 1 - word 2 int diff = word 1. compare. To. Ignore. Case(word 2); returns the “difference” word 1 - word 2, case-blind Usually programmers don’t care what the numerical “difference” of word 1 - word 2 is, just whether the difference is negative (word 1 comes before word 2), zero (word 1 and word 2 are equal) or positive (word 1 comes after word 2). Often used in conditional statements. if(word 1. compare. To(word 2) > 0){ //word 1 comes after word 2… }
Comparison Examples //negative differences diff = “apple”. compare. To(“berry”); //a before b diff = “Zebra”. compare. To(“apple”); //Z before a diff = “dig”. compare. To(“dug”); //i before u diff = “dig”. compare. To(“digs”); //dig is shorter //zero differences diff = “apple”. compare. To(“apple”); //equal diff = “dig”. compare. To. Ignore. Case(“DIG”); //equal //positive differences diff = “berry”. compare. To(“apple”); //b after a diff = “apple”. compare. To(“Apple”); //a after A diff = “BIT”. compare. To(“BIG”); //T after G diff = “huge”. compare. To(“hug”); //huge is longer
Methods — trim String word 2 = word 1. trim (); returns a new string formed from word 1 by removing white space at both ends does not affect whites space in the middle String word 1 = “ Hi Bob “; String word 2 = word 1. trim(); //word 2 is “Hi Bob” – no spaces on either end //word 1 is still “ Hi Bob “ – with spaces
Methods — replace String word 2 = word 1. replace(old. Ch, new. Ch); returns a new string formed from word 1 by replacing all occurrences of old. Ch with new. Ch String word 1 = “rare“; String word 2 = “rare“. replace(‘r’, ‘d’); //word 2 is “dade”, but word 1 is still “rare“
Methods — Changing Case String word 2 = word 1. to. Upper. Case(); String word 3 = word 1. to. Lower. Case(); returns a new string formed from word 1 by converting its characters to upper (lower) case String word 1 = “He. LLo“; String word 2 = word 1. to. Upper. Case(); //”HELLO” String word 3 = word 1. to. Lower. Case(); //”hello” //word 1 is still “He. LLo“
Replacements n Example: to “convert” word 1 to upper case, replace the reference with a new reference. word 1 = word 1. to. Upper. Case(); n A common bug: word 1. to. Upper. Case(); word 1 remains unchanged
Numbers to Strings Three ways to convert a number into a string: 1. String s = "" + num; Integer and Double s = “” + 123; //” 123” 2. String s = Integer. to. String (i); String s = Double. to. String (d); s = Integer. to. String(123); //” 123” s = Double. to. String(3. 14); //” 3. 14” are “wrapper” classes from java. lang that represent numbers as objects. They also provide useful static methods. 3. String s = String. value. Of (num); s = String. value. Of(123); //” 123”
Review Questions: 1. 2. 3. 4. 5. The String class is part of what package? What does the String class have that other classes do not have? “Text enclosed in quotes is called ? ” What is the returned value for “Rumplestiltskin”. length()? Define immutable objects.
Review (cont’d): 6. 7. 8. 9. 10. How does immutability of Strings make Java more efficient? How does immutability of Strings make Java less efficient? How do you declare an empty string? Why are String constructors not used very often? “Bob” + “ “ + “Smith” is called
Review (cont’d): 11. 12. 13. 14. 15. String city = "Bloomington“; What is returned by city. char. At (2)? By city. substring(2, 4)? By city. last. Index. Of(‘o’)? By city. index. Of(3)? What does the trim method do?
Review (cont’d): 16. 17. 18. 19. 20. “sam”. equals(“Sam”) returns ? What kind of value does “sam”. compare. To(“Sam”) return? What will be stored in s? s = “mint”. replace(‘t’, ‘e’); What does s. to. Upper. Case() do to s? Name a simple way to convert a number into a string.
- Slides: 28