What you have to know about string and string constant pool in Java

Coderw likes to blog 2021-01-24 14:26:36
know string string constant pool


Old fashioned written test questions

In some old-fashioned written test questions , I'll ask you to judge s1==s2 by false still true,s1.equals(s2) by false still true.

String s1 = new String("xyz");
String s2 = "xyz";
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));

For this kind of question , You can always give standard answers quickly :== The comparison is the object address ,equals Method compares real character arrays . So the output is false and true.

The questions above belong to the lowest level , There is no difficulty .

Now the old-fashioned topic has gradually disappeared , Instead, there are some new issues that are out of shape :

String s1 = "aa";
String s2 = "bb";
String str1 = s1 + s2;
String str2 = "aabb";
// What is the output ???
System.out.println(str1 == str2);
final String s3 = "cc";
final String s4 = "dd";
String str3 = s3 + s4;
String str4 = "ccdd";
// What's the output ???
System.out.println(str3 == str4);

It's a little more difficult , But it's not hard to think about it. The answer is false and true.

Today's article is based on these topics .

String Object creation

Let's take a look String Class structure :

image-20210122222326753

You can find ,String There's a value attribute , It's really storing characters char Array .

In execution String s = "xyz"; When , In the heap area, a String object , One char Array objects .

image-20210123134243855

How to prove that a String Object and a char Array objects ? We can go through IDEA Of Debug functional verification :

15

Pay attention to the location of my screenshot , The execution of the String s = "xyz"; after , Click again on the load classes,Diff Hurdles String and char[] They added 1, Indicates that a new one has been added to the memory char Array objects and a String object .

Now? , Let's see String s = new String("xyz"); Several objects are created .

14

From this Debug Moving graph , We can come to the conclusion that String s = new String("xyz"); after , I created two String Object and a char Array objects .

Again because String s = new String("xyz"); Of s A reference can only point to one object , You can draw a memory map :

image-20210123135550260

As you can see from the diagram , In the pile area , There are two String object , these two items. String Object's value All point to the same char Array objects .

So here comes the question , The next one String Objects are not referenced at all , That is to say, he was not used , So what does it do ?

It takes up memory space and doesn't use it , Is this the case? JDK Design defects of ?

image-20210123140717179

Obviously not JDK The defects of ,JDK Although there are design flaws , But it's not so obvious , So stupid .

The one down there String What does the object do ?

The answer is to reside in the string constant pool , Be careful , I used one here Resident , It's not just putting objects into the string constant pool , What's the difference? We'll talk about it later .

It's here String constant pool The concept of , I am here String s = new String("xyz") Create a few examples, can you really answer right ? I also have a detailed introduction in , If you are interested, you can have a look , No more repetition here .

You just need to know , String constant pool in JVM The corresponding class in the source code is StringTable, The bottom layer is an implementation Hashtable.

image-20210123154722863

We use String s = new String("xyz"); For example :

First, look for the string constant pool , See if you can find “xyz” A string corresponds to a reference to an object , If not found in the string constant pool :

  • Create a String Objects and char Array objects
  • Will create the String Object encapsulation into HashtableEntry, As StringTable Of value For storage
  • new String("xyz") Another one will be created in the heap String object ,char The array points directly to the created char Array objects

If you can find it in the string constant pool :

  • new String("xyz") An object is created in the heap ,char Arrays point directly to existing char Array objects
image-20210123151830718

and String s = "xyz"; What kind of logic :

First, look for the string constant pool , See if you can find “xyz” A reference to a string , If you can't find it in the string constant pool :

  • Create a String Objects and char Array objects
  • Will create the String Object encapsulation into HashtableEntry, As StringTable Of value For storage
  • Return to the created String object

If you can find it in the string constant pool :

  • Directly return to find the reference corresponding to String object
image-20210123153425794

In summary, it is :

about String s = new String("xyz"); This form creates string objects , If you can find it in the string constant pool , Create a String object ; If not found in the string constant pool , Create two String object .

about String s = "xyz"; This form creates string objects , If you can find it in the string constant pool , Does not create String object ; If not found in the string constant pool , Create a String object .

image-20210123171825252

therefore , In daily development , It works String s = "xyz"; As far as possible need not String s = new String("xyz");, Because you can create one less object , Save some space .

It's important to note that , The string constant pool stores neither strings nor String object , But one by one HashtableEntry,HashtableEntry Inside value It's pointing to String object , In order not to complicate the expression , I omitted HashtableEntry The existence of , But it doesn't mean it doesn't exist .

The residence mentioned above is new HashtableEntry Point to String object , And put HashtableEntry The process of storing in the string constant pool .

In some articles on the Internet , Some authors may be trying to make readers better understand , Omitted some of these , Be sure to distinguish .

image-20210123160353095

After reaching the above consensus , Let's go back to the old written test .

String s1 = new String("xyz");
String s2 = "xyz";
// Why output is false Well ?
System.out.println(s1 == s2);
// Why output is true Well ?
System.out.println(s1.equals(s2));

With the foundation above , We draw the corresponding memory map ,s1 == s2 Why false At a glance .

