Use = to compare the String type, use the string type to compare

Source: Internet
Author: User

Use = to compare the String type, use the string type to compare

String type ratio

Public class StringDemo {public static void main (String [] args) {String s1 = "abc"; String s2 = "abc"; String s3 = new String ("abc "); system. out. println (s1 = s2); // true System. out. println (s1 = s3); // false }}

According to the = syntax, s1, s2, and s3 are three different objects. Generally, the output is false. However, the running result of the program is true and false. The second output is false, and the first output is true. We know that some basic types of variables and Object Reference variables are allocated in the function stack memory, while the heap memory stores new objects and arrays. However, another region is called the constant pool. The value of a declarative String object, such as String s1 = "abc";, is stored in the constant pool. After we create an object such as String s1 = "abc", "abc" is stored in the constant pool (also called the String pool, when we create a reference String s2 = "abc", the Java underlying layer will first find whether "abc" exists in the constant pool. If so, let s2 point to this value, and will not re-create, if the constant pool does not exist, the pool is created and added. This is why the answer is true and false.

 

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.