構造方法
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 s = new String("hello");
System.out.println(s);
System.out.println("............");
char[] arr = {'h','e','l','l','o'};
String s1 = new String(arr);
System.out.println(s1);
System.out.println("............");
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);
}
}
通過構造方法創建的對象和直接賦值創建的對象的區別
- 通過構造方法創建的對象在堆內存中
- 通過直接賦值創建的對象在方法區的常量池中
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));
}
}