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 understand the String of Java

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "how to understand the String of Java". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Characteristics of 1.String

1.1 invariance

We often hear that HashMap's key recommends using immutable classes such as String. Immutable here means that once the class value is initialized, it can no longer be changed. If it is modified, it will be a new class. Let's write a demo to demonstrate it.

Public class test {public static void main (String [] args) {String str= "hello"; str=str+ "world";}}

From the code point of view, the value of s seems to have been modified, but from the debug log, in fact, the memory address of s has been modified, that is to say, the seemingly simple assignment s = "world". In fact, the reference to s has been pointed to the new String,debug screenshot to show that the memory address has been modified. The two screenshots are shown below, and we can see that the address value of the standard red has been modified.

Use a diagram to represent heap memory, as shown in the following figure.

We can see that the address of str has been changed, saying that two strings have been generated, and the official comment of the String class is Strings are constant; their values cannot be changed after they are created. Strings are constant in simple translation; their values cannot be changed after creation.

The following is the relevant code for String. The following code can be seen:

1. String is modified by final, which means that the String class can never be inherited, that is, any operation method on String will not be inherited and overridden, which ensures the parent delegation mechanism and the security of the base class.

2. The value that holds the data in String is an array of char. We found that value is also modified by final, that is, once value is assigned, the memory address can never be modified, and the permission of value is private, and there is absolutely no external access, and String does not open a method to assign values to value, so once value is generated, the memory address cannot be modified at all.

/ / final array of type char private final char value []; / / hash value private int hash; private static final long serialVersionUID =-6849794470754667710L

1.2 Equality judgment

Equality judgment logic is very clear, if someone asks how to judge whether the two are equal, we can start from the underlying structure of the two, so we can quickly think of a practical idea and method, just as the underlying data structure of String is an array of char, when judging equality, we can compare whether the characters in the char array are equal one by one. (dig a hole here first, Ctrip asked a similar question)

Public boolean equals (Object anObject) {/ / if the address is equal, return true if directly (this = = anObject) {return true } / / if it is a String string, then make the following logic judgment if (anObject instanceof String) {/ / convert the object to String String anotherString = (String) anObject; / / get the length of the current value int n = value.length / / first compare whether the lengths are equal. If the lengths are not equal, the two must not be equal if (n = = anotherString.value.length) {char v1 [] = value; char v2 [] = anotherString.value; int I = 0 / / the while loop compares each char while (nmura -! = 0) {if (v1 [I]! = v2 [I]) return false; iTunes + } return true;}} return false;}

The flow chart of the equality logic is as follows, and we can see that the whole process is very clear.

1.3 replace operation

Replacement is also often used in daily work. There are mainly three scenarios: replace replacing all characters, replaceAll replacing strings in batches, and replaceFirst.

A demo is written below to demonstrate three scenarios:

Public static void main (String [] args) {String str = "hello word!!"; System.out.println ("before replacement:" + str); str = str.replace ('lumped,' d'); System.out.println ("replace all characters:" + str); str = str.replaceAll ("d", "l") System.out.println ("replace all:" + str); str = str.replaceFirst ("l", "); System.out.println (" replace the first l: "+ str);}

The result of the output is:

One thing to note here is the difference between replace and replaceAll, not all the differences between replacement and replacement.

Instead, replaceAll supports regular expressions, so parameters are parsed (both parameters are), such as replaceAll ("\\ d", "*"), while replace does not. Replace ("\\ d", "*") is a string that replaces "\ d" and does not resolve to regular.

1.4 intern method

String.intern () is a Native method, that is, the code for c and C++ to interact with the underlying layer, and its purpose (unlike in JDK1.6 and 1.7) is:

If the runtime pool already contains a string equal to the contents of this String object, a reference to the string in the constant pool is returned directly

If not, in jdk1.6, add the String object to the constant pool, and then return a reference to the String object (where the referenced string is in the constant pool).

In jdk1.7, put a reference to the address of the String object in the heap and return the reference address (where the referenced string is in the heap).

Public native String intern ()

If you don't understand the above, let's take a look at the specific examples and analyze them.

Public static void main (String [] args) {String S1 = new String ("learning Java's little sister"); s1.intern (); String S2 = "learning Java's little sister"; System.out.println (S1 = = S2); String S3 = new String ("learning Java's little sister") + new String ("test"); s3.intern () String S4 = "learn Java's little sister test"; System.out.println (S3 = = S4);}

Let's take a look at the results. The actual printed information is as follows.

Why do you show such a result? let's take a look. So in the jdk7 version, the string constant pool has been moved from the method area to the normal heap area.

The first false: the first sentence code String S1 = new String ("learning Java's little sister"); two objects are generated. The "learn Java's little sister" in the constant pool and the string object in the heap. S1.intern (): after looking for S1 object in the constant pool, we found that "the little sister learning Java" is already in the constant pool. Next String S2 = "learn Java's Little Sister"; this code generates a reference to S2 pointing to the "learn Java's Little Sister" object in the constant pool. The result is that the reference addresses of s and S2 are significantly different, so the print result is false.

The second true: look at the S3 and S4 strings first. String S3 = new String ("learning Java's little sister") + new String ("test");, this code now generates three objects, which are the objects pointed to by "learning Java's little sister" in the string constant pool, "test", and the S3 reference in the heap. At this time, the content of the S3 reference object is "learn Java's Little Sister test", but there is no "Learning Java's Little Sister test" object in the constant pool, then s3.intern () This code is to put the string "learn Java's little sister test" in S3 into the String constant pool, because the "learn Java's little sister test" string does not exist in the constant pool at this time, the constant pool does not need to store an object, you can directly store references in the heap. This reference points to the object referenced by S3. In other words, the reference address is the same. Finally, String S4 = "learn Java's Little Sister test"; in this code, "learn Java's Little Sister test" is declared, so it will be created directly in the constant pool. When you create it, you will find that this object already exists, which is a reference to the S3 reference object. So the S4 reference points to the same as S3. So the final comparison S3 = = S4 is true.

Let's see if the print results are different if we reposition the above two lines of code.

Public static void main (String [] args) {String S1 = new String ("Little Sister learning Java"); String S2 = "Little Sister learning Java"; s1.intern (); System.out.println (S1 = = S2); String S3 = new String ("Little Sister learning Java") + new String ("test"); String S4 = "Little Sister test learning Java" S3.intern (); System.out.println (S3 = = S4);}

In the first false: S1 and S2 code, s1.intern ();, it doesn't matter if you put this sentence back, because the first line of code String s = new String ("learning Java's little sister") is executed in the object pool, and the "little sister learning Java" object has been generated. The following S2 declarations take address references directly from the constant pool. The reference addresses of s and S2 will not be equal.

The only difference between the second false and the above is s3.intern (); the order is put in String S4 = "learn Java's little sister test"; later. In this way, first execute String S4 = "learn Java's Little Sister test"; declare S4 when there is no "Learning Java's Little Sister test" object in the constant pool, and after execution, "learn Java's Little Sister test" object is the new object of S4 declaration. When s3.intern (); is then executed, the "learning Java test" object already exists in the constant pool, so the references to S3 and S4 are different.

2. String, StringBuilder and StringBuffer

2.1 inheritance structure

2.2 main differences

1) String is an immutable character sequence, while StringBuilder and StringBuffer are variable character sequences.

2) execution speed StringBuilder > StringBuffer > String.

3) StringBuilder is not thread-safe, StringBuffer is thread-safe.

This is the end of "how to understand the String of Java". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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