构造方法
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));
}
}