Java Basics (C) String depth analysis

String in Java can be said that the most used most frequently, most special class, but also because the literal, and literal, including basic types, String type, air type.

A. String of use

1. String 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[];
}

Once a String object is created out of the heap, it can not be modified. Because String objects in the char array, the array is modified by the final keyword, immutable.

2. Define a string

/**
 * 定义一个字符串
 */
String str1 = "helloworld";
String str2 = "helloworld";
//也可以,但基本不这样写
String str3 = new String("helloworld");
System.out.println(str1 == str2);
System.out.println(str1 == str3);

//运行结果 true, false

The above three codes how to understand it? We should first introduce a concept, a string constant pool .

String constant pool is a special independent memory space on the Java Heap before Jdk7.0 in {string constant pool is stored in the PermGen, Jdk7.0 when moving to Java Heap (heap remain separate) , Jdk8.0 when removed PermGen, substitution} with Metaspace, focused on Java memory model is not discussed in this chapter.

Literal strings str1 and str2 cited in a string constant pool, and the object referenced in the Java Heap str3 in.

How, is not very good understanding? for example

Day's work, to working hours, and ready to watch while gold bottle, well, "Three Kingdoms", open the novel site, reading online;. After half an hour, the female vote to go home, see "Three Kingdoms" is her wish thing to do, I see URL sent to her, well, she began to read, another half an hour, my dad came back, he is also a fan of the three countries, but he did not like to see online, so the bookstore to buy a watch .

Novel site mentioned above is a string constant pool contains a lot of string literal, such as "Three Kingdoms", "Journey to the West", "Dream of Red Mansions" and so on, each string literal remain only in the constant pool copies, regardless of who enter the site to see "Three Kingdoms" is the same URL and the same content.

I and female ticket is str1 and str2, we are looking at the same site of the "Three Kingdoms", not only the same content, same address reference (string constant pool retains only "helloworld"), and therefore str1 = = str2 run to true

And my dad is str3, with my ticket and women are not the same, although the look of the content is "Three Kingdoms", but through the physical book point of view, the reference address is not the same, while a book does not support more than one person while watching (string in java heap object, and each new will create a new object), so str1 == str3 operation result is false.

A string literal always refers to the same instance of the String class, it is limited because the String.intern () method, the same we can call this method String object heap into a string constant pool, doing so can improve memory usage efficiency, while allowing users to share used only instance.

System.out.println(str1 == str3.intern());
//运行结果为true

Then implement the logic of this method is kind of how we 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&trade; 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 this to be a native method, look at the comments and found str3.intern () method is a general process:

When performing Intern (), first it determines whether the string constant pool contain the same (by the method equals) the literal string, if there is a direct return string literal; if free, the String object to add string constant pool, and returns the string object reference in the constant pool.

References required assignment before returning, or otherwise address will point to 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

Here we look at the structure of memory
Here Insert Picture Description

3. reassigned to the string already defined

str6 = "helloHuaxia";

We started already said String is modified by the final keyword, immutable, so at this time how to reflect it in memory?
Here Insert Picture Description

4. String processing of "+"

String str7 = "good good" + " study";
String str8 = "good good study";
system.out.println(str7 == str8);

Tools are compiled by

String str7 = "good good study";
String str8 = "good good study";

So we can see that the compiler during compilation is to be variable merger does not create three objects "good good", "study", "good good study" in the constant pool. str7 == str8 operating results true.

But if this

String str9 = "good good ";
String str10 = str9 + "study";
system.out.println(str8 == str10);//false

Then run the result is false, the result obtained by the String variable + character constants way will the heap, not the constant pool, of course, can be put into the constant pool by intern () method, while only "+" So, call substring ( ), toUpperCase (), trim (), etc. are returned in address String heap.

5. String commonly used method

//str1 == "hello,world ";

//获取长度
str1.length()//12;

//截取位置2到5之间的字符串(包括位置2,不包括位置5,从0开始)
str1.substring(2,5);//"llo"

//判断是否含有字符串“ello”
str1.contains("ello");//true,通过indexOf实现

//获取ello在str1中的开始位置
str1.indexOf("ello");//1

//将字符串转化为字符串数据
str1.split(",");//["hello","world"]

//去掉字符串两侧空格
str1.trim();//"hello,world"

II. Summary

From the immutability of String, different, string literal constant pool, a string of memory structure, described herein is created when String literals and the String object String commonly associated methods, if imperfect, please criticism and hope common progress, thank you!

Guess you like

Origin blog.csdn.net/fengdongsuixin/article/details/93306868