Heap, Stack, Chang __java in Java

Source: Internet
Author: User
Tags garbage collection wrapper advantage

Java memory allocation:

1. Registers: We cannot control in the program
2. Stack: Hold the base type of data and object references, but the object itself is not stored in the stack, but stored in the heap
3. Heap: Storing data produced with new
4. Static domain: Static members that are stored in the object with static definitions
5. Constant pool: Storing constants
6. Non-RAM (random access memory) storage: Hard disk and other permanent storage space
--------------------------------------------------------------------------------------------------------------- -------

A. Some basic types of variable data and reference variables for objects defined in functions 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 variable exits the scope, Java automatically releases the memory space allocated for the variable, which can be used as an immediate alternative.
B. 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. A reference variable is equivalent to a name that is an array or an object. A reference variable is a normal variable that is assigned in the stack when defined, and the reference variable is released after the program runs beyond its scope. and the arrays and the objects themselves are allocated in the heap, even if the program runs to a block of code that uses new to produce an array or an object's statements, the memory occupied by the array and the object itself is not freed, and the array and object become garbage when they point to it without a reference variable, and cannot be used, but still occupy the memory space. Be taken Away (released) by the garbage collector at a later uncertain time. This is why Java comparisons account for memory.
In fact, the variables in the stack point to variables in the heap memory, which is the pointer in Java.
C. Chang (constant pool) refers to some data that is determined at compile time and is saved in the compiled. class file. In addition to the various basic types that are defined in the code, such as int, long, and so on) and the constant values (final) of object types (such as strings and arrays) also contain some symbolic references that appear as text, such as the fully qualified name of the class and interface; the name and descriptor of the field, the method and the name and the descriptor. The virtual machine must maintain a constant pool for each mounted type. A constant pool is an ordered set of constants used by the type, including direct constants (String,integer and floating point constants) and symbolic references to other types, fields, and methods. For a string constant, its value is in a constant pool. The Chang in the JVM exists as a table in memory, and for string types, a fixed-length constant_string_info table is used to store literal string values, noting that the table stores only literal string values and does not store symbol references. Here, there should be a clearer understanding of where to store string values in a constant pool.

When the program executes, the constant pool is stored in method area, not in the heap.
The D.java 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 variable data in the stack (int, short, long, byte, float, double, Boolean, char) and object handles (references).

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, and then through the symbolic reference go to the string constant pool to find there is no "ABC", if not, then put "ABC" into the string constant pool, and make str point to "ABC", if there is already "ABC" Then 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.
1. First, string does not belong to 8 basic data types, and string is an object.
Because the default value of the object is NULL, the default value of string is also null, but it is a special object with some attributes that other objects do not have.

2. The new string () and the new string ("") are all declarations of a newly empty string, which is not null;

3. The difference between string str= "Kvill"; string Str=new string ("Kvill")

See Example 1:

String s0= "Kvill";
String s1= "Kvill";
String s2= "kv" + "ill";
System.out.println (S0==S1);
System.out.println (S0==S2);
The results are:
True
True

First of all, we need to know that the result is Tao Java will ensure that a string constant has only one copy.
Because the "Kvill" in the S0 and S1 in the example are string constants, they are determined at compile time, so s0==s1 is true, and "kv" and "ill" are string constants, and when a string is concatenated by multiple string constants, it is definitely a string constant, So S2 is also parsed as a string constant at compile time, so S2 is also a reference to "Kvill" in a constant pool. So we come to s0==s1==s2; The string created with the new string () is not a constant and cannot be determined at compile time, so the string created by new string () is not placed in a constant pool and has its own address space.

See Example 2:
String s0= "Kvill";
String S1=new string ("Kvill");
String s2= "kv" + New String ("ill");
System.out.println (S0==S1);
System.out.println (S0==S2);
System.out.println (S1==S2);
The results are:
False
False
False

Example 2, S0 or the application of "Kvill" in a constant pool, S1 is a reference to the new object "Kvill" that was created at run time because it cannot be determined at compile time, S2 is also a newly created object because it has the latter half of new String ("ill") and cannot be determined at compile time. Kvill "The application of the", understand these also know why to come to this result.

4. String.intern ():
One more thing: the constant pool that exists in the. class file is loaded by the JVM at runtime and can be expanded. The Intern () method of string is a method of extending a constant pool, and if a string instance str calls the Intern () method, does the Java lookup constant pool have the same Unicode string constant, and if so, returns its reference, if not, Adds a string of Unicode equals str to the constant pool and returns its reference; see example 3 is clear.

Example 3:
String s0= "Kvill";
String S1=new string ("Kvill");
String S2=new string ("Kvill");
System.out.println (S0==S1);
System.out.println ("**********");
S1.intern ();
S2=s2.intern (); Assigns a reference to "Kvill" in a constant pool to S2
System.out.println (S0==S1);
System.out.println (S0==s1.intern ());
System.out.println (S0==S2);
The results are:
False
**********
False//Although S1.intern () was executed, its return value was not assigned to S1
True//Description S1.intern () returns a reference to "Kvill" in a constant pool
True

And finally, I'm going to break a wrong understanding: Someone says, "using the String.intern () method, you can save a string class to a global string table, and if the Unicode string with the same value is already in this table, So the method returns the address of an existing string in the table, if there are no strings of the same value in the table, register your address in the table "If I take this global string table he said as Chang, his last remark," If you don't have a string with the same value in the table, register your address in the table "Is wrong:

