谈谈Java中最常用的类—String

java.lang.String 类可以说是 Java 中最常被使用的一个类,它是一个很普通的类,但是又有很多特殊的地方。本文主要讲解两个部分:

① 使用不同方式创建字符串区别

② String 一个重要的特性:不可变性。

首先,以一道面试题为开始:

@Test
public void test01() {
    String s1 = "hello";
    String s2 = "world";

    String s3 = "helloworld";
    String s4 = "hello" + "world";
    String s5 = new String("helloworld");
    String s6 = s1 + s2;
    String s7 = s1 + "world";

    final String s8 = "hello";
    String s9 = s8 + "world";

    System.out.println("s3 == s4:" + (s3 == s4));
    System.out.println("s3 == s5:" + (s3 == s5));
    System.out.println("s3 == s6:" + (s3 == s6));
    System.out.println("s6 == s7:" + (s6 == s7));
    System.out.println("s3 == s9:" + (s3 == s9));
}





输出结果:
s3 == s4:true
s3 == s5:false
s3 == s6:false
s6 == s7:false
s3 == s9:true

结果是不是很奇怪,明明内容都是“helloworld”,为什么有的是 true,有的是 false 呢?想要搞清楚其中的原因,就必须先理解 JVM 底层是如何给 String 变量赋值的。

一、使用不同方式创建字符串

1、方式一:使用字面量方式赋值(即:使用 “” 方式)

当执行 String s1 = "helloworld"; 语句时,JVM 会先在常量池中查找是否已经存在 "helloworld" 字符串,如果已存在,则不会重新创建对象,而是直接将该字符串内存地址赋值给 s1,如果不存在,就在常量池中创建新的字符串对象“helloworld”。

                                                                     a. 首次创建某个字符串(s1)

                                                                        b. 非首次创建某个字符串(s2)

由上图可以看出,同样使用字面量方式创建的两个字符串的内存地址是相同的,所以 “s1==s2” 的结果为 true。

2、方式二:使用 new 方式创建字符串

当执行 String s3 = new String("helloworld"); 语句时,JVM 先会在堆中创建一个对象,该对象的值指向常量池中对应字符串的内存地址。

由上图可以看出,通过 new 方式创建的字符串,栈中存放的是堆中对象的内存地址,而不是常量池中对象的内存地址,所以 “s3 == s1” 结果是 false。

3、使用拼接方式给字符串变量赋值

(1)当全部都是常量拼接时:本质和使用字面量类似,其栈中存放的内存地址值还是指向常量池中的内存地址。如:String s4 = "hello" + "world"; (使用 final 修饰的字符串变量也是常量,如:图中的 s5)。

 

(2)当拼接中有变量时:本质和使用 new 的方式类似,会先在堆中创建一个对象,堆中对象的值就是常量池中对应字符串的内存地址。

结论:

  1. 使用一个或多个常量给字符串赋值时,栈中的内存地址(即变量的地址)指向的是常量池中的对象地址,并且常量池中不会存在相同内容的常量。
  2. 只要赋值等式右侧存在变量,栈中的内存地址(即变量的地址)指向的就是堆中对象的内存地址。

另外:可以调用 String 的 方法,此时,栈中的内存地址指向为常量池中对象的地址。

@Test
public void test02() {
    String str1 = "helloworld";

    String str2="hello";
    String str3 = str2 + "world";
    String str4 = str3.intern();
    System.out.println("str1 == str3:" + (str1 == str3));
    System.out.println("str1 == str4:" + (str1 == str4));
}

输出结果:
str1 == str3:false
str1 == str4:true

二、关于String的不可变性

如何理解 String 是一个不可变的字符序列,还是举个例子:

@Test
public void test03() {
    String s1 = "helloworld";
    String replace = s1.replace("o", "g");

    System.out.println("s1=" + s1);
    System.out.println("replace=" + replace);

    String substring = s1.substring(0, 5);
    System.out.println("s1=" + s1);
    System.out.println("substring=" + substring);
}

输出结果:
s1=helloworld
replace=hellgwgrld
s1=helloworld
substring=hello

可见,对String变量进行任何修改都不会改变原来变量的值。

点开 String 的源码可以看到:

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

String 是一个被 final 修饰的类,这表示它是不能被继承,但是 String 的不可变性并不是指的这个,而是其中的一个成员属性:private final char value[]; 其实 String 底层是用 char 数组实现的(这点和 ArrayList 类似),这个char数组是被 final 修饰,也就是说它是不可以被修改的。所以,当对 String 进行修改时,必须重新新建一个 char 数组。这点也很容易理解,因为使用常量池的好处是,相同的对象只会存储一份,这可以大大节省内存空间,但是多个变量指向同一个常量池中的对象时,其中任何一个变量发生改变都不应该影响其他变量的值,所以只能重新去创建一个对象。

我们平时比较字符串相等时,一般都是使用 String 类中的 equals() ,下面是它的源码,可以看出,它是先去比较两个变量的地址值是否相等,然后再去判断类型是否是 String 类型,如果是 String 类型就通过遍历挨个比较每个char字符是否相同,否则返回false。

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

总结:String 其实是 Java中一个普通的类,但是它有一些特殊的地方,主要需要理解的是使用不同方式创建字符串时,JVM是如何分配内存的,另外,要理解 String 的不可变性,其底层是使用一个被 final 修饰的 char 类型的数组存储数据的。

 

参考地址:

本文内容大部分是根据“尚硅谷Java核心基础_2019年版”视频中常量类部分进行的个人总结,非常推荐大家去尚硅谷官网下载相关视频学习,里面的内容非常不错。尚硅谷官网

另一个推荐不错的知乎专栏:https://zhuanlan.zhihu.com/p/27626724 ,里面其他的文章也非常值得学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值