image-20210123155156910

because equals Methods compare the real char data , and s1 and s2 It's all pointing to the same char Array objects , therefore s1.equals(s2) be equal to true.

They're all pointing to the same char The idea of array objects , It can also be proved by reflection :

image-20210123170204407

I modified str1 Point to the String Object's value,str2 The object pointed to is also affected .

image-20210123222415172

String splicing

Now? , Let's take another look at the variation :

String s1 = "aa";
String s2 = "bb";
String str1 = s1 + s2;
String str2 = "aabb";
// Why output is false
System.out.println(str1 == str2);

For this subject , We need to look at the bytecode of this code first .

image-20210123161329482

It doesn't matter if you don't understand the bytecode instruction , Just look at the part I framed in red , It can be seen that StringBuilder.

What does that mean , That is to say String str1 = s1 + s2; Will be optimized by the compiler to new StringBuilder().append("aa").append("bb").toString();

StringBuilder Inside append The way is right char Array operation , that StringBuilder Of toString What did the method do ?

image-20210123221900789

You can see from the source code ,StringBuilder Inside toString Method is called String The inside of the class String(char value[], int offset, int count) Construction method , What does this method do ?

  • Make a copy according to the parameters char Array objects . Made a copy of !
  • Create a String object ,String Object's value Point to the copied char Array objects .

Be careful , It doesn't reside in the string constant pool , This is the key !!! Draw a picture to understand :

image-20210123164646528

in other words str2 Point to the String Object does not reside in the string constant pool , and str1 The object pointed to resides in the string constant pool , And they're not the same object . therefore str1 == str2 still false

Because make a copy of char Array objects , So if we change one of them char Array words , The other won't have an impact :

image-20210123170038866

Put... In it String After becoming ugly , The other is Shuaibi , It also shows two String The objects are not the same char Array .

2abe2cc517a513e4ac5fcec0d3669b22

intern Method

The above said , call StringBuilder Of toString Method to create String Objects do not reside in the string constant pool , What if I want to reside in the string constant pool ? Is there any way ?

yes , we have ,String Class intern Methods can help you to complete this thing .

Take this code for example :

String s1 = "aa";
String s2 = "bb";
String str = s1 + s2;
str.intern();

In execution str.intern(); Before , The memory map looks like this :

image-20210123174512400

In execution str.intern(); after , The memory map looks like this :

image-20210123174805405

intern The way to do that is to create a HashtableEntry object , And put value Point to String object , And then put HashtableEntry adopt hash Locate and store it in the corresponding string constant pool . Of course , The premise is that there is no corresponding... In the string constant pool HashtableEntry.

be without ,intern Method , It's that simple , Let me make it clear to you in one sentence .

About intern Method , There is also a very interesting story , If you are interested, you can have a look why This article of God 《 In depth understanding of Java virtual machine 》 The first 2 Finally, the hole dug in the 3 In version by R Big fill

Compile optimization

Write here , There seems to be only one hole left unfilled . That's why the output is true.

final String s3 = "cc";
final String s4 = "dd";
String str3 = s3 + s4;
String str4 = "ccdd";
// Why output is true Well ???
System.out.println(str3 == str4);

This problem is compared with the one above , A bit similar , Add two to the original final keyword . Let's take a look at the bytecode of this code first :

image-20210123171346440
image-20210123171437557

Another bytecode instruction , You don't need to understand , You click #4, You can see “ccdd” character string .

original , use final After modification ,JDK Your compiler recognizes optimizations , Will be able to String str3 = s3 + s4; Optimize to String str3 = "ccdd".

image-20210123223456766

So the original question is equivalent to :

String str3 = "ccdd";
String str4 = "ccdd";
// Why output is true Well ???
System.out.println(str3 == str4);

Is this a difficult topic ? It doesn't matter str3 and str4 How to compare , It must be equal .

summary

String about Java For programmers, it's just “ The most familiar stranger ”, You say? String Simple , It's really simple . You say it's difficult , It's really difficult to get to the bottom of it , But these topics , As long as you have a memory map in your mind, it will be very simple .

Interview questions will only get harder and harder , The industry seems to be getting more and more involved , But as long as I learn fast , The inner volume can't reach me .

Okay , Today I wrote about , I'm going to play games .

Hope this article , Can help you a little .

At the end ( Please pay attention to )

I am responsible for every article I send out , Knowledge theory is involved in this paper , I try to find and verify it in official documents and authoritative books . But even so , I can't guarantee that every point in the article is correct , If you find something wrong , Welcome to point out , I'll fix it .

It's not easy to create , For better expression , You need to draw a lot of pictures , These are all for my own use PPT Painted , Drawing is also very hard !

image-20210123180803720

therefore , Don't hesitate , Give me some positive feedback , Promise me , One key, three links ( Focus on 、 give the thumbs-up 、 Look again ) Okay? ?

I am a CoderW, A programmer .

Thanks for reading , See you next time !

WeChat official account 【CoderW】

版权声明
本文为[Coderw likes to blog]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210124142602994t.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云