目录
String类的特性
1. 代表字符串。Java 程序中的所有字符串字面值(如 "abc")都作为此类的实例实现
2. String 是一个 final 类,代表不可变的字符序列
3. 字符串是常量,用双引号引起来表示。它们的值在创建之后不能修改
4. String 对象的字符内容是存储在一个字符数组 value[ ] 中的
String类的使用
1. String 声明为 final ,不可被继承
2. String 实现了 Serializable 接口:表示字符串是支持序列化的
Comparable 接口:表示 String 可以比较大小
3. String 内部定义了 final char[ ] value 用于存储字符串数据
4. String 代表不可变的字符序列。简称:不可变性
当对字符串重新赋值时,需要重新指定内存区域赋值,不能使用原有的 value 进行赋值
String s1 = "abc"; //字面量的定义方式
String s2 = "abc";
System.out.println(s1 == s2); //true 比较s1和s2的地址值
s1 = "helllo";
System.out.println(s1); //hello
当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的 value 进行赋值
String s1 = "abc";
String s2 = "abc";
s1 += "def";
System.out.println(s1); //abcdef
System.out.println(s2); //abc
当调用 String 的 replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有的 value 进行赋值
String s1 = "abc";
String s2 = s1.replace('a','d');
System.out.println(s1); //abc
System.out.println(s2); //dbc
5. 通过字面量的方式(区别于 new)给一个字符串赋值,此时的字符串值声明在字符串常量池中
6. 字符串常量池中是不会存储相同内容的字符串的
String不同实例化方式的对比
通过 String s = new String("abc"); 方式创建对象,在内存中创建了两个对象
一个是堆空间中的 new 结构,一个是 char[ ] 对应的常量池中的数据:"abc"
public class MyTest {
public static void main(String[] args) {
//字面量的定义方式,此时的s1和s2数据声明在方法区中字符串常量池中
String s1 = "abc";
String s2 = "abc";
//通过 new + 构造器的方式,此时的s3和s4保存的地址值,是数据在堆空间中开辟空间以后对应的地址值
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println(s1 == s2);//true
System.out.println(s1 == s3);//false
System.out.println(s3 == s4);//false
}
}
String不同拼接操作对比
1. 常量与常量的拼接结果在方法区的常量池中,且常量池中不会存在相同内容的常量
2. 只要其中有一个是变量,结果就在堆中
3. 如果拼接的结果调用 intern()方法,返回值就在常量池中
public class MyTest {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "def";
String s3 = "abcdef";
String s4 = "abc" + "def";
String s5 = s1 + "def";
String s6 = "abc" + s2;
String s7= s1 + s2;
System.out.println(s3 == s4);//true
System.out.println(s3 == s5);//false
System.out.println(s3 == s6);//false
System.out.println(s5 == s6);//false
System.out.println(s5 == s7);//false
System.out.println(s6 == s7);//false
String s8 = s5.intern();
System.out.println(s3 == s8);//true
}
}
有关String的面试题
public class MyTest {
String str = new String("good");
char[] ch = {'t','e','s','t'};
public void change(String str, char ch[]){
str = "test ok";
ch[0] = 'b';
}
public static void main(String[] args) {
MyTest ex = new MyTest();
ex.change(ex.str, ex.ch);
System.out.println(ex.str);
System.out.println(ex.ch);
}
}
>>> good
best