See Example 4:
String S1=new string ("Kvill");
String S2=s1.intern ();
System.out.println (S1==s1.intern ());
System.out.println (s1+ "" +s2);
System.out.println (S2==s1.intern ());
Results:
False
Kvill Kvill
True

In this class we have no reputation for a "kvill" constant, so there's no "Kvill" at first in the constant pool, and when we call S1.intern () we add a new "Kvill" constant in the constant pool, and the original "Kvill" in the constant pool still exists, and it's not " Register your address in a constant pool ".
S1==s1.intern () to False indicates that the original "Kvill" still exists; S2 is now the address of "Kvill" in the constant pool, so S2==s1.intern () is true.

5. About Equals () and = =:
This is simple for string to compare the Unicode sequences of two strings to be equivalent, if equality returns true, and = = is to compare the addresses of two strings to the same, that is, whether they are references to the same string.

6. About string is immutable
This is a lot to say, you just know that a string instance once generated will not change again, for example: string str= "kv" + "ill" + "" + "ans"; Is that there are 4 string constants, first "KV" and "ill" generate "Kvill" in memory, and then "Kvill" and "" Generate "Kvill" exist in memory, and then "Kvill ans" is generated, and the address of this string is assigned to STR, It is because string "immutable" produces a lot of temporary variables, which is why it is suggested that StringBuffer be used because StringBuffer is changeable.

/*******************************************************************************/

The following are some common questions related to string:

Final usage and understanding in string
Final StringBuffer a = new StringBuffer ("111");
Final StringBuffer B = new StringBuffer ("222");
a=b;//This sentence compilation does not pass

Final StringBuffer a = new StringBuffer ("111");
A.append ("222");/compile through

It is visible that final is valid only for reference "value" (that is, memory address), forcing the reference to point only to the object to which it was initially directed, and changing its point will result in a compile-time error. Final is not responsible for the change in the object it points to.

Several examples of String constant pool problems

Here are a few common examples of comparative analysis and understanding:
[1]
String a = "A1";
String B = "a" + 1;
System.out.println ((A = = b)); result = True
String a = "atrue";
String B = "a" + "true";
System.out.println ((A = = b)); result = True
String a = "a3.4";
String B = "a" + 3.4;
System.out.println ((A = = b)); result = True

Analysis: JVM for string constant "+" connection, the program compile period, the JVM will be the constant string "+" connection optimization to the value after the connection, take "a" + 1, after the compiler optimization in class is already A1. The value of the string constant at compile time is determined, so the final result of the above program is true.

[2]
String a = "AB";
String BB = "B";
String B = "a" + BB;
System.out.println ((A = = b)); result = False

Analysis: JVM for string reference, because there is a string reference in the string's "+" connection, and the referenced value is not determined at the program compile time, the "a" + BB cannot be optimized by the compiler, and only dynamically assigns and assigns the new address after the connection to B during the program run time. So the result of the above program is false.

[3]
String a = "AB";
Final String bb = "B";
String B = "a" + BB;
System.out.println ((A = = b)); result = True

Analysis: The only difference in [3] is the BB string with the final modification, which, for final-modified variables, is stored in its own constant pool or embedded in its bytecode stream at compile time as a local copy of a constant value. So at this point "a" + BB and "a" + "B" effect is the same. Therefore, the result of the above program is true.

[4]
String a = "AB";
Final String bb = GETBB ();
String B = "a" + BB;
System.out.println ((A = = b)); result = False
private static String GETBB () {
return "B";
}

Analysis: JVM for string reference BB, its value cannot be determined at compile time, the result of the above program is false only after the method is invoked by the program runtime, and the return value of the method and "a" are dynamically connected and assigned the address to B.

From the above 4 examples you can tell:
String s = "a" + "B" + "C";
is equivalent to string s = "abc";

String a = "a";
String B = "B";
String c = "C";
String s = a + B + C;

This is not the same, the end result is equal to:
StringBuffer temp = new StringBuffer ();
Temp.append (a). Append (b). append (c);
String s = temp.tostring ();

From the analysis above, it is not difficult to infer that string uses the Join operator (+) inefficiency reason analysis, in the form of such code:

public class Test {
public static void Main (String args[]) {
String s = null;
for (int i = 0; i < i++) {
S + + "a";
}
}
}

Every time you do it, you create a StringBuilder object and then throw it away after append. Recreate the StringBuilder object when the next loop arrives, and then append the string so that it loops until the end. If we use the StringBuilder object directly to append, we can save N-1 time to create and destroy objects. So for the application of string concatenation in the loop, the StringBuffer or Stringbulider object is generally used for append operation.

The Intern method of the string object understands and analyzes:

public class Test4 {
private static String a = "AB";
public static void Main (string[] args) {
String S1 = "a";
String s2 = "B";
String s = s1 + s2;
System.out.println (s = = a);//false
System.out.println (s.intern () = = a);//true
}
}

This is a problem with a constant pool in Java. For the s1+s2 operation, a new object is recreated in the heap, and s holds the contents of the new object in the heap space, so s is not equal to the value of a. When the S.intern () method is invoked, it can return the address value of s in a constant pool, because the value of a is stored in a constant pool, so s.intern and A are equal

Summarize:

A. References (String, array, object, and so on) of local variable data and objects used in the stack to hold some of the original data types but no object content

B. The heap holds objects created using the New keyword.

C. A string is a special wrapper class, the references are stored on the stack, and the object content must be set differently depending on how it was created (Chang and heap). Some compile-time is already created, stored in a string constant pool, and some runtime is created. Use the new keyword to store in the heap.

This article turns from: http://zy19880423.javaeye.com/blog/434179

Related Article

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.