There are two interview questions about the difference between the String nominal value object and the object created by the constructor = and equals.

Source: Internet
Author: User

There are two interview questions about the difference between the String nominal value object and the object created by the constructor = and equals.

Interview Question 1:

 

Package common object _ String; public class StringDemo4 {public static void main (String [] args) {String s1 = new String ("hello "); string s2 = new String ("hello"); System. out. println (s1 = s2); // falseSystem. out. println (s1.equals (s2); // trueString s3 = new String ("hello"); String s4 = "hello"; // This constant value System is available in the method area. out. println (s3 = s4); // falseSystem. out. println (s3.equals (s4); // trueString s5 = "hello"; String s6 = "hello"; System. out. println (s5 = s6); // trueSystem. out. println (s5.equals (s6); // true }}

Interview Question 2:

 

 

Package common object _ String; public class StringDemo5 {public static void main (String [] args) {String s1 = "hello"; String s2 = "world "; string s3 = "helloworld"; System. out. println (s3 = s1 + s2); // false. out. println (s3.equals (s1 + s2); // trueSystem. out. println (s3 = "hello" + "world"); // true (because "hello" and "world" are constants, so first splice and then find the constant after splicing, and find that there are, s3 so equal) System. out. println (s3.equals ("hello" + "world"); // true // check the source code through decompilation. We know that the processing is completed here. // System. out. println (s3 = "helloworld"); // System. out. println (s3.equals ("helloworld "));}}

 

/*
* Conclusion:
* If the string is a variable addition, open the space first and then splice it (the address is definitely different when the space is opened)
* If a string is a constant addition, it is first added and then found in the constant pool. If yes, it is directly returned; otherwise, it is created.

We can use the Java decompilation tool XJad to figure out the cause.

*/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.