Character Strings class String Buffer Java 1 4

Character Strings class String. Buffer (Java 1. 4 and before : thread-safe) class String. Builder (Java 5 : thread-unsafe) (Cf. array of characters) Based on 2 -byte Unicode characters cs 480 (Prasad) L 9 Strings 1

class String vs class String. Buffer/String. Builder • immutable • mutable – contents of String instance unchangeable – cannot insert or append characters • fixed length • s. length() – number of characters in the string cs 480 (Prasad) – contents of String. Buffer instance modifiable • growable – grows automatically when characters added • sb. length() • sb. capacity() – total allocated capacity L 9 Strings 2

String literals and concatenation • String s = “abc”; • System. out. println( s + “def” ); – “+” stands for string concatenation. – Built-in operator overload. • Left associativity of “+” – (s + 3 + 5) – (s + (3 + 5)) – (5 + 3 + s) cs 480 (Prasad) evaluates to “abc 35”. evaluates to “ 8 abc”. L 9 Strings “abc 8”. 3

Left Associativity of “+” • “+” is an associative operation on integers. (i + (j + k) ) == ( (i + j) + k) • “+” is an associative operation on strings. (s 1 + (s 2 + s 3) ) == ( (s 1 + s 2) + s 3) • However, when expressions mix both strings and integers, in the presence of coercion, the “+” operation is not associative. (s + (i + j) ) != ( (s + i) + j) int-plus cs 480 (Prasad) string-concat L 9 Strings 4

String conversions supports to. String()-method to convert a class instance into a printable string form: classname@hashcode to. String() can be overridden. • class Object • public String to. String() {. . . }; methods in System. out, the “+”-expressions, and the “+= ”-statements invoke to. String() implicitly, to coerce an instance to a string. • println/print cs 480 (Prasad) L 9 Strings 5

Assignment String s = “abc”; s += 2+3+5; s. equals(“abc 10”) == true s. equals(“abc 235”) == false (Recall that “+” is left-associative. ) (cf. s = s + 2 + 3 + 5; ) Type E 1; E 1 += E 2; E 1 = (Type) ((E 1) + (E 2)) cs 480 (Prasad) L 9 Strings 6

cs 480 (Prasad) L 9 Strings 7

Comparison • “abc”. equals(“abc”) is true. • “abc”. equals. Ignore. Case(“ABC”) is is true. • “abc” == new String(“abc”) false. (skipping String interning details) • • s == s is true. s 1. compare. To(s 2) • negative: s 1 lexicographically precedes s 2 • zero: s 1 is equal s 2 • positive: s 1 lexicographically follows s 2 cs 480 (Prasad) L 9 Strings 8

Useful Methods – String t = “abca”; – String s = new String(t); • s. char. At(2) • s. index. Of(‘a’) • s. index. Of(“bc”) • s. index. Of(‘a’, 2) • s. last. Index. Of(‘a’) is is is ‘c’. 0. 1. 3. 3. • region. Matches, starts. With, ends. With, etc. – Pure ASCII applications can be inefficient because Java uses 16 -bit Unicode characters. cs 480 (Prasad) L 9 Strings 9
- Slides: 9