A String object is immutable; its contents cannot be changed
String s = "Java"; s = "HTML"; // original "Java" not changed
p.327 Figure 9.1 Strings are immutable; once created, their contents cannot be changed
p.327 Figure 9.2 interned string instance
String s1 = "SCU CSIM"; String s2 = new String("SCU CSIM"); String s3 = "SCU CSIM"; System.out.printf("s1=[%s] s2=[%s] s3=[%s]\n", s1, s2, s3); System.out.printf("1 s1==s2 is %b\n", s1 == s2); System.out.printf("2 s1==s3 is %b\n", s1 == s3); System.out.printf("3 s1 equals s2 is %b\n", s1.equals(s2)); System.out.printf("4 s1 equals s3 is %b\n", s1.equals(s3));
p.327 Figure 9.2 The String class contains the methods for comparing strings
if (s1 == s2) { System.out.println("s1 s2 相同字串物件"); } else { System.out.println("s1 s2 不同字串物件"); } if (s1.equals(s2)) { System.out.println("s1 s2 字串內容相等"); } else { System.out.println("s1 s2 字串內容不相等"); }
p.328 Caution 不可以使用 < > 來比較字串,需要使用 compareTo
p.328 Note equals : true, false; compareTo : <0, 0, >0
p.329 Figure 9.3 The String class contains the methods for getting string length, individual characters, and combining string
p.329 Caution string charAt from 0 to length()-1
s1 = "All"; s2 = "Pass"; s3 = s1.concat(s2); s3 = s1 + " " + s2;
p.330 Figure 9.5 The String class contains the methods for obtaining substrings. substring
p.330 Figure 9.6 The substring method obtains a substring from a string
p.331 Figure 9.7 The String class contains the methods for converting, replacing, and splitting strings.
參考 regular expression (RE)
p.333 Figure 9.8 The String class contains the methods for matching substrings.
s = String.format("height=%d, weight=%.1f", 185, 72.5);
參考 p.334 程式 Listing 9.1 CheckPalindrome.java
參考 p.336 程式 Listing 9.2 HexToDecimalConversion.java