Java 如果我们使用新字符串(“abcd”)是否在堆中创建字符串对象
若字符串对象是在堆中创建的,那个么两者都是false。但它给出false,trueJava 如果我们使用新字符串(“abcd”)是否在堆中创建字符串对象,java,Java,若字符串对象是在堆中创建的,那个么两者都是false。但它给出false,true String s1 = new String("anil"); String s2 = s1.toUpperCase(); String s3 = s1.toLowerCase(); System.out.println(s1 == s2); System.out.println(s1 == s3); 此语句创建一个新对象 而这个, String s1 = new Str
String s1 = new String("anil");
String s2 = s1.toUpperCase();
String s3 = s1.toLowerCase();
System.out.println(s1 == s2);
System.out.println(s1 == s3);
此语句创建一个新对象
而这个,
String s1 = new String("anil");
指向第一个对象的位置,即s1
这就是第二个条件得到true
的原因
也要看清楚
希望这有帮助 这里有四个字符串对象:
- 由编译器和类加载器创建的文本
- s1,由新字符串()创建
- s2,由toUpperCase()创建
- s3,由toLowerCase()创建
除了toLowerCase()可能返回相同的对象(如果它已经是小写的)。Javadoc中没有这方面的内容,因此实现中的任何此类行为都不能依赖。这里S1对象将在heap中创建。其值存储在常量字符串池中 S2是字符串文字而不是对象。因此,第一个JVM将检查常量池中是否存在该字符串。若字符串在常量池中,它将不会创建新对象。它将返回可用对象的引用 这里s1.toUpper将返回“ANIL”。“ANIL”不在常量池中。因此将创建新对象。并将其与s1(使用“==”)进行比较,得出false S3也是如此。但对于S3,它不会创建新对象,因为“anil”已经存在于常量池中。 so将返回S1的引用。所以这是真的 研究以下链接
如果您查看String类中的toLowerCase()方法
toLowerCase(Locale)
toLowerCase(Locale)
inturn使用Character.toLowerCase(c)
字符。字符类中的toLowerCase(c)
有以下注释-
- @param ch要转换的字符
- @返回该字符的小写等效字符(如果有)李>
- 否则,角色本身
大小写1:带
大写首字母的字符串
String s3 = s1.toLowerCase();
> String s1 = new String("Ajay")
String s2 = s1.toUpperCase()
String s3 = s1.toLowerCase()
System.out.println s1 == s2
System.out.println s1 == s3
false
false
大小写2:带小首字母的字符串
String s3 = s1.toLowerCase();
> String s1 = new String("Ajay")
String s2 = s1.toUpperCase()
String s3 = s1.toLowerCase()
System.out.println s1 == s2
System.out.println s1 == s3
false
false
在案例1中,由于字符串具有大写字母,转换为小写将生成一个新对象,因此为其创建一个新引用,而在案例2中转换为小写后,小首字母仍将指向同一对象,因为原始对象相同,因此为同一对象创建两个引用
您可以非常清楚地看到
groovyshell的输出。s3将指向与s1相同的字符串。这是真的。检查toLowerCase()的实现@没有为toLowerCase()指定这样的行为,因此不能依赖它。@EJP-请检查我的更新答案。+1。。因为如果没有大写字符,toLowerCase将返回相同的字符串。@注释中的WhoAmI+1应添加到应答中。这段代码可以帮助您如何操作?这是什么?@EJP-我的错。我已经编辑了我的答案。上面的代码让我认为,如果char已经是小写的,String的toLowercase()将不会起任何作用。