In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you the example analysis of String in Java, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Preface
Based on the position of the string String in java, there is no introduction to the common sense knowledge of String. Let's take a look at a piece of code first.
Public class Test {public static void main (String [] args) {String a = "abc"; String b = "abc"; String c = new String ("abc"); System.out.println (astatb); System.out.println (a.equals (b)); System.out.println (astatc); System.out.println (a.equals (c));}}
So what is the result of the previous code? The answer is: true true false true, friends who are beginners to java will surely wonder, why is it false? Why is it all true that equals judges?
According to these questions, we will understand it step by step through the interpretation of String.
Why is the result of astatc false?
To understand this problem, you need to have a certain understanding of the memory structure of JVM, that is, you don't need to know too much, just be able to get to the knowledge points in the following figure.
Ps: all the illustrations in this article are for ease of understanding. If you want to understand more clearly, please study the principle of virtual machine yourself.
The java syntax is designed for String and provides two creation methods and a special storage mechanism (String intern pool).
Two ways to create a string object:
1. The way the literal value is assigned
Create a new string object using the 2.new keyword
There are differences in performance and memory footprint between the two methods.
String Pool string pool: a special space in the memory heap is used to store all String object data. When constructing a new string String object (through literal assignment), the Java compilation mechanism will first find out whether a String object already exists in this pool to meet the needs, and if so, directly return the address reference of the object (if not, construct a new object normally) Throw it in and save it), so that the next time you use the same String, you can take it directly from the string pool without having to create objects again, thus avoiding a lot of unnecessary space overhead.
According to the above concept, let's take a look at the code in the preface. When JVM executes to String a = "abc";, it will first see if there is a string in the constant pool that happens to be the object "abc". If not, create and initialize the object in the constant pool and point the reference to it, as shown in the following figure.
When String b = "abc"; is executed, it is found that the constant pool already has the value of abc, so instead of creating the object in the constant pool, the reference is directed directly to the object, as shown below:
Continue to String c = new String ("abc"). At this time, we add a new keyword, which tells JVM that you open up a new memory for me directly in the heap memory, as shown in the following figure:
At this time, we execute four print statements. We need to know that = = compares the address, equals compares the content (rewritten in String), and the contents of the three variables of abc are exactly the same, so the result of equals is that true,ab is the same object, so the address is the same, so an and c are obviously not the same object, so it is easy to understand false at this time.
String related source code
In this article, there is only part of the source code of String. After all, the source code of String has more than 3000 lines, so it is not realistic to write it all. Let's choose some interesting code to do some analysis.
Attribute
Let's first take a look at what member variables String has. There are two key attributes, as follows:
Public final class Stringimplements java.io.Serializable, Comparable, CharSequence {/ * * The value is used for character storage. * / char array private final char value []; / * * Cache the hash code for the string * / private int hash; / / Default to 0
We can see from the source code that a char [] array is declared in the String class, with the variable name value, and a variable of type int hash (the cache of the hash value of the String object). In other words, the String class in java is actually an encapsulation of the char array.
Construction method
Next, let's take a look at the string creation process through a single line of code, String c = new String ("abc"); we know that using the new keyword will use the constructor, so here's how it works.
Public String (String original) {this.value = original.value;this.hash = original.hash;}
The code in the constructor is very simple, assigning the value of the passed string, that is, the char array, to the current object, and hash also handles it, so the problem is WTF original?
What you need to pay attention to here is a mechanism in java. In Java, when the value is enclosed in double quotes (such as "abc" in this example), JVM will first check to see if there is an object called abc in the constant pool. If not, initialize the abc as an object into the constant pool, and if so, directly return the content of the constant pool. So that is to say, on the basis of no "abc", the executing code will create an abc in the string pool and another new in the heap memory. The final result is shown below:
What if there is another String c2 = new String ("abc"); at this time? As shown in the picture
We can also see this through the debug function of IDEA, and you will find that the addresses of the char arrays in c and c2 are the same. It is enough to show that the same array is used when creating c and c2.
Equals method
Public boolean equals (Object anObject) {/ / if two objects are the same reference, then directly return trueif (this = = anObject) {return true;} / * 1. Determine whether the incoming object is of type String 2. Determine whether the length of the char array of the two objects is the same. 3. Loop to determine whether each value in the char array is equal or not before the above conditions are met before returning true*/if (anObject instanceof String) {String anotherString = (String) anObject;int n = value.length;if (n = = anotherString.value.length) {char v1 [] = value;char v2 [] = anotherString.value;int I = 0bot while (NFO -! = 0) {if (v1 [I]! = v2 [I]) return false;i++;} return true;}} return false;}
Why is String immutable?
String pool needs
Why is it needed for a string of pools? We mentioned at the beginning that strings in the string pool are referenced by multiple variables, which allows string objects to be reused and avoids a lot of unnecessary memory consumption.
So imagine that if the String object itself allows secondary modification, I have a string "abc" referenced by 100 variables at the same time, one of which modifies the String object, then it will affect the other 99 variables that reference the object, which will have an uncontrollable impact on other variables.
The advantage of immutability
Security.
The consideration of string immutable security is in two aspects, data security and thread safety.
Data security, you can recall, where do we use a lot of strings? Network data transfer, file IO, etc., that is to say, when we are passing parameters, we do not need to consider who may modify its internal values when using immutable classes. If we use mutable classes, we may need to remember to re-copy the values every time, and there will be a certain loss of performance.
Thread-safe, because strings are immutable, they are multithread-safe, and the same string instance can be shared by multiple threads, so that synchronization does not have to be used because of thread-safety issues.
Performance and efficiency
On the one hand, performance efficiency is reuse, on the other hand, it needs to start from the cache direction of hash values.
The hash value of String is used in many places, and if the immutability of String is guaranteed, it can be guaranteed that the hash value is always immutable, so that there is no need to recalculate the hash value each time it is used.
How is String immutability achieved?
By privatizing the property, final modification, and without providing public get set methods and other methods that can modify the property, it is guaranteed that it will not be modified externally after creation.
Don't forget that String is also decorated by final. As we mentioned in the previous article, the result of the final decorated class is that the String class has no subclasses.
So String really can't change? No, through reflection we can, the code is as follows:
String c = new String ("abc"); System.out.println (c); / / get the value field Field valueFieldOfString = String.class.getDeclaredField ("value") in the String class; / / change the access permission of the value property valueFieldOfString.setAccessible (true); / / get the value of the value property on the s object char [] value = (char []) valueFieldOfString.get (c); / / change the fifth character value [1] ='_'; System.out.println (c) in the array referenced by value
The result of the execution is
Abca_c
In other words, what's the point of changing the value of the string object? It doesn't make any sense. We never do that.
Other questions
Please do not use the new keyword to create a string if it is not particularly needed
We know from the previous article that when you use the new keyword to create a String, even if there is the same String in the string pool, you will still create objects in the heap memory again, which will be a waste of memory. On the other hand, object creation is less efficient than fetching from the string pool.
The difference between String StringBuffer StringBuilder
With regard to the difference between the three, it often appears in the interview questions, the String object is immutable, so any modification on the content will create a new string object, once the modification operation is too much, it will cause a lot of waste of resources.
StringBuffer and StringBuilder do not create new objects when doing string concatenation, but modify them on the original object. The difference is that StringBuffer is thread-safe and StringBuilder is not thread-safe. Therefore, StringBuffer or StringBuilder is recommended for string concatenation.
The above is all the content of the article "sample Analysis of String in Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.