2、构造方法
A: String s = new String();
-- 空字符序列
B: String s = new String(byte[] bys);
-- 使用平台的默认字符集解码指定的 byte 数组,构造一个 String。
C: String s = new String(byte[] bys, int index, int length);
-- 使用平台的默认字符集解码指定的 byte 数组,构造一个 String。从索引为 index 处开始,截取长度为 length。
如果参数 index 或者 length 超出数组范围,报出:java.lang.StringIndexOutOfBoundsException
D: String s = new String(char[] chs);
-- 使用字符数组中包含的字符序列,构造一个 String。
E: String s = new String(char[] chs, int index, int length);
-- 使用字符数组中包含的字符序列,构造一个 String。从索引为 index 处开始,截取长度为 length。
如果参数 index 或者 length 超出数组范围,报出:java.lang.StringIndexOutOfBoundsException
F: String s = new String(String str);
G: String s = "hello";
3、特点
A:字符串一旦初始化就不可以改变。(注意:是指字符串在常量池中的值不可以改变,不是指引用。)
B:面试题:
a:String s = new String("hello")和String s = "hello"的区别。
第一种方式在内存中有两个对象。
第二种方式只有一个对象。
b:请写出结果:
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1==s2); // false
System.out.println(s1.equals(s2)); // true