我在java上对字符串概念有以下问题 [英] I have the following question in java on strings concept

查看:61
本文介绍了我在java上对字符串概念有以下问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是代码::

Here is the code::

String x="a";
    String xy=x+"b";
    String ab="ab";





因为字符串被分配了字符串文字并且可以在字符串常量中创建游泳池。



As the strings got assigned with string literals and can be created in the string constant pool.

String x="a";  // "a" will be created in the constant pool referenced by x
    String xy=x+"b"; // this will be computed in Runtime and created in the constant pool with value as ab referenced by xy
    String ab="ab";  //this will be created in the constant pool referenced by ab





引用的常量池中创建,但在执行System.out.println时(xy == ab)它返回为false。

因为它们(ab)都是在字符串常量池中创建的,而后者又应该返回true.Am我什么都错过了?



我尝试了什么:



我的理解是,当要创建一个字符串时,它应该是go并首先检查字符串常量池,如果不存在,它将创建字符串,否则它将给出现有字符串的引用。



but while executing System.out.println(xy==ab) it is returning as false.
As both of them("ab") are created in the string constant pool which in turn should return true.Am i missing anything?

What I have tried:

my understanding is that when ever a string is to be created it should go and first check in the string constant pool if not exists it will create the string else it will give the reference of the existing string.

推荐答案

引用:

字符串xy = x +b; //这将在运行时计算并在常量池中创建,其值为xy引用的ab

String xy=x+"b"; // this will be computed in Runtime and created in the constant pool with value as ab referenced by xy

上述注释不正确。连接运算符创建一个新的字符串对象。

The above remark is incorrect. The concatenation operator creates a new string object.


Quote:

注意:String类是不可变的,这样一旦创建它就无法更改String对象。 String类有许多方法,其中一些将在下面讨论,它们似乎可以修改字符串。由于字符串是不可变的,这些方法实际上做的是创建并返回一个包含操作结果的新字符串。

Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.

- 字符串(The Java™Tutorials) [ ^ ] => xy和ab是两个不同的字符串对象。

接下来,

==检查引用相等性(指向同一对象) [ ^ ] => ab == xy返回false。

对于值相等检查,请转到

-- Strings (The Java™ Tutorials)[^] => xy and ab are of two different string objects.
Next,
== checks for reference equality (pointing to the same object)[^] => ab==xy returns false.
For value equality check, go for

.equals()


这篇关于我在java上对字符串概念有以下问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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