string.toUppercase() 在堆或字符串池中创建了一个新对象 [英] string.toUppercase() created a new object in heap or string pool

查看:20
本文介绍了string.toUppercase() 在堆或字符串池中创建了一个新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们使用String类的toUpperCase()方法,是不是把对象放在堆中,而不是在String池中创建.下面是代码,当我运行时,我可以推断出新创建的字符串对象不在字符串池中.

If we use toUpperCase() method of String class, does it put the object in the heap rather than creating it in the String pool. Below is the code, when I ran, I could infer that newly created string objects are not in String pool.

public class Question {
    public static void main(String[] args) {
        String s1="abc";
        System.out.println(s1.toUpperCase()==s1.toUpperCase());
    }
}

以上代码的输出返回false.我知道 "==" 和 equals() 的区别,但在这个问题中,我想知道为什么创建的两个字符串不相等.唯一的解释可能是它们不是在 String 池中创建的,而是完全不同的两个对象.

Output of the above code return false. I know about "==" and equals() difference but in this question I am wondering why the two created strings are not equal. The only explanation could be that they are not created in the String pool and are two different objects altogether.

推荐答案

Java 自动实习字符串文字.检查这个 answer,但是当您使用 toUpperCase() 时,它会创建一个新的字符串实例,使用 new String(),这就是为什么两个对象不同的原因.

Java automatically interns String literals. check this answer, but when you use toUpperCase() it creates a new instance of the string, using new String(), that's why both the objects are different.

这篇关于string.toUppercase() 在堆或字符串池中创建了一个新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