String objects can be assigned with “=” or “new”. What is the difference between the two methods?

When you see the title, you may subconsciously think about the difference between the two methods?

Take a look at the demo below, and it will be distinguished naturally

Operation effect:

Let's analyze why this result occurs:

The first thing we need to understand is

Such code may or may not create an object: a noun "string instance pool" will appear here

This noun is very vivid. In this string instance pool, there are many strings, which may contain the string "ABC", so

In this case, the above statement will not create an object, but directly reference the string in the pool: "ABC";

If the string "ABC" does not exist in the instance pool, then a string "ABC" will be initialized, that is, the instance pool will be created

A string object: "ABC", and the created string will be put into the "string instance pool".

For the keyword: new, a new object will be generated, that is, a new string object will be generated every time

Thus, for the first result:

We knew it. It turned out to be so.

For the second result:

As long as we have an impression of "string instance pool", it is not difficult to understand.

Finally, the third result:

This is a little more difficult to understand.

The strings teststrd and teststre are both string constants, so they have been determined at the time of code compilation,

However, for teststrf, its value is a reference to teststrd and teststre, so it will not be determined at compile time. In fact

Teststrf is similar to creating a new object, and then assigning the reference of the created object to teststrf.

So it's reasonable to have a third result

========================================================

More reading,and english is important.

I'm Hongten

大哥哥大姐姐,觉得有用打赏点哦!多多少少没关系,一分也是对我的支持和鼓励。谢谢。Hongten博客排名在100名以内。粉丝过千。Hongten出品,必是精品。

E | hongtenzone@foxmail.com B |

========================================================

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>