-String 對象創建后則不能被修改,是不可變的,所謂的修改其實是創建了新的對象,所指向的內存空間不同。 -多次出現的字符串,Java編譯器只創建一個。 -一旦一個字符串在內存中創建,則這個字符串將不可改變。如果需要一個可以改變的字符串,我們可以使用 StringBuffer或者StringBuilder。 -每次 new 一個字符串就是產生一個新的對象,即便兩個字符串的內容相同,使用 ”==” 比較時也為 ”false” ,如果只需比較內容是否相同,應使用 ”equals()” 方法。
public class test { public static void main(String[] args) { String s1 = "123"; String s2 = "123"; String s3 = new String("123"); String s4 = new String("123"); System.out.PRintln(s1==s2); System.out.println(s1==s3); System.out.println(s4==s3); }}true false false

-1. 字符串 str 中字符的索引從0開始,范圍為 0 到 str.length()-1
-2. 使用 indexOf 進行字符或字符串查找時,如果匹配返回位置索引;如果沒有匹配結果,返回 -1
-3. 使用 substring(beginIndex , endIndex) 進行字符串截取時,包括 beginIndex 位置的字符,不包括 endIndex 位置的字符
public class Test2 { public static void main(String[] args) { String s1 = "abcd/efgh"; String s2 = "1234/5678"; String s3 = " 1234/5678"; String s4 = new String("abcd/efgh"); String[] s5; String[] s6; byte[] b1; System.out.println(s1.length()); System.out.println(s1.indexOf("a")); System.out.println(s1.indexOf("abcd")); System.out.println(s1.lastIndexOf("efgh")); System.out.println(s1.lastIndexOf("e")); System.out.println(s1.substring(2)); System.out.println(s1.substring(2,7)); System.out.println(s3.trim()); System.out.println(s1.equals(s4)); System.out.println(s1.toLowerCase()); System.out.println(s1.toUpperCase()); System.out.println(s1.charAt(4)); s5 = s1.split("/"); System.out.println(s5[0]); s6 = s1.split("/",0); System.out.println(s6[0]); b1 = s1.getBytes(); System.out.println(b1[1]); }}9 0 0 5 5 cd/efgh cd/ef 1234/5678 true abcd/efgh ABCD/EFGH / abcd abcd 98
-String 類具有是不可變性。StringBuilder可變。 -當頻繁操作字符串時,如果用String則會生成很多對象、臨時變量,降低系統性能。 - StringBuilder 和StringBuffer ,它們基本相似,不同之處,StringBuffer 是線程安全的,而 StringBuilder 則沒有實現線程安全功能,所以性能略高。 -創建內容可變的字符串對象優先考慮StringBuilder。

123213456 123213456456 true 12
新聞熱點
疑難解答