Java中的String(1)

String不可變

摘自JDK1.8 API文檔

Strings are constant; their values cannot be changed after they are created.

這玩意被創造出來之後就是不可變的了。

如下代碼:

public class String_01 {
    public static void main(String[] args) {
        // 1 String是不可變的
        String a = "abc";
    }
}

圖1


重新創建了一個新的abc123,而不是直接在原有的abc後面直接加

public class String_01 {
    public static void main(String[] args) {
        // 1 String是不可變的
        String a = "abc";
        a = a + "123";
    }
}

在這裏插入圖片描述


一個例子

是字符串常量的情況下

這種情況下,字符串常量都在數據棧中。常量是被共享的。

public class String_02 {
    public static void main(String[] args) {
        String s1 = "oh";
        String s2 = "oh";
        System.out.println(s1 == s2);
    }
}

如圖:
在這裏插入圖片描述


是對象的情況下

public class String_02 {
    public static void main(String[] args) {
        String s1 = new String("oh");
        String s2 = new String("oh");
        System.out.println(s1 == s2); // flase
        System.out.println(s1.equals(s2)); // true
    }
}

在這裏插入圖片描述


String中對equals方法的說明:

  • Compares this string to the specified object.
  • The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

總結一下就是:
要返回true的話

  • equals方法的參數不能爲空
  • 和被比較的是相同的字符序列

所以,第一個爲false,可以看圖理解一下。
第二個爲true,因爲滿足我們上面兩個規則。

常用的方法

具體可查看API文檔,本處不再贅述。
學習查看API也是一種非常重要的能力。

注意
一般情況下,工作中用的比較多的就是截取字符串。
但有時候會忘記這裏的截取究竟從1開始,還是從0開始。
亦或者兩者都行。

其實,很容易記住:
看官方文檔中String類的一個構造方法:

public String(char[] value)

char data[] = {'a', 'b', 'c'};
String str = new String(data);

也就是說,String可以由字符數組構造出來。
那麼既然是數組。
所以必須是從
0
開始

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章