String s = new String(“hello”);和String s = “hello”;的区别?以及字符串是如何相加的?

本文详细探讨了Java中字符串对象创建的newString()与直接赋值的区别,重点讲解了'=='和equals()的使用场景,以及字符串连接的内存分配原理。通过实例展示了字符串相加时的不同行为,揭示了常量池和变量操作的差异。

思考:

String s = new String(“hello”)和String s = “hello”;的区别?
字符串比较之看程序写结果
字符串拼接之看程序写结果


经过分析我们给出代码:

public class StringDemo3 {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = "hello";

        System.out.println(s1==s2);//false
        System.out.println(s1.equals(s2)); //true
    }
}

 运行结果:

false
true

Process finished with exit code 0


 打开原码:

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 = 
代码 `String s1 = new String("hello");` `String s2 = "hello";` 存在以下区别: #### 1. 对象创建数量 - `String s1 = new String("hello");`:会创建 2(1)个对象。当执行该语句时,会先检查字符串常量池中是否存在 "hello" 这个字符串对象,如果不存在则会在字符串常量池中创建一个 "hello" 对象;然后会在堆内存中创建一个新的 `String` 对象,该对象会复制常量池中 "hello" 的内容。若字符串常量池中已有 "hello" 对象,则只在堆中创建一个新的 `String` 对象[^1][^4][^5]。 - `String s2 = "hello";`:创建 1(0)个对象。执行该语句时,会先在字符串常量池中查找是否存在 "hello" 字符串对象,若存在,则直接将该对象的引用赋值给 `s2`;若不存在,则在字符串常量池中创建 "hello" 对象并将引用赋值给 `s2`[^1][^4][^5]。 #### 2. 内存分配 - `String s1 = new String("hello");`:`s1` 指向堆内存中的 `String` 对象,该对象包含了从字符串常量池中复制过来的 "hello" 内容。 - `String s2 = "hello";`:`s2` 指向字符串常量池中的 "hello" 对象。 #### 3. 比较结果 ```java public class StringComparison { public static void main(String[] args) { String s1 = new String("hello"); String s2 = "hello"; System.out.println(s1 == s2); // false System.out.println(s1.equals(s2)); // true } } ``` - `s1 == s2` 结果为 `false`,因为 `==` 比较的是两个引用是否指向同一个对象,`s1` 指向堆内存中的对象,`s2` 指向字符串常量池中的对象,它们的内存地址不同。 - `s1.equals(s2)` 结果为 `true`,因为 `String` 类重写了 `equals()` 方法,该方法比较的是字符串的内容,`s1` `s2` 的内容都是 "hello"。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liangzai2048

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值