Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Java understand String?

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to understand String in Java". In daily operation, I believe many people have doubts about how to understand String in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to understand String in Java". Next, please follow the editor to study!

"

How many objects are created by the code String s = new String ("abc")? What is the result of the judgment that slots = "abc"? What is the result of s.substring (0Jol 2) .intern () = = "ab"?

Can s.charAt (index) really represent all the corresponding characters?

Is "abc" + "gbn" + s direct string concatenation really slower than using StringBuilder?

"Preface

Nice to meet you.

The feature of the String object in Java is very different from the cUniverse + language, with the emphasis on its immutability. So for the design of service string immutability, a lot of related questions arise: why keep it immutable? How do you store strings at the bottom? How to perform string manipulation for better performance? Wait. In addition, knowledge of character encoding is also very important; after all, it is perfectly normal to use emoij these days.

The content of the article revolves around the focus of immutability:

Analyze the immutability of String objects

The storage principle of constant pool and the principle of intern method

The principle and Optimization of string concatenation

The difference between code unit and code point

Summary

So, let's get started.

Immutability

To understand the immutability of String, we can simply look at a few lines of code:

String string = "abcd"; String string1 = string.replace ("a", "b"); System.out.println (string); System.out.println (string1); output: abcdbbcd

The string.replace ("a", "b") method replaces an in "abcd" with b. From the output, you can see that the original string string has not changed, and the replace method constructs a new string "bbcd" and assigns a value to the string1 variable. This is the immutability of String.

Another example of chestnut: change the last character d of "abcd" to a, and then modify the last character directly in the cUniverse + language; in java, you need to recreate a String object: abca, because "abcd" itself is immutable and cannot be modified.

"

The value of the String object is immutable, and none of the operations change the value of String. Instead, string manipulation is achieved by constructing a new string.

"

It is often difficult to understand why Java is designed in this way, and doesn't it lead to performance degradation? Looking back at our daily use of String, we find that more often than not, we don't modify a string directly, but if we use it once, it is discarded. But next time, most likely, you will use the same String object again. For example, log printing:

Log.d ("MainActivity", string)

We don't need to change the previous "MainActivity", but we use this string frequently. Java designed String to be immutable, precisely to maintain data consistency, so that the same literal amount of String refers to the same object. For example:

String S1 = "hello"; String S2 = "hello"

S1 and S2 refer to the same String object. If the String is variable, then the design cannot be implemented. Therefore, we can reuse the String object we created without having to recreate it.

"

Based on the premise that there are more cases of repeated use of String than changing the scene of String, Java designs String as immutable to maintain data consistency, so that the same literal string can refer to the same String object and reuse the existing String object.

"

Another point is mentioned in the book Java programming ideas. Let's look at the following code first:

Public String allCase (String s) {return string.toUpperCase ();}

The allCase method capitalizes all the incoming String objects and returns the modified string. At this point, the caller's expectation is that the incoming String object is used only as a source of information and does not want to be modified, which is well suited to the immutable nature of String.

"

When using the String object as a parameter, we want to not change the String object itself, and the immutability of String conforms to this.

"Storage principle

Because of the immutable nature of String objects, it is also different from ordinary objects in storage. We all know that objects are created on the heap, and String objects are actually the same, except that they are also stored in constant pools. String objects in the heap area are most likely to be recycled during GC, while String objects in the constant pool are not easily recycled, so the String objects in the constant pool can be reused. In other words, constant pooling is the root cause of the reuse of String objects.

"

The constant pool does not easily garbage collect, so that the String objects in the constant pool can always exist and be reused.

"

There are two ways to create a String object in the usual quantity pool: explicitly using double quotes to construct a string object, and using the intern () method of the String object. These two methods do not necessarily create an object in the constant pool, but if the same object already exists in the constant pool, it will directly return a reference to that object and reuse the String object. Other ways to create String objects are to create String objects in the heap area. Give me a chestnut.

