String str1= "ABC"; Memory distribution problem

Source: Internet
Author: User
Tags garbage collection wrapper
[Csharp]View plain copy String str1= "abc";   String Str2=new string ("abc"); What's the difference?
Today, some people in a Java group asked this question, found that they did not understand, Google a while to find a more clear article said.

=================================================================

Java divides memory into two types: one is stack memory and the other is heap memory.

Some of the basic types of variables and reference variables defined in the function are allocated in the stack memory of the function.

When a variable is defined in a block of code, Java allocates memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically releases the memory space allocated for the variable, which can be used as an immediate alternative.

Heap memory is used to store objects and arrays created by new.

The memory allocated in the heap is managed by the automatic garbage collector of the Java Virtual machine.

After generating an array or object in the heap, you can also define a special variable in the stack so that the value of the variable in the stack equals the first address of the array or object in the heap memory, and the variable in the stack becomes the reference variable for the array or object.

A reference variable is equivalent to a name that is an array or an object, and you can later use the reference variable in the stack to access the array or object in the heap.

In particular, say:
Stacks and heaps are places where Java is used to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set stacks or heaps.
Java's heap is a run-time data area in which the object allocates space. These objects are established through directives such as new, NewArray, Anewarray, and Multianewarray, and they do not require program code to be explicitly released. The heap is responsible for garbage collection, the advantage of the heap is the dynamic allocation of memory size, the lifetime does not have to tell the compiler in advance, because it is dynamically allocating memory at runtime, the Java garbage collector will automatically take away these no longer used data. The disadvantage is that the access rate is slow due to the dynamic allocation of memory at run time.
The advantage of the stack is that the access speed is faster than the heap, after the register, the stack data can be shared. The disadvantage is that the data size and lifetime in the stack must be fixed and inflexible. There are some basic types of variables in the stack (, int, short, long, byte, float, double, Boolean, char), and object handles.
Stack has a very important particularity, is the existence of the stack of data can be shared. Let's say we both define:
int a = 3;
int b = 3;
The compiler deals with int a = 3 First, it creates a reference to a in the stack, finds out if there is a 3 value in the stack, and if not, it stores 3 in, then points a to 3. then process int b = 3, after you create the reference variable for B, because you already have 3 in the stack, point B directly to 3. In this way, there is a case where A and B both point to 3. At this point, if you make a=4 again, the compiler will search for a 4 value in the stack, and if not, put 4 in and point A to 4, and if so, direct a to this address. Therefore the change of a value does not affect the value of B. Note that this sharing of data is different from the two-object reference to an object, because the modification of a does not affect B, it is done by the compiler, and it helps save space. While an object reference variable modifies the internal state of the object, it affects another object reference variable.

A string is a special wrapper class data. Can be used:
String str = new String ("abc");
String str = "ABC";
In two forms, the first is to create a new object with new (), which is stored in the heap. Each time a call is made, a new object is created.
And the second is to create an object reference variable str in the stack on a string class, then find out if there is any "ABC" in the stack, and if not, store "ABC" in the Stack and make str point to "ABC", and If "ABC" is already there, direct STR to "ABC".

When comparing the values in a class with the Equals () method, use = = when testing whether references to two wrapper classes are pointing to the same object, use the following example to illustrate the above theory.
String str1 = "abc";
String str2 = "abc";
System.out.println (STR1==STR2); True
You can see that str1 and str2 are pointing to the same object.

String str1 =new string ("abc");
String str2 =new string ("abc");
System.out.println (STR1==STR2); False
The way to new is to generate different objects. Generate one each time.
So the second way to create multiple "ABC" strings is that there is only one object in memory. This formulation is advantageous and saves memory space. At the same time it can improve the speed of the program to some extent, because the JVM will automatically determine whether it is necessary to create new objects based on the actual situation of the data in the stack. For code with string str = new String ("abc"), the new object is created in the heap, regardless of whether its string value is equal or not, and it is necessary to create a new object, which increases the burden on the program.
On the other hand, note that when we use a format-definition class such as String str = "ABC", we always assume that the object str of the string class was created. Worry about traps. The object may not have been created. Instead, you might just point to an object that you have previously created. Only the new () method can be used to guarantee that one object is created each time. Because of the immutable nature of the string class, you should consider using the StringBuffer class to improve program efficiency when string variables need to change their values frequently. ====================================================== Exercise question: The following code generates several string objects
String a= "ABC";
String b= "ABC";
String C=new string ("abc");
String D=c.intern ();
String a= "ABC"; Yes
String b= "ABC"; No
String C=new string ("abc"); Yes
String D=c.intern (); This sentence is the key.
String C=new string ("abc");
String D=c.intern ();
If this is the only way
c = d. The result is false because the reference variable C to the address of the heap memory; but intern (); But in the stack to open up a piece of memory.
For the subject: C.intern (); When executed, the object "ABC" is found in the stack memory, so the pointer is directed to "ABC" so that a = = d, b==d result is true;
So the answer to this one is 2.

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.