The difference between string s= "abc" and string S=new string ("abc")

Source: Internet
Author: User

First, explain the difference between string s= "abc" and string S=new string ("abc"):

String s= "ABC"; the object is not created in the heap, the constant "abc" is first searched for in the constant pool, and if there is no "ABC", the ABC is stored in the Run-time pool, then the reference is assigned to S, and the existing address is assigned to s if there is a direct value.

String S=new string ("abc"), first creating an object in the heap, and then assigning the object reference to S.

Next look at this small example:

public class Example {
    String str = new String ("good");
    String str1 = "good";
    String str2 = "good";
    public static void Main (string[] args) {
        Example Example = new Example ();
        System.out.println (EXAMPLE.STR==EXAMPLE.STR1);//output to False
        System.out.println (EXAMPLE.STR2==EXAMPLE.STR1); Output is True
    }
 }

Inside This example:

STR holds a reference to memory in the heap, str1 as an address in a constant pool;

When executing the str2= "good", it will look for "good" directly in the constant pool, if there is a constant, directly assign the constant address to str2, if there is no "good", you need to add it to the constant pool, and then add the new constant address to str2.

The string object also has a method--intern (unfortunately, it is a local method and cannot see how it is implemented internally):

This method can be dynamically extended to run a regular volume pool.

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.