A comparison of Java-Foundation string

Source: Internet
Author: User

String Str=new string ("X");
and string str= "X";

What is the difference between the two sentences?

In the computer's memory there are heaps and stacks of space, where the stack of all objects, functions, variables such as drinking, while the heap of objects, values and so on.
Whether it's a new object or a string str = "X", objects of this kind are placed in the heap.
For your first question, give a simple example:
String str1 = "x";
String str2 = "x";
String str3 = new String ("X");
On the surface these three sentences are instantiated 3 string objects, actually two. In Java, there is a memory management mechanism called "character data Pool", before assigning a value to STR2, it checks for the same data in the pool and, if so, a direct reference; if not, the system instantiates the string object; execution to string str3 = new String ("X" ; The system will instantiate the object directly without looking in the pool. This object will not be placed in the pool.
You may ask if changes to str1 or str2 will change the value of another reference. The answer is no. The system first looks for the same object in the pool, and if not, instantiates the object.

public static void Main (string[] arg) {
String B = "1";
String A=new string ("a");
int c = 1;
String a = string.valueof (c); A!=b
String a= string.valueof ("1"); A=b
if (a = = b) {
System.out.print ("a");

}
}

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.