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 to use string three Musketeers String, StringBuffer, StringBuilder

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to use string three Musketeers String, StringBuffer, StringBuilder", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to use string three Musketeers String, StringBuffer, StringBuilder"!

The mental map of the full text is as follows:

1. The head of the three Musketeers: the immutable String

Overview

Java does not have a built-in string type, but instead provides a "predefined class" String in the standard Java class library. Each string enclosed in double quotes is an instance of the String class:

String e = ""; / / empty string String str = "hello"

Take a look at the source code of String, "in Java 8, String internally uses an char array to store data."

Public final class String implements java.io.Serializable, Comparable, CharSequence {/ * * The value is used for character storage. * / private final char value [];}

As you can see, the String class is decorated with final, so "the String class is not allowed to be inherited".

"after Java 9, the implementation of the String class uses the byte array to store strings," while using coder to identify which encoding is used.

Public final class String implements java.io.Serializable, Comparable, CharSequence {/ * * The value is used for character storage. * / private final byte [] value; / * * The identifier of the encoding used to encode the bytes in {@ code value} * / private final byte coder;}

However, whether it is Java 8 or Java 9, "the char or byte array value used to store data has always been declared final," which means that the value array cannot be referenced after initialization. And there is no way to change the value array within String, so we say that String is immutable.

The so-called immutable, just as the number 3 is always the number 3 -, the string "hello" always contains a sequence of code units of the characters h, e, 1, 1 and o, and cannot modify any of them. Of course, you can modify the string variable str to refer to another string, just as you can change the numeric variable that holds 3 to store 4.

Let's look at an example:

String str = "asdf"; String x = str.toUpperCase ()

ToUpperCase is used to convert all strings to uppercase characters, and into the source code of toUpperCase, we find that this method, which appears to modify the String value, actually ends up creating a completely new String object, while the original String object remains intact.

Empty string and Null

The empty string "" is easy to understand, which is a string of length 0. You can call the following code to check whether a string is empty:

If (str.length () = = 0) {/ / todo}

Or

