Java中的String類

構造方法

  String:字符串類
        由多個字符組成的一串數據;其本質是一個字符數組;

  構造方法:
            String(String original):把字符串數據封裝成字符串對象
            String(char[] value):把字符數組的數據封裝成字符串
            String(char[] value, int offset, int count):把字符數組中的一部分數據封裝成字符串對象
                                                         offset:從第幾個索引開始        count:一共截取幾個
package Test8;

public class StringDemo {
    public static void main(String[] args) {
        //String(String original) 
        String s = new String("hello");
        System.out.println(s);

        System.out.println("............");

        //String(char[] value)
        char[] arr = {'h','e','l','l','o'};
        String s1 = new String(arr);
        System.out.println(s1);

        System.out.println("............");

        //String(char[] value, int offset, int count)
        char[] arr1 = {'h','e','l','l','o'};
        String s2 = new String(arr1,1,4);
        System.out.println(s2);

        System.out.println("............");

        //直接賦值創建對象
        String s3 = "hello";
        System.out.println(s3);
    }
}

通過構造方法創建的對象和直接賦值創建的對象的區別

  1. 通過構造方法創建的對象在堆內存中
  2. 通過直接賦值創建的對象在方法區的常量池中
package Test8;

public class StringDemo2 {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = "hello";
        String s3 = "hello";

        System.out.println("s1和s2地址值是否相同:"+(s1==s2));
        System.out.println("s1和s3地址值是否相同:"+(s1==s3));
        System.out.println("s2和s3地址值是否相同:"+(s2==s3));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章