String It can be said that it is Java Most frequently used in , The most special class , Because it's also a literal constant , Literal constants include basic types ,String type , Null type .

<> One . String Use of

<>1. String The immutability of
/** * The {@code String} class represents character strings. All * string
literals in Java programs, such as {@code "abc"}, are * implemented as
instances of this class. * <p> * Strings are constant; their values cannot be
changed after they * are created. String buffers support mutable strings. *
Because String objects are immutable they can be shared. For example: * ... */
public final class String { private final char value[]; }
String Once the object is created in the heap , You can't modify it . because String Object in char Array , The array consists of final Keyword modification , Immutable .

<>2. Define a string
/** * Define a string */ String str1 = "helloworld"; String str2 = "helloworld";
// it's fine too , But it is not written in this way String str3 = new String("helloworld"); System.out.println(str1
== str2); System.out.println(str1 == str3); // Operation results true, false
How to understand the above three codes ? Here we need to introduce a concept first , String constant pool .

String constant pool is a special independent memory space , Put in Java Heap in { stay Jdk7.0 The string constant pool was stored in the PermGen in ,Jdk7.0 Time to move to Java
Heap( It is still independent in the heap ),Jdk8.0 It was removed at the time PermGen, use Metaspace Replace } ,Java The memory model is not the focus of this chapter .

str1 and str2 The literal of the string referenced is in the string constant pool , and str3 Referenced object in Java Heap in .

Yes? , It's not very easy to understand ? for instance

Work one day , It's time to get off work , Ready to see the Golden Vase . forget it ,《 Romance of the Three Kingdoms 》, Open novel website , Online reading ; Half an hour later , Female ticket home , see 《 Romance of the Three Kingdoms 》 It's what she wants to do , I read the website and send it to her , good , She started to watch, too , In half an hour , My dad's back , He is also a fan of the Three Kingdoms , But he doesn't like watching online , So I bought a book in the bookstore .

The novel website mentioned above is a string constant pool , Contains a lot of string literals , as 《 Romance of the Three Kingdoms 》,《 Journey to the West 》,《 The Dream of Red Mansion 》 etc. , Each string literal remains unique in the constant pool , No matter who enters the website to see 《 Romance of the Three Kingdoms 》 It's the same URL and the same content .

I'm with the female ticket str1 and str2, We're all looking at the same website 《 Romance of the Three Kingdoms 》, Not only the content is the same , The same is true of the address quoted ( A unique string constant pool is reserved “helloworld”), therefore str1
== str2 The running result is true

And my dad was str3, It's not the same as me and the female ticket , Although the content is also 《 Romance of the Three Kingdoms 》, But from the perspective of physical books , The reference address is different , One book does not support reading by multiple people at the same time ( String object in java
heap in , And every time new A new object will be created ), therefore str1 == str3 The running result is false.

A string literal is always referenced String The same instance of the class , Because of being String.intern() The method defines , Similarly, we can call this method to change the String Object into the string constant pool , This can improve memory efficiency , At the same time, users can share unique instances .
System.out.println(str1 == str3.intern()); // The running result is true
What is the implementation logic of this method , Let's take a look at the source code
/** * Returns a canonical representation for the string object. * <p> * A pool
of strings, initially empty, is maintained privately by the * class {@code
String}. * <p> * When the intern method is invoked, if the pool already
contains a * string equal to this {@code String} object as determined by * the
{@link #equals(Object)} method, then the string from the pool is * returned.
Otherwise, this {@code String} object is added to the * pool and a reference to
this {@code String} object is returned. * <p> * It follows that for any two
strings {@code s} and {@code t}, * {@code s.intern() == t.intern()} is {@code
true} * if and only if {@code s.equals(t)} is {@code true}. * <p> * All literal
strings and string-valued constant expressions are * interned. String literals
are defined in section 3.10.5 of the * <cite>The Java™ Language
Specification</cite>. * * @return a string that has the same contents as this
string, but is * guaranteed to be from a pool of unique strings. */ public
native String intern();
We found that this is a native method , Take a look at the notes , find str3.intern() The general process of the method is as follows :

When implemented intern() Time , Whether the string constant pool contains the same ( adopt equals method ) String literal for , If there is a direct return string literal ; If not , The string object is added to the string constant pool , At the same time, it returns the reference of the object in the string constant pool .

The returned reference must be assigned a value , Otherwise, it still points to the address in the heap , Namely :
String str4 = new String("helloChina"); System.out.println(str4.intern() ==
str4);//false str4 = str4.intern(); String str5 = "helloChina"; String str6 =
"helloZhonghua" System.out.println(str4 == str5);//true
Let's take a look at the memory structure

<>3. Assign to the defined string again
str6 = "helloHuaxia";
We already said that at the beginning String By final Keyword modification , Immutable , So how to reflect it in memory at this time ?

<>4. String Yes “+” Treatment of
String str7 = "good good" + " study"; String str8 = "good good study";
system.out.println(str7 == str8);
After compiling the tool, the
String str7 = "good good study"; String str8 = "good good study";
Therefore, we can find that the compiler does variable merging during compilation , Instead of creating three objects in the constant pool “good good”,“ study”,“good good
study”.str7 == str8 Operation results true.

But if so
String str9 = "good good "; String str10 = str9 + "study";
system.out.println(str8 == str10);//false
At this time, the running result is false, adopt String variable +
The result of character constant mode will be in the heap , Not in constant pool , Yes, of course intern() Method into the constant pool , At the same time, not only “+” such , call substring(),toUpperCase(),trim() All of them are coming back String Address in heap .

<>5. String Common methods
//str1 == "hello,world "; // Get length str1.length()//12;
// Intercept position 2 reach 5 Between the string ( Including location 2, Location is not included 5, from 0 start ) str1.substring(2,5);//"llo"
// Determine whether the string contains “ello” str1.contains("ello");//true, adopt indexOf realization // obtain ello stay str1 Start position in
str1.indexOf("ello");//1 // Convert string to string data str1.split(",");//["hello","world"]
// Remove the spaces on both sides of the string str1.trim();//"hello,world"
<> Two . summary

This paper starts from String The immutability of ,String Literal and String Different objects , String literal constant pool , Memory structure of strings , frequently-used String Description of related methods , If there's something wrong , Please criticize and correct , Hope for common progress , thank you !

©2019-2020 Toolsou All rights reserved,
c Language to achieve mine clearance Games and mine source code Node.js Middle template engine 3 species Python data structure ,13 Creation methods , This is the conclusion , Great ! The situation of receiving and receiving multi-path git It's set correctly ssh, But it still prompts Permission denied (publickey) new iPhone I won't support it 5G Will lead to further decline in shipment C# Sorting method of Chinese Dictionaries 10909 rice ! Chinese fighter successfully landed in Mariana Trench MySQL8.0MGR Single owner / Multi master installation and switching Java Poor reflection performance ?