When we use the method of new String () or call an instance method of the String object, such as the string.substring () method, we create a String object in the heap area. When we use double quotes to create a string object, such as String s = "abc", or call the intern () method of the String object, an object is created in the constant pool, as shown in the following figure:

Image.png

Do you remember the question at the beginning of our article?

String s = new String ("abc"), how many objects does this code create? "abc" constructs an object in the constant pool, and the new String () method creates another object in the heap area, so there are two.

The result of slots = "abc" is false. Two different objects, one in the heap and one in the constant pool.

The s.substring (0 2) .intern () = = "ab" intern method builds a String object with a value of "ab" in the constant pool, and the "ab" statement does not build a new String object, but returns an existing String object. So the result is true.

"

Only two methods, explicitly using double quotes to construct a string object and using the intern () method of the String object, create the String object in the constant pool, and the other methods create the object in the heap area. Each time the String object is created in the constant pool, it is checked for the existence of the same String object, and if so, a reference to the object is returned directly without recreating the object.

"

One more problem with the intern method is that the specific logic performed varies from version to version of jdk. Before jdk6, the method area was stored in the immortal memory area and separated from the heap area, so when you create an object in the usual quantity pool, you need to make a deep copy, that is, copy an object completely and create a new object, as shown below:

Image.png

Observe this code:

String s = new String (new char [] {'a'}); s.intern (); System.out.println (slots = "a")

Before jdk6, two different objects are created, and the output is false;, but after jdk7, no new object is created in the constant pool, referencing the same object, so the output is true.

"

Jdk6 used intern to create deep copies of objects, while shallow copies were used after jdk7, allowing reuse of String objects in the heap area.

"

From the above analysis, String really reuses strings when creating strings directly using double quotes. Using the intern method, you can return a string reference in the constant pool, but you already need a String object in the heap area. Therefore, we can draw a conclusion:

"

Try to use double quotes to explicitly build a string; if a string needs to be reused frequently, you can call the intern method to store it in a constant pool.

"string concatenation

There is no more string operation than string concatenation. Because of the immutability of String objects, it will affect performance too much if you need to create a new string object for each concatenation. As a result, two classes have been officially launched: StringBuffer and StringBuilder. These two classes can assemble and modify strings without creating a new String object. The code is as follows:

StringBuilder stringBuilder = new StringBuilder ("abc"); stringBuilder.append ("p") .append (new char [] {'q'}) .deleteCharAt (2) .insert (2, "abc"); String s = stringBuilder.toString ()

Stitching, insertion, and deletion can all be done very quickly. Therefore, it is more efficient to initialize strings using StringBuilder for operations such as modification, splicing, and so on. The interfaces of StringBuffer and StringBuilder are the same, but StringBuffer adds the synchronize keyword to the operation method, which ensures thread safety while paying the corresponding performance price. StringBuilder is more recommended in a single-threaded environment.

"

Using StringBuilder and StringBuffer to initialize strings through concatenation, modification and other operations can improve performance; StringBuilder is more appropriate in a single-threaded environment.

"

In general, we use + to concatenate strings. + after operator overloading in java, it can be used to concatenate strings. The compiler also makes a series of optimizations for +. Observe the following code:

String S1 = "ab" + "cd" + "fg"; String S2 = "hello" + S1 politics object object = new Object (); String S3 = S2 + object

For S1 strings, the compiler optimizes "ab" + "cd" + "fg" directly to "abcdefg", which is equivalent to String S1 = "abcdefg";. This optimization also reduces the consumption caused by splicing. Even more efficient than using StringBuilder.

S2's splicing compiler automatically creates a StringBuilder to build strings. This is equivalent to the following code:

StringBuilder sb = new StringBuilder (); sb.append ("hello"); sb.append (S1); String S2 = sb.toString ()

So does this mean that we don't have to use StringBuilder explicitly, and the compiler will help us optimize anyway? Of course not. Look at the following code:

String s = "a"; for (int item0)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report