当前位置:网站首页>The String class objects created by the JVM memory allocation and the difference between equals and = =

The String class objects created by the JVM memory allocation and the difference between equals and = =

2022-08-09 07:33:00 hash crazy

Definition:

String s1 = "uml";String s2 = "uml";String s3 = new String("uml");String s4 = new String("uml");System.out.println(s1==s2);System.out.println(s3==s4);System.out.println(s1.equalsspan>(s4));

Judging code output results

A. true false true

B. false true false

Parse

This question examines the memory allocation of objects created by the String class in the JVM and the difference between equals and ==.

  • ==Compare address and value
  • equals compares values

insert image description here

  • s1==s2 compares the address and value. From the above figure, we know that the two references point to the same address, so return true.
  • s3 == s4 compares the addresses of two space objects created by new, so the values ​​are the same, but the addresses are different, return false.
  • s1.equals(s3) compares the content and returns true.
  • Objects created with new are in the heap
  • The temporary variable in the function is in the stack area
  • string in java is in the string constant area

This question is extremely imprecise, and the answer depends on the specific JVM type and specific JVM version.The following analysis is based on the widely used Oracle HotSpot virtual machine:
First, String str1 = "abc", when compiled to bytecode, is actually equivalent to: String str1 = "abc".intern()

For JDK 1.6, the intern() method is like this: if "abc" is encountered for the first time, the string "abc" itself is copied into the string constant pool, and if "abc" is encountered again later, which directly returns a reference to the constant pool.Note that the constant pool of JDK 1.6 exists in the permanent generation of the JVM, and for the implementation of the Hotspot virtual machine, the permanent generation actually corresponds to the method area in the java virtual machine specification!

As of JDK 1.7, the intern() method does not make a copy of the string instance, but only records the first occurrence of the instance reference in the string constant pool.Of course, the most important thing is that the string constant pool in JDK 1.7 is on the heap!
For details, please refer to the discussion on pages 42 and 57 of the book "In-depth understanding of the JAVA virtual machine"

原网站

版权声明
本文为[hash crazy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090724110891.html