Java-11.1 unchanged strings

Source: Internet
Author: User

Java-11.1 unchanged strings

In this section, we will discuss the unchanged strings.

Why is it unchanged?

Let's first look at the String constructor.

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


Here, let's look at the value:

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


The identifier of value is final. Therefore, the character string cannot be modified in the same 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 conversion process, the string object "a" is actually copied and then converted.

We can click in the toUpperCase method, which has two notes:

 

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

And

 

 

 

return new String(0, count+resultOffset, result);

The first sentence is to copy the input value, and the second sentence is in the last new string.

 

 

 

Then, you can search for return new String in the source code of the String class. You will find that the methods you commonly use basically return a new String.

 

Summary: here we simply end the unmodifiable features of the string. In fact, it contains a lot of content, but it is not detailed for the time being. We know that this feature is available.

 

 

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.