If (str.equals (")) {/ / todo}

An empty string is a Java object with its own string length (0) and content (empty), that is, the value array is empty.

The String variable can also hold a special value called null, which means that "there are currently no objects associated with this variable." To check whether a string is null, you can judge as follows:

If (str = = null) {/ / todo}

Sometimes to check that a string is neither null nor empty, you need to use the following conditions:

If (str! = null & & str.length ()! = 0) {/ / todo}

Some students will feel that such a simple condition judgment still need you to say? Yes, this is simple, but there is still a small hole, that is, we "must first check whether str is null, because if a method is called on a null value, the compiler will report an error."

String concatenation

Now that String is immutable, let's look at a piece of code. Why has the string a changed here?

String a = "hello"; String b = "world"; a = a + b; / / a = "helloworld"

In fact, when using + for string concatenation, JVM initializes a StringBuilder for concatenation. The compiled code is as follows:

String a = "hello"; String b = "world"; StringBuilder builder = new StringBuilder (); builder.append (a); builder.append (b); a = builder.toString ()

StringBuilder will be explained in more detail below, now you only need to know that StringBuilder is a variable string type on OK. Let's look at the source code of builder.toString ():

Obviously, the toString method also generates a new String object, rather than making changes to the contents of the old string, which is equivalent to pointing a reference to the old string to the new String object. This is why the string a has changed.

In addition, we need to understand a feature that when a string is concatenated with a non-string value, the latter is automatically converted to a string ("any Java object can be converted to a string"). For example:

Int age = 13; String rating = "PG" + age; / / rating = "PG13"

This feature is commonly used in output statements. For example:

Int a = 12; System.out.println ("a =" + a)

Combined with the above two features, let's look at a small question, "what is the result of the splicing of empty strings and null?"

String str = null; str = str + ""; System.out.println (str)

The answer is null, which everyone can guess, but why null? As mentioned above, stitching with + is actually converted to StringBuilder and stitched using the append method. The compiled code is as follows:

String str = null;str = str + ""; StringBuilder builder = new StringBuilder (); builder.append (str); builder.append (""); str = builder.toString ()

Take a look at the append source code:

As you can see, when the string passed in is null, the appendNull method is called, and this method returns null.

Detect whether the string is equal

You can use the equals method to detect whether two strings are equal. For example:

String str = "hello"; System.out.println ("hello" .equals (str)); / / true

Equals is actually a method in the Object class, and all classes inherit from the Object class. Before we talk about the equals method, let's review the use of the operator = =, which has two uses:

For basic data types, = = compares whether the values are the same

For reference data types, = = compares whether the memory address is the same.

For example:

String str1 = new String ("hello"); String str2 = new String ("hello"); System.out.println (str1 = = str2); / / false

If you still don't understand the data storage area in Java, you can go back to the first chapter, "everything is an object." For the above code, str1 and str2 use the constructor new String () to create two different strings, with String str1 = new String ("hello"); for example, the object from new is stored in heap memory, pointing to the object's address with a reference str1, while the object's reference str1 is stored in stack memory. Str1 and str2 are two different objects with different addresses, so the result of the = = comparison is false.

In fact, the original equals method in the Object class calls the operator = =, which "determines whether two objects have the same reference (address), and the effect is the same as = =":

That is, if your new class does not override the equals method, then this method compares the address of the object. The String method overrides the equals method, so let's take a look at the source code:

As you can see, the equals method overridden by String compares the contents of the object, not the address.

Summarize the two uses of equals ():

Case 1: the class does not override the equals () method. Then comparing two objects of this class through equals () is equivalent to comparing the two objects through = = (comparing addresses).

Case 2: the class overrides the equals () method. In general, we all override the equals () method to determine whether the contents of two objects are equal, as the String class does. Of course, you don't have to do this.

For example:

String a = new String ("ab"); / an is a string reference String b = new String ("ab"); / / b is another string reference, and the contents of these two objects are the same if (a.equals (b)) / / true System.out.println ("aEQb"); if (aEQb) / / false, not the same object with different System.out.println addresses ("aEQb")

String constant pool

Since the string String is a class in Java, like other object allocation, it needs a high cost of time and space. As the most basic and commonly used data type, a large number of frequent creation of strings will greatly affect the performance of the program. To this end, JVM makes some optimizations when instantiating string constants to improve performance and reduce memory overhead:

A "string constant pool String Pool" has been created for strings, which can be understood as a cache area

When you create a string constant, first check whether the string exists in the string constant pool

"if the string exists in the string constant pool, the reference instance is returned directly without re-instantiation"; if it does not exist, the string is instantiated and placed in the pool.

For example:

String str1 = "hello"; String str2 = "hello"; System.out.printl ("str1 = = str2": str1 = = str2) / / true

For the above code, String str1 = "hello";, "the compiler will first create a reference named str1 in the stack, then look for a reference with the value" hello "in the string constant pool, if not, open up an address in the string constant pool to store the string" hello ", and then point the reference str1 to" hello ".

It is important to note that the location of the string constant pool changes in JDK 1.7:

"before JDK 1.7", string constant pool exists in "constant storage" (Constant storage)

After JDK 1.7, the string constant pool exists in heap memory (Heap).

In addition, we "can use the intern () method of String to manually add strings to the String Pool at run time." The specific process is as follows:

When a string calls the intern () method, a reference to the string in String Pool is returned if a string already exists in String Pool that equals the value of that string; otherwise, a new string is added to String Pool and a reference to the new string is returned.

Look at the following example:

String str1 = new String ("hello"); String str3 = str1.intern (); String str4 = str1.intern (); System.out.println (str3 = = str4); / / true

For str3, str1.intern () first checks in String Pool to see if there is already a string equal to the value of str1, no, so it adds a new string equal to str1 in String Pool and returns a reference to the new string.

In the case of str4, str1.intern () finds a string in String Pool that is equal to the value of str1 and returns a reference to that string directly. So S3 and S4 refer to the same string, which means they have the same address, so the result of str3 = = str4 is true.

"Summary:"

String str = "I", which is automatically assigned to the constant pool by the java virtual machine

String str = new String ("I") is allocated to heap memory. You can manually join the constant pool through the intern method.

New String ("hello") creates several string objects

How many string objects are created in the following line of code? Only one is created in the heap?

String str1 = new String ("hello")

Apparently not. For str1, new String ("hello") takes two steps:

First, "hello" belongs to the literal quantity of a string, so the compilation time looks in String Pool for references with the value "hello". If not, it opens up an address space in the pool of string constants to create a string object that points to the literal quantity of the "hello" string.

Then, using new creates a string object in the heap.

Therefore, using this approach creates a total of two string objects (provided that there is no "hello" string object in String Pool).

two。 Twins: variable StringBuffer and StringBuilder

String string concatenation problem

Sometimes, you need to build a string from a shorter string, such as pressing a key or a word from a file. It is inefficient to use string concatenation to achieve this goal. Because the object contents of the String class are immutable, a new object is always created in memory whenever string concatenation is performed. It not only takes time, but also wastes space. For example:

String s = "Hello"; s + = "World"

This simple code actually produces a total of three strings, namely "Hello", "World" and "HelloWorld". "Hello" and "World" are created in String Pool as string constants, while the splicing operation + new an object to store "HelloWorld".

This problem can be avoided by using the StringBuilder/ StringBuffer class. After all, the underlying + operation of String is implemented by StringBuilder. StringBuilder and StringBuffer have the same parent class:

However, StringBuilder is not thread-safe, and data inconsistency will occur when using it in a multithreaded environment, while StringBuffer is thread-safe. This is because the common methods within the StringBuffer class use the synchronized keyword for synchronization, so it is thread-safe. And StringBuilder didn't. This is also the reason why the running speed StringBuilder is greater than StringBuffer. Therefore, if you are in a single thread, priority is given to using StringBuilder.

Initialization operation

The API of the two classes StringBuilder and StringBuffer are the same, so take StringBuilder as an example to demonstrate its initialization operation.

StringBuiler/StringBuffer cannot be assigned directly as a string as String does, so it cannot be initialized that way. It "needs to be initialized by constructor". First, build an empty string builder:

StringBuilder builder = new StringBuilder ()

Each time you need to add a piece of content, call the append method:

Char ch = 'ert; builder.append (ch); String str = "ert" builder.append (str)

When you call the toString method when you need to build the string String, you get a String object:

String mystr = builder.toString (); / / aert

3. Comparison of String, StringBuffer and StringBuilder

Mutable thread safety String immutable because it is immutable, it is thread safe StringBuffer variable thread safe, because most of its internal methods use synchronized for synchronization. Its inefficiency StringBuilder variable is not thread-safe because synchronized is not used for synchronization, which is why it is more efficient than StringBuffer. In single-threading, StringBuilder is preferred. At this point, I believe you have a deeper understanding of "how to use string three Musketeers String, StringBuffer, StringBuilder". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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