Understanding java-11.1 immutable strings from the beginning

Source: Internet
Author: User

In this chapter we will discuss the invariant string.

Why is that not the same?

Let's look at the constructor of string first.

Public String () {this.offset = 0;this.count = 0;this.value = new char[0];    }


Inside of the value, let's look at it again:

/** The value is used for character storage. */    Private final char value[];


The identifier for value is final, so the string cannot be modified in-place in the compiler.

Package Com.ray.ch11;public class Test {public static void main (string[] args) {String a = "a"; String B = a.touppercase (); System.out.println (A = = B);}}

Output:

False

In the process of conversion, it is actually a copy of the string object "a", and then the conversion.

We can go in there. toUpperCase method inside, there are two sentences to note:

  System.arraycopy (value, offset, result, 0, firstupper);

And

return new String (0, Count+resultoffset, result);

The first sentence is to copy the value passed in, and then the second sentence comes out in the last new string.


You can then search for the return new string in the source code of the string class, and you will find that the methods you use most often return a new string.


Summary: We are simply the end of a string of non-modifiable features, in fact, it also contains a lot of content, but temporarily do not do detailed deployment, we know that this feature can be.


This chapter is here, thank you.

-----------------------------------

Directory


Understanding java-11.1 immutable strings from the beginning

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.