String类
一、String类的特性
-
String
类代表字符串,Java中所有的字符串字面值(如“abc”)都作为此类的实现类 -
String类是一个
final
类,代表不可变字符,且不可被继承
-
字符串是常量,用双引号包含起来表示。他们的值在擦黄健之后不能更改。
-
String对象的字符内容是存储在一个字符数组
value[]
中的 -
String实现了
Serializable
接口:表示字符串是支持序列化的 -
实现了
Comparable
接口:表示String可以比较大小 -
String在内部定义了
final char[] value
用于存储字符数据
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
1.1String的不可变性
- String:代表不可变的字符序列。简称
不可变性
。
体现:
①:当对字符串重新赋值时,需要重新指定内存区域赋值,不能使用原有的value上进行赋值
②:当对已有字符串进行连接操作时,也需要重新指定内存区域赋值,不能在原有的value上赋值
③:当调用String的replace
方法修改指定字符串或字符时,也需要重新指定内存区域赋值,不能在原有的value
上赋值
@Test
@Test
public void test1(){
//此处s1\s2共用一个"abc"
String s1 = "abc";//字面量定义,
/*
s1首次使用"abc",在直接在方法区字符串常量池中直接生成了"abc"
并把"abc"的首地址值赋给s1
*/
String s2 = "abc";
/*
常量池中不会存在两个相同的字符串,所以这里s2得到的"abc"与s1得到的一样
*/
String s3 = "abc";
s3 += "def";
System.out.println(s3 == s2);//false
/*
此处对s3的拼接操作,是在字符串常量池中又新建了一个字符串
*/
String s4 = "abc";
String s5 = s4.replace("a","m");
System.out.println(s4);
System.out.println(s5);
}
输出
false
abc
mbc
false
1.2String的不同实例化方式(String 对象的创建)
1.2.1
String str = "hello";
//本质上this.value = new char[0];
String s1 = new String();
//this.value = original.value;
String s2 = new String(String original);
//this.value = Arrays.copyOf(value,value.length);
String s3 = new String(char[] a);
String s4 = new String(char[] a,int startIndex,int count);
1.2.2 String s1 = “abc”; 与 String s2 = new String(“abc”); 的区别
@Test
public void Test2(){
/*
String 的实例化方式
方式一:通过字面量定义的方式
方式二:通过new+构造器的方式
*/
//字面量定义:此时的地址值是在方法区中字符串常量池中的唯一的地址值,常量池中只有一个“hello”
String s1 = "hello";
String s3 = "hello";
//new:此时的地址值,是数