String and String Builder Part I String All
String and String. Builder Part I: String All examples in String. Examples in the repository 22 -Oct-21
About Strings n Strings are objects, but there is a special syntax for writing String literals: "Hello" n Strings, unlike most other objects, have a defined operation (as opposed to a method): " This " + "is String " + "concatenation"" n Strings can contain any character, but some of them must be “escaped” in order to write them in a literal n n " stands for the double-quote (") character n stands for the newline character \ stands for the backslash ()character Each of these is written as a two-character sequence, but represents a single character in the string 2
Useful String methods I n char. At(int index) n n boolean starts. With(String prefix) n n Returns the character at the given index position (0 -based) Tests if this String starts with the prefix String boolean ends. With(String suffix) n Tests if this String ends with the suffix String 3
Useful String methods II n boolean equals(Object obj) n n boolean equals. Ignore. Case(String other) n n Tests if this String is the same as the obj (which may be any type; false if it’s not a String) Tests if this String is equal to the other String, where case does not matter int length() n Returns the length of this string; note that this is a method, not an instance variable 4
Useful String methods III n int index. Of(char ch) n n int index. Of(char ch, int from. Index) n n Returns the position of the first occurrence of ch in this String, or -1 if it does not occur Returns the position of the first occurrence of ch, starting at (not after) the position from. Index There are two similar methods that take a String instead of a char as their first argument 5
Useful String methods IV n int last. Index. Of(char ch) n n int last. Index. Of(char ch, int from. Index) n n Returns the position of the last occurrence of ch in this String, or -1 if it does not occur Returns the position of the last occurrence of ch, searching backward starting at position from. Index There are two similar methods that take a String instead of a char as their first argument 6
Useful String methods V n String substring(int begin. Index) n n Returns a new string that is a substring of this string, beginning with the character at the specified index and extending to the end of this string. String substring(int begin. Index, int end. Index) n Returns a new string that is a substring of this string, beginning at the specified begin. Index and extending to the character at index end. Index - 1. Thus the length of the substring is end. Index-begin. Index 7
Understanding “index” n With char. At(index), index. Of(x), and last. Index. Of(x), just count characters (starting from zero) "She said, "Hi"" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 n With substring(from) and substring(from, to), it works better to count positions between characters "She said, "Hi"" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 n n So, for example, substring(4, 8) is "said", and substring(8, 12) is ", "H" If index. Of(', ') is 8, then substring(0, index. Of(', ')) is "She said" and substring(index. Of(', ') + 1) is " "Hi"" 8
Useful String methods VI n String to. Upper. Case() n n String to. Lower. Case() n n Returns a new String similar to this String, in which all letters are uppercase Returns a new String similar to this String, in which all letters are lowercase String trim() n Returns a new String similar to this String, but with whitespace removed from both ends 9
Useful String methods VII n String[] split(String regex) n n n Breaks the string up into an array of strings The parameter is a regular expression that defines what separates the strings For example, String s = "one, two, three"; String[] ss = s. split(", "); n n This assigns the array {"one", "two", "three"} to ss Regular expressions are complex expressions that assign meanings to many common punctuation marks, such as +, *, period, and [ n Hence, regular expressions are powerful, but can be treacherous if you aren’t very familiar with them 10
Finally, a useless String method n String to. String() n n Returns this String Why do we have this method? n Consistency--Every Object has a to. String() method 11
Strings are immutable n n n A String, once created, cannot be changed None of the preceding methods modify the String, although several create a new String Statements like this create new Strings: my. String = my. String + another. Character; n n Creating a few extra Strings in a program is no big deal Creating a lot of Strings can be very costly 12
More about equals n If you write String s = "abc"; String t = "abc“; the compiler only creates the string "abc" once, and makes s and t both refer to this one string n n However, if you now write String u = new String(“abc”); the test s == u will be false n n It can do this because strings are immutable Hence, the test s == t will be true This is because they are different strings Moral: Use equals for strings, not == For more on this http: //stackoverflow. com/questions/13098668/javastring-comparison-equals-vs String interning 13
String interning n n For an efficient use of memory, JVM manages String values (especially String literals) by putting them in a special area of memory called the “String constant pool”. If you use a literal value to initialize a String, the JVM checks the pool to see if the String value is already in memory. If it is, it will not create a new value, it will put its address in the reference. 14
Still more about equals n Suppose you want to test whether a variable name has the value "Dave" n n Here’s the obvious way to do it: if (name. equals("Dave")) {. . . } But you could also do it this way: if ("Dave". equals(name)) {. . . } It turns out that the second way is usually better Why? n If name == null, the first way will cause a Null. Pointer. Exception, but the second way will just return false 15
Strings, Etc. Part II: String. Builder 22 -Oct-21
About String. Builders n n n A String. Builder has a capacity (the number of characters it can hold) and a length (the number of characters it is currently holding) If the capacity is exceeded, the String. Builder is copied to a new location with more room String. Builder is a reimplementation of String. Buffer n n n The API (collection of methods) is the same String. Buffers are threadsafe, but String. Builders are more efficient String. Builders are used to implement String concatenation n n Whenever you say String s = "ab" + "cd", Java creates a String. Buffer containing the characters a and b, appends the characters c and d to it, and converts the result back to a String As you might guess, this isn’t terribly efficient, but it’s fine if you don’t overdo it 17
String. Builder constructors n String. Builder() n n String. Builder(int capacity) n n Constructs a String. Builder with a capacity of 16 characters Constructs a String. Builder with the requested capacity String. Builder(String str) n Constructs a String. Builder containing the String str 18
Useful String. Builder methods I n String. Builder append(X) n n Appends X to the end of this String. Builder; also (as a convenience) returns this String. Builder The append method is so heavily overloaded that it will work with any argument; if the argument is an object, its to. String() method is used 19
Useful String. Builder methods II n int length() n n Returns the number of characters in this String. Builder void set. Length(int new. Length) n Sets the number of characters in this String. Builder; this may result in truncation of characters at the end, or addition of null characters 20
Useful String. Builder methods III n char. At(int index) n n void set. Char. At(int index, char ch) n n Returns the character at the location index Sets the character at location index to ch String. Builder reverse() n The sequence of characters in this String. Builder is replaced by the reverse of this sequence, and also returned as the value of the method 21
Useful String. Builder methods IV n String. Builder insert(int offset, X) n n String. Builder delete. Char. At(int index) n n Insert X starting at the location offset in this String. Builder, and also return this String. Builder as the value of the method. Like append, this method is heavily overloaded Deletes the character at location index String. Builder delete(int start, int end) n Deletes chars at locations start through end-1 22
Useful String. Builder methods V n String substring(int start) n n String substring(int start, int end) n n Returns a new String of characters from this String. Builder, beginning with the character at the specified index and extending to the end of this string. Returns a new String of characters from this String. Builder, beginning at location start and extending to the character at index end-1. Thus the length of the substring is end-begin String to. String() n Returns the characters of this String. Builder as a String 23
When to use String. Builders n n n If you make a lot (thousands) of changes or additions to a String, it is much more efficient to use a String. Builder If you are simply examining the contents of a String, then a String is at least as efficient as a String. Builder For incidental use (such as creating output lines), use Strings; they are more convenient 24
Strings, etc. Part III: Characters 22 -Oct-21
The Character class n char is a primitive type, not an object, therefore… …there are no methods you can call on a char This is why we need a Character class! n There a lot of methods in the Character class n n They are all static Do you see why? 26
Some Character methods n n n n n static boolean is. Digit(char ch) static boolean is. Letter. Or. Digit(char ch) static boolean is. Lower. Case(char ch) static boolean is. Upper. Case(char ch) static boolean is. Whitespace(char ch) static char to. Lower. Case(char ch) static char to. Upper. Case(char ch) For more methods, see java. lang. Character 27
- Slides: 27