In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how java String is designed to be an immutable object". In daily operation, I believe many people have doubts about how java String is designed to be an immutable object. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how java String is designed to be an immutable object". Next, please follow the editor to study!
What is an immutable object
It can also be understood literally, that is, the object we create is immutable. So what is immutable? In order to make the created objects immutable, the java language requires us to follow the following five rules:
(1) all fields within the class are decorated with final.
(2) all fields within the class are private, that is, they are decorated by private.
(3) classes cannot be integrated and extended.
(4) the class cannot provide external methods that can modify the internal state, and neither can the setter method.
(5) if the field within the class is a reference, that is, it can point to a mutable object, then we programmers cannot get the reference.
It is because our String type follows the above five rules that we say that String objects are immutable. If you want to get to know him, you'd better see what the String minister looks like and take a look at the above five rules.
How String is designed to be an immutable object
1. Doubt one
Before we look at it, let's give you a question. Let's look at the following code.
Public class Test2 {
Public static void main (String [] args) {
String a = "Zhang San"
System.out.println (a)
A = "Li Si"
System.out.println (a)
}
}
/ / output:
/ / Zhang San
/ / Li Si
We said at the beginning of the article that String objects are immutable, here a = Zhang San, and then a = Li Si, is this in line with the immutability of String? The answer is yes, of course.
From the picture above, we can see that the first time String a = "Zhang San", the same object "Zhang San" was created in the heap. Later, when we executed a = "Li Si", we created another object "Li Si" in memory. In other words, our a just changes the address that the reference a points to.
2. Doubts about source code interpretation
Now that the reference address that a points to has changed, there must be a variable inside its String that can point to different actual objects. To find out further, let's go inside its String.
Here we mainly analyze the source code of the String class to see how the Java language is designed to make the String type immutable. What is given here is part of the source code of jdk1.8.
Public final class String
Implements java.io.Serializable, Comparable, CharSequence {
/ * The value is used for character storage. , /
Private final char value []
/ * * Cache the hash code for the string * /
Private int hash; / / Default to 0
.
}
The two main fields above are value and hash. We are mainly here to look at the value array, hash has nothing to do with the topic, so I will not explain it here, I have a special article to introduce hash.
Our String object is actually a character inside and then stored in this value array. But value has no external setValue method, so the entire String object looks immutable externally. Let's draw a picture to explain the above doubts.
Now you get it, which means that what really changes the reference is value, because value is also an array reference. This can also be very convenient to explain the next question.
3. Doubt II
Since our String is immutable, it seems that there are many ways to operate substring, replace, and replaceAll inside. It seems that the String object has changed, and the explanation is very simple. Every time we replace these operations, we actually create a new object in the heap memory. Then our value points to different objects.
During the interview, we just explained that the above reasons are not so perfect. If we want to better get a raise and pretend to be forced, we need to answer further.
Is there any way to change String
Since there is such a title. There must be a way, don't forget our reflection mechanism, under normal circumstances, he can do something that violates the principles of language design. This is also a technique. Whenever the interviewer asks questions that violate the principles of language design, you can refute him with reflection. Let's take a look at this:
Public class Test2 {
Public static void main (String [] args) {
String str = "Zhang San"
System.out.println (str)
Try {
/ / We get the internal value character array through reflection
Field field = String.class.getDeclaredField ("value")
Field.setAccessible (true)
Char [] value
Value = (char []) field.get (str)
/ / change the first character of the string to Wang
Value [0] = 'Wang'
System.out.println (str)
} catch (Exception e) {
E.printStackTrace ()
}
}
}
/ / output:
/ / Zhang San
/ / Wang San
We can change the String through reflection.
Now we know its principle and usage, and we also know that String can be changed by reflection. There is another question we haven't figured out. You can also ask him during the interview to further improve your pressure.
4. Why the JAVA language designed the String type to be immutable
There are several features here.
First: in the Java program, the String type is the most used, which involves a large number of additions, deletions, modifications and queries. In fact, before each addition, deletion and correction, jvm needs to check the security of this String object, that is, through hashcode, when it is designed as an immutable object, it ensures the uniqueness of each addition, deletion, change and search, and you can rest assured of operation.
Second: the network connection address URL, the file path path is usually saved in the String type, if the String is not fixed, it will cause a variety of security risks. Just like our password cannot be saved as String, if you save the password as a string in clear text, it will remain in memory until the garbage collector clears it. Because the string is placed in the string buffer pool to facilitate reuse, it may be retained in memory for a long time, which will lead to security risks.
Third: string values are retained in the constant pool, that is, if string objects are allowed to change, it will lead to various logic errors.
At this point, the study on "how java String is designed to be an immutable object" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.