java+ the difference between memory allocation and variable storage location

Source: Internet
Author: User

Java memory allocation and management is one of the core technologies of Java, before we introduced the Java memory management and memory leaks and Java garbage collection knowledge, today we go deep into the Java core, the detailed introduction of Java in memory allocation knowledge. In general, Java involves the following areas in memory allocation:

Register: We can't control it in the program

Stack: A reference to a primitive type of data and objects, but the object itself is not stored in the stack, but is stored in the heap (new object)

Heap: Storing data generated with new

Static domain: Static members that are stored in the object with static definitions

Constant pool: Storing constants

Non-RAM storage: Persistent storage space such as hard drives

Stacks in Java memory allocation

Some basic types of variable data and object reference variables that are defined in the function are allocated in the function's stack memory.

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 frees the memory space allocated for the variable, and the memory space is immediately available for another use. The data size and life cycle in the stack can be determined, and the data disappears when no references point to the data.

Heap in Java memory allocation

Heap memory is used to hold 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 an object in the heap, you can also define a special variable in the stack that is equal to the first address of the array or object in the heap memory, and this variable in the stack becomes the reference variable of the array or object. A reference variable is a name that is an array or an object, and you can use reference variables from the stack to access the arrays or objects in the heap later in your program. A reference variable is equivalent to a name that is an array or an object.

A reference variable is a normal variable that is allocated in the stack when defined, and the reference variable is freed after the program runs outside its scope. While the array and the object itself are allocated in the heap, the memory occupied by the array and the object itself is not freed when the program runs beyond the block of code that uses new to produce the array or object's statement, and the array and object become garbage when no reference variable points to it, not in use, but still occupy memory space. The garbage collector takes off (releases) at a later indeterminate time. This is why the Java comparison accounts for memory.

In fact, the variables in the stack point to the variables in the heap memory, which is the pointer in Java!

Heap and Stack

The Java heap is a run-time data area in which objects allocate 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. Heap is responsible for garbage collection, the advantage of the heap is the ability to dynamically allocate memory size, the lifetime does not have to tell the compiler beforehand, because it is at runtime to allocate memory dynamically, Java garbage collector will automatically take away these no longer use data. However, the disadvantage is that the access speed is slower 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. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. The stack mainly contains some basic types of variable data (int, short, long, byte, float, double, Boolean, char) and object handle (reference).

Stack has a very important particularity, is that there is data in the stack can be shared. Let's say we define both:

Java code

int a = 3;

int b = 3;

The compiler processes int a = 3 First, it creates a reference to a variable in the stack, and then finds out if there is a value of 3 in the stack, and if it does not, it stores the 3 in and then points a to 3. then the int b = 3 is processed, and after the reference variable of B is created, because there are already 3 values in the stack, B points directly to 3. In this case, A and B both point to 3.

At this point, if you make a=4 again, then the compiler will re-search the stack for 4 values, if not, then store 4 in, and a point to 4; Therefore the change of a value does not affect the value of B.

It is important to note that this sharing of data with two object references also points to an object where this share is different, because the modification of a does not affect B, which is done by the compiler, which facilitates space saving. An object reference variable modifies the internal state of the object, affecting another object reference variable.

Java code 1.int I1 = 9;   2.int i2 = 9;    3.int i3 = 9;   4.public static final int INT1 = 9;   5.public static final int INT2 = 9; 6.public static final int INT3 = 9;

For member variables and local variables: member variables are external to the method, variables defined internally by the class, and local variables are variables defined inside a method or statement block. Local variables must be initialized. The formal parameter is a local variable, and the data for the local variable exists in the stack memory. Local variables in the stack memory disappear as the method disappears. Member variables are stored in objects in the heap and are collected by the garbage collector. such as the following code: Java code 1.class BirthDate {  2.    private int day;  3.    private int Month ;  4.    Private int year;      5.    public BirthDate ( int d, int m, int y) {  6.        day = d;   7.         month = m;   8.        year = y;  9.  & nbsp }  10.    Omit Get,set method .........  11.}   12.  13.public class test{  14.    public static void Main (String args[]) {  15.int da Te = 9;  16.        test test = new Test ();         17.           Test.change (daTE);   18.        BirthDate d1= new BirthDate (7,7,1970);          19.   }    20.  21.    public void Change1 (int i) {  22.        i = 1234;  23.   }   for the above code, date is a local variable, i,d,m,y is a local variable, and Day,month,year is a member variable. The following analysis of the code execution time changes: 1. The main method begins execution: int date = 9; Date local variables, underlying types, references, and values are present in the stack. 2. Test test = new test (); Test is an object reference, exists in the stack, and the object (new Test ()) exists in the heap. 3. Test.change (date); I is a local variable, and the reference and value exist in the stack. When the method change execution is complete, I will disappear from the stack. 4. BirthDate d1= new BirthDate (7,7,1970);  D1 is an object reference, exists in the stack, the object (new BirthDate ()) exists in the heap, where D,m,y is stored in the stack as local variables, and their type is the underlying type, So their data is also stored in the stack. Day,month,year are member variables that are stored in the heap (new BirthDate ()). When the birthdate construction method finishes executing, the d,m,y disappears from the stack. After the 5.main method executes, the date variable, TEST,D1 reference will disappear from the stack, new test (), new BirthDate () will wait for garbage collection.

Chang (Constant Pool)

Chang refers to some data that is determined at compile time and is saved in the compiled. class file.

In addition to the constant values (final) that contain the various basic types defined in the code (such as int, long, and so on) and object types (such as strings and arrays), there are also 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;

Methods and names and descriptors.

If the compilation period has been created (defined directly in double quotation marks), it is stored in a constant pool, which is stored in the heap if the runtime (new) is determined. for a string equal to equals, there is always only one copy in the constant pool, with multiple copies in the heap.

String is a special wrapper class data. Can be used:

Java code

String str = new String ("abc");

String str = "ABC";

Two forms, the first is to create new objects with new (), which is stored in the heap. A new object is created each time the call is made. The second is to create an object reference to the string class in the stack str, and then through the symbol reference to the string constant pool to find there is no "ABC", if not, the "ABC" into the string constant pool, and the Str point to "ABC", if there is already "ABC" The STR directly points to "ABC".

Use the Equals () method when comparing values within a class, and when testing two wrapper classes for reference to the same object, use = =, the following example illustrates the above theory.

Java code

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.

Java code

String str1 =new string ("abc");

String str2 =new string ("abc");

System.out.println (STR1==STR2); False

The new method is to generate different objects. Each time one is generated.

So the second way to create multiple "abc" strings, in memory in fact there is only one object. This writing 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 data in the stack. In the case of string str = new String ("abc"), the code creates a new object in the heap, regardless of whether the string value is equal or not, and it is necessary to create a new object, thereby aggravating the burden of the program.

On the other hand, it is important to note that when you define a class using a format such as String str = "ABC", you always want to assume, of course, that the object that created the string class is Str. Worry about traps! The object may not have been created! Instead, it might just point to an object that was previously created. Only through the new () method can you guarantee that a new object is created each time.

Several examples of string constant pool problems

Example 1:

Java code

String s0= "Kvill";

String s1= "Kvill";

String s2= "kv" + "ill";

System.out.println (S0==S1);

System.out.println (S0==S2);

The result is:

True

True

Analysis: First, we need to know that the result is that Java ensures that a string constant has only one copy.

Because the "Kvill" in 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 also string constants, and when a string is concatenated by multiple string constants, it is itself a string constant. So S2 is also parsed as a string constant at compile time, so S2 is also a reference to "Kvill" in the constant pool. So we come to s0==s1==s2;

Example 2:

Example:

Java code

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 result is:

False

False

False

Parsing: strings created with new string () are not constants and cannot be determined at compile time, so the strings created by new string () are not placed in the constant pool, they have their own address space.

S0 is also an application of "Kvill" in a constant pool, s1 because it cannot be determined at compile time, it is a reference to the new object "Kvill" created at run time, S2 because there is a second half part new String ("ill") so it cannot be determined at compile time, so it is also a newly created object "Kvill" The application of the same, and understand that this will know why the result is reached.

Example 3:

Java code

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 "+" number connection, the program compile period, the JVM will be the constant string "+" connection optimization to the concatenated value, take "a" + 1, the compiler is optimized in class is already A1. The value of its string constants is determined at compile time, so the final result of the above program is true.

Example 4:

Java code

String a = "AB";

String BB = "B";

String B = "a" + BB;

System.out.println ((A = = b)); result = False

Analysis: JVM for string reference, because in the string "+" connection, there is a string reference exists, and the reference value in the program compilation period is not determined, that is, "a" + BB can not be optimized by the compiler, only during the program run time to dynamically allocate and the new address after the connection to B. So the result of the above program is also false.

Example 5:

Java code

String a = "AB";

Final String bb = "B";

String B = "a" + BB;

System.out.println ((A = = b)); result = True

Analysis: The only difference between [4] is that the BB string has a final decoration, and for a final modified variable, it is parsed at compile time to a local copy of the constant value stored in its own constant pool or embedded in its byte stream. So at this point the "a" + BB and "a" + "B" effect is the same. Therefore, the result of the above program is true.

Example 6:

Java code

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: The JVM for the string reference BB, its value in the compilation period can not be determined, only after the program run time call method, the return value of the method and "a" to dynamically connect and assign the address to B, so the result of the above program is false.

About string is immutable

From the above example, we 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 equals:

Java code

StringBuffer temp = new StringBuffer ();

Temp.append (a). Append (b). append (c);

String s = temp.tostring ();

From the above analysis results, it is not difficult to infer that the string using the Join operator (+) inefficiency reason analysis, such as the code:

Java 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 produce a StringBuilder object and then throw it away after append. The next time the loop arrives, it re-generates the StringBuilder object and then append the string so that it loops until the end. If we use the StringBuilder object directly for Append, we can save N-1 time to create and destroy objects. So for applications that want to concatenate strings in a loop, the StringBuffer or Stringbulider objects are generally used for append operations.

Because of the immutable nature of the string class, this is said a lot, as long as we know that the string instance once generated will not be changed, such as: string Str= "kv" + "ill" + "+" ans "; There are 4 string constants, first "KV" and "ill" generate "Kvill" in memory, and then "Kvill" and "Generate" Kvill "in memory, and finally generated" Kvill ans ", and the address of the string to the STR, This is because the "immutable" of string produces a lot of temporary variables, which is why it is recommended to use StringBuffer, because StringBuffer can be changed.

Final usage and understanding in string

Java code

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

As you can see, final is valid only for the reference "value" (that is, the memory address), which forces the reference to point only to the object that was initially pointed to, and changes its point to cause a compile-time error. Final is not responsible for the change in the object it points to.

Summarize

  A reference to the local variable data and objects (String, Array, object, and so on) that are used to hold some raw data types in the stack. But not the object content

The heap contains objects created using the New keyword.

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

java+ the difference between memory allocation and variable storage location

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.