The meaning of string is immutable.

Source: Internet
Author: User

Assume String s = new String ("ni"); String s1 = new String ("hao ");
S = s + s1;
System. out. println (s); the result is nihao. Does s actually change? Java bytecode can be compiled at a glance.

We can see that three variables are generated in total for new. The specific process should be: first, there is a "s" variable in the stack pointing to the "ni" object in the heap...
The "s1" variable in the stack points to the "hao" object in the heap.
When executed to s = s + s1;
The system re-creates a larger array in the heap, and then copies "ni" and "hao" in it, then the "s" in the stack points to the new array...
Immutable means that, instead of modifying the original array "ni", it creates a new larger array for expansion, that is, at this time, the array of "ni" objects still exists in the heap, but the "s" variable does not point to the array "ni", but to the new array, this is the difference between StringBuffered and StringBuffered. The latter is modified on the original array to change the value of the original array. StringBuffered is not copied through a new array, it is extended on the basis of the original array... let the variable point to the original array ....

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.