In-depth explanation of Java core Java memory allocation principles
Although stacks, stacks, and constant pools belong to the same Java memory allocation operation region, their applicability and functions are quite different. This article will go deep into the Java core and explain in detail the knowledge of Java memory allocation.
Java memory allocation and management is one of the core technologies of Java. We have previously introduced Java memory management and Memory leakage and Java garbage collection knowledge. Today we go deep into Java core again, this section describes Java's knowledge about memory allocation in detail. Java generally involves the following areas in memory allocation:
◆ Register: we cannot control it in the program
◆ Stack: stores basic types of data and object references, but the object itself is not stored in the stack, but stored in the heap.
◆ Heap: stores data generated with new
◆ Static domain: static members defined by static in objects
◆ Constant pool: stores constants.
◆ Non-RAM storage: Permanent storage space such as hard disk
Stack in Java Memory Allocation
Variable data of some basic types defined in functions and referenced variables of objects are allocated in the function stack memory.
When a variable is defined in a code block, Java allocates memory space for the variable in the stack. After the variable exits the scope, java will automatically release the memory space allocated for the variable, and the memory space can be used for another use immediately.
Heap in Java Memory Allocation
Heap memory is used to store objects and arrays created by new. The memory allocated in the heap is managed by the Java Virtual Machine's automatic garbage collector.
After an array or object is generated in the heap, you can define a special variable in the stack so that the value of this variable in the stack is equal to the first address of the array or object in the heap memory, the variable in the stack becomes the referenced variable of the array or object. The referenced variable is equivalent to an array or an object name. Later, you can use the referenced variable in the stack in the program to access the array or object in the heap. The referenced variable is equivalent to an array or object name.
The referenced variable is a common variable. It is assigned to the stack during definition. The referenced variable is released after the program runs out of its scope. Arrays and objects are allocated in the heap. Even if the program runs outside the code block where the new statement is used to generate arrays or objects, the memory occupied by arrays and objects is not released, arrays and objects become junk only when no referenced variable points to it. They cannot be used, but still occupy the memory space, the garbage collector collects (releases) the garbage collector at an uncertain time ). This is also the reason why Java accounts for memory usage.
In fact, the variables in the stack point to the variables in the heap memory. This is the pointer in Java!
Constant pool)
A constant pool refers to some data that is determined during the compilation period and stored in the compiled. class file. Besides containing the basic types (such as int and long) defined in the Code and the constant values (final) of the object type (such as String and array) it also contains some symbolic references that appear in the form of text, such:
◆ Full qualified names of classes and interfaces;
◆ Field name and descriptor;
◆ Method and name and descriptor.
The virtual machine must maintain a constant pool for each mounted type. A constant pool is an ordered set of constants used for this 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 the constant pool. The constant pool in JVM exists in the memory as a table. For the String type, there is a fixed-length CONSTANT_String_info table to store the text String value. Note: this table only stores the text string value, not the symbol reference. Here, we should have a clear understanding of the storage location of string values in the constant pool.
During program execution, the constant pool is stored in the Method Area rather than in the heap.
Stack and stack
The Java heap is a runtime data zone and class (the object allocates space from it. These objects are created using commands such as new, newarray, anewarray, and multianewarray. They do not need program code to be explicitly released. The heap is responsible for garbage collection. The advantage of the heap is that the memory size can be dynamically allocated, and the lifetime does not have to be told in advance because the heap dynamically allocates memory at runtime, the Java Garbage Collector automatically collects the unused data. However, the slow access speed is due to the need to dynamically allocate memory during runtime.
The advantage of stack is that the access speed is faster than that of stack, second only to register, and stack data can be shared. However, the disadvantage is that the data size and lifetime in the stack must be fixed, and there is a lack of flexibility. The stack mainly stores some basic types of variable data (int, short, long, byte, float, double, boolean, char) and object handle (reference ).
A very important feature of stacks is that data in stacks can be shared. Suppose we define both:
1. int a = 3;
2. int B = 3;
The compiler first processes int a = 3. First, it creates a reference with the variable a in the stack, and then finds whether the value 3 in the stack exists. If no value is found, store 3 and point a to 3. Then process int B = 3. After the referenced variable of B is created, B is directed to 3 because there is already 3 in the stack. In this way, both a and B point to 3 at the same time.
At this time, if a is set to 4 again, the compiler will re-search whether there are 4 values in the stack. If not, it will store 4 and make a point to 4; if yes, direct a to this address. Therefore, changing the value of a does not affect the value of B.
Note that the sharing of data is different from the sharing of two objects pointing to one object at the same time, because the modification of a does not affect B, which is completed by the compiler, it facilitates space saving. A variable referenced by an object modifies the internal state of the object, which affects the variable referenced by another object.
String is a special packaging data. Available:
1. String str = new String (abc );
2. String str = abc;
The first method is to use new () to create an object, which is stored in the heap. Each call creates a new object. The second is to first create a String class object reference variable str in the stack, and then use the symbol reference to find out if there is any abc in the String constant pool. If not, store abc in the String constant pool and point str to "abc". If "abc" exists, str points to "abc" directly ".
Use the equals () method to compare the values in a class. Use the = method to test whether the references of the two classes point to the same object. The example below illustrates the above theory.
3. String str1 = abc;
4. String str2 = abc;
5. System. out. println (str1 = str2); // true
It can be seen that str1 and str2 point to the same object.
6. String str1 = new String (abc );
7. String str2 = new String (abc );
8. System. out. println (str1 = str2); // false
The new method is used to generate different objects. Each time one is generated.
Therefore, the second method is used to create multiple "abc" strings, and only one object exists in the memory. this method is advantageous and saves memory space. at the same time, it can improve the program running speed to a certain extent, because the JVM will automatically decide whether to create a new object based on the actual situation of the data in the stack. For the code of String str = new String (abc);, a new object is created in the heap, regardless of whether the String value is equal, and whether it is necessary to create a new object, this increases the burden on the program.
On the other hand, note that when we define a class using a format such as String str = abc;, we always take it for granted that the str object of the String class is created. Worry trap! The object may not be created! Instead, it may only point to a previously created object. Only by using the new () method can a new object be created every time.
Because of the immutable property of the String class, when the String variable needs to change its value frequently, you should consider using the StringBuffer class to improve program efficiency.
1. First, String does not belong to eight basic data types. String is an object. Because the default value of an object is null, the default value of String is also null, but it is a special object and has some features that other objects do not have.
2. Both new String () and new String (") declare a new null String, which is a null String or not null;
3. String str = "kvill"; String str = new String ("kvill ")
Example:
9. String s0 = kvill;
10. String s1 = kvill;
11. String s2 = kv + ill;
12. System. out. println (s0 = s1 );
13. System. out. println (s0 = s2 );
Result:
True
True
First, we need to know that Java will ensure that a String constant has only one copy.
Because "kvill" in s0 and s1 in the example are string constants, they are determined during the compilation period, so s0 = s1 is true; "kv" and "ill" are both string constants. When a character string is connected by multiple string constants, it must be a String constant, so s2 is also parsed as a String constant during compilation, so s2 is also a reference of "kvill" in the constant pool. So we can get s0 = s1 = s2; the String created with new String () is not a constant and cannot be determined during the compilation period, so new String () the created strings are not placed in the constant pool. They have their own address space.
Example:
14. String s0 = kvill;
15. String s1 = new String (kvill );
16. String s2 = kv + new String (ill );
17. System. out. println (s0 = s1 );
18. System. out. println (s0 = s2 );
19. System. out. println (s1 = s2 );
Result:
False
False
False
In Example 2, s0 is still the kvill application in the constant pool. s1 is a reference to the new object "kvill" created during runtime because it cannot be determined during the compilation period, s2 is also an application that creates the "kvill" object because it has a new String ("ill") in the second half and cannot be determined during the compilation period; if you understand this, you will know why this result is obtained.
4. String. intern ():
Another note: the constant pool exists in the. class file and is loaded by JVM at runtime and can be expanded. The intern () method of String is a method to expand the constant pool. When a String instance str calls the intern () method, Java checks whether the constant pool has the same Unicode String constant, if yes, its reference is returned. If no, a string with Unicode equal to str is added to the regular pool and Its Reference is returned.
Example:
20. String s0 = kvill;
21. String s1 = new String (kvill );
22. String s2 = new String (kvill );
23. System. out. println (s0 = s1 );
24. System. out. println (**********);
25. s1.intern ();
26. s2 = s2.intern (); // assign the kvill reference in the constant pool to s2.
27. System. out. println (s0 = s1 );
28. System. out. println (s0 = s1.intern ());
29. System. out. println (s0 = s2 );
Result:
False
False // although s1.intern () is executed, its return value is not assigned to s1
True // indicates that s1.intern () returns a kvill reference from the constant pool.
True
Finally, let me get rid of another misunderstanding: someone says, "Use String. the intern () method can save a String class to a global String table. If a Unicode String with the same value is already in this table, this method returns the address of an existing String in the table, if there is no String with the same value in the table, register the address in the table. "If I understand this global String table as a constant pool, his last sentence is, "If there is no string with the same value in the table, register your address in the table" is incorrect:
Example:
30. String s1 = new String (kvill );
31. String s2 = s1.intern ();
32. System. out. println (s1 = s1.intern ());
33. System. out. println (s1 ++ s2 );
34. System. out. println (s2 = s1.intern ());
Result:
False
Kvill
True
In this class, we do not have a "kvill" constant, so there is no "kvill" in the constant pool at the beginning. When we call s1.intern () then, a new "kvill" constant is added to the constant pool. The original "kvill" that is not in the constant Pool still exists, it is not "registering your own address to the constant pool.
If s1 = s1.intern () is false, 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 =:
In simple terms, this is to compare whether the Unicode sequence of the two strings is equivalent. If the two strings are equal, true is returned, and = is to compare whether the addresses of the two strings are the same, that is, whether it is a reference to the same string.
6. the String is immutable.
This is a lot more important. You only need to know that once the String instance is generated, it will not change, for example: string str = "kv" + "ill" + "" + "ans"; there are four String constants, first, "kv" and "ill" generate "kvill" in memory, and then "kvill" and "generate" kvill "in memory, finally, the "kvill ans" is generated, and the address of this String is assigned to str, because the String's "immutable" produces many temporary variables, this is the reason why StringBuffer is recommended, because StringBuffer can be changed.
The following are some FAQs related to String:
Usage and understanding of final in String
Final StringBuffer a = new StringBuffer (111 );
Final StringBuffer B = new StringBuffer (222 );
A = B; // This sentence cannot be compiled
Final StringBuffer a = new StringBuffer (111 );
A. append (222); // compiled
It can be seen that final is only valid for the referenced value (that is, the memory address). It forces the reference to point only to the object initially pointed to. changing its direction will lead to a compilation error. Final is not responsible for the changes to the objects it points.
Several examples of String constant pool problems
The following is a comparative analysis and understanding of several common examples:
1. String a = a1;
2. String B = a + 1;
3. System. out. println (a = B); // result = true
4. String a = atrue;
5. String B = a + true;
6. System. out. println (a = B); // result = true
7. String a = a3.4;
8. String B = a + 3.4;
9. System. out. println (a = B); // result = true
Analysis: For the + number connection of a String constant, during the program compilation period, the JVM optimizes the + connection of the constant string to the value after the connection. Take a + 1 as an example, after optimization by the compiler, it is already a1 in the class. The value of its String constant is determined during compilation, so the final result of the above program is true.
10. String a = AB;
11. String bb = B;
12. String B = a + bb;
13. System. out. println (a = B); // result = false
Analysis: JVM for string reference, because there is a string reference in the string + connection, the referenced value cannot be determined during program compilation, that is, a + bb cannot be optimized by the compiler. It is dynamically allocated only during the running period and assigned the new connection address to B. Therefore, the result of the above program is false.
14. String a = AB;
15. final String bb = B;
16. String B = a + bb;
17. System. out. println (a = B); // result = true
Analysis: The only difference from [3] Is that the bb string is decorated with final. For final modified variables, it is parsed as a local copy of a constant value during compilation and stored in its own constant pool or embedded in its byte code stream. Therefore, the effect of a + bb is the same as that of a + B. Therefore, the result of the above program is true.
18. String a = AB;
19. final String bb = getBB ();
20. String B = a + bb;
21. System. out. println (a = B); // result = false
22. private static String getBB (){
23. return B;
24 .}
Analysis: JVM cannot determine the value of bb referenced by strings during compilation. After calling a method during the runtime, it dynamically connects the return value of the method to a and assigns the address B, therefore, the result of the above program is false.
The above four examples show that:
String s = a + B + c;
It is equivalent to String s = abc;
String a =;
String B = B;
String c = c;
String s = a + B + c;
This is different. The final result is equal:
25. StringBuffer temp = new StringBuffer ();
26. temp. append (a). append (B). append (c );
27. String s = temp. toString ();
From the above analysis results, it is not difficult to infer the cause of the inefficiency of the String using the join operator (+), such as the Code:
28. public class Test {
29. public static void main (String args []) {
30. String s = null;
31. for (int I = 0; I <100; I ++ ){
32. s + =;
33 .}
34 .}
35 .}
Every time you do the plus sign (+), a StringBuilder object is generated and then thrown away after append. When the next loop arrives, A StringBuilder object is generated again, and then the append string is generated. The loop ends until the end. If we directly use the StringBuilder object for append, we can save N-1 time to create and destroy objects. Therefore, for applications that require string connection in a loop, the append operation is generally performed using the StringBuffer or StringBulider object.
The intern method of the String object is described as follows:
36. public class Test4 {
37. private static String a = AB;
38. public static void main (String [] args ){
39. String s1 =;
40. String s2 = B;
41. String s = s1 + s2;
42. System. out. println (s = a); // false
43. System. out. println (s. intern () = a); // true
44 .}
45 .}
Java is used here as a constant pool problem. For the s1 + s2 operation, a new object is actually created in the heap, and s stores the content of the new object in the heap space, the values of s and a are not equal. When the s. intern () method is called, the address value of s in the constant pool can be returned. Because the value of a is stored in the constant pool, the values of s. intern and a are equal.
Summary
The stack stores local variable data of some original data types and references of objects (String, array. Object, etc.) but does not store object content.
Heap stores the objects created with the new keyword.
A string is a special packaging class. Its reference is stored in the stack, and the object content must be determined according to the creation method (constant pool and heap ). some have been created in the compilation phase and stored in the regular string pool, while others are created during runtime. store the new keyword in the heap.
· A deep understanding of Java Polymorphism
Http://developer.51cto.com wrewrter csdn I want to comment ()
This document describes Java polymorphism through examples and explanations of several classes. The concept of Java polymorphism can also be described as "one interface and multiple methods ".
I have read some articles about Java polymorphism. I have read some of my own ideas for your reference. It is not necessarily correct. Thank you for your criticism.
(1) Related Classes
1. class ...{
2. public String show (D obj )...{
3. return (A and D );
4 .}
5. public String show (A obj )...{
6. return (A and );
7 .}
8 .}
9. class B extends ...{
10. public String show (B obj )...{
11. return (B and B );
12 .}
13. public String show (A obj )...{
14. return (B and );
15 .}
16 .}
17. class C extends B ...{}
18. class D extends B ...{}
(2) Question: What are the output results below?
19. A a1 = new ();
20. A a2 = new B ();
21. B B = new B ();
22. C c = new C ();
23. D d = new D ();
24. System. out. println (a1.show (B); ①
25. System. out. println (a1.show (c); ②
26. System. out. println (a1.show (d); ③
27. System. out. println (a2.show (B); ④
28. System. out. println (a2.show (c); ⑤
29. System. out. println (a2.show (d); ⑥
30. System. out. println (B. show (B); 7
31. System. out. println (B. show (c); then
32. System. out. println (B. show (d); then
(3) answer
① A and
② A and
③ A and D
④ B and
⑤ B and
⑥ A and D
7. B and B
Between B and B
Between A and D
(4) Analysis
① ③ It is easy to understand and generally does not cause errors. ④ It's a bit confused. Why isn't B and B output ?!! Let's review the polymorphism.
Runtime polymorphism is one of the most powerful mechanisms for code reuse in object-oriented programming. The concept of Java polymorphism can also be said to be "one interface, multiple methods ". Dynamic Method scheduling is the basis for Java Implementation of Runtime polymorphism. It is a mechanism for calling overloaded methods at runtime rather than during compilation.
Overriding and Overloading are different manifestations of Java polymorphism. Overriding is a manifestation of the polymorphism between the parent class and the Child class, and Overloading is a manifestation of the polymorphism in a class. If a subclass defines a method with the same name and parameter as its parent class, we say this method is overwritten ). When a subclass object uses this method, it calls the definition in the subclass. For it, the definition in the parent class is "blocked. If multiple methods with the same name are defined in a class, they may have different numbers of parameters or different parameter types, it is called Overloading ). The Overloaded method can change the type of the returned value. Overriding and Overloading are different manifestations of Java polymorphism. Overwriting Overriding is a manifestation of the polymorphism between the parent class and the Child class, and Overloading is a manifestation of Java polymorphism in a class. If a subclass defines a method with the same name and parameter as its parent class, we say this method is overwritten ). When a subclass object uses this method, it calls the definition in the subclass. For it, the definition in the parent class is "blocked. If multiple methods with the same name are defined in a class, they may have different numbers of parameters or different parameter types, it is called Overloading ). The Overloaded method can change the type of the returned value.
When a superclass object references a variable to reference a subclass object, the type of the referenced object, instead of the type of the referenced variable, determines who calls the member method, however, the called method must have been defined in the superclass, that is, the method covered by the quilt class. (However, if the superclass is forced to be converted into a subclass, you can call the method newly added to the subclass but the superclass does not have .)
Now, let's get down to it first! In fact, this involves the priority of method calls. The priority is from high to low: this. show (O), super. show (O), this. show (super) O), super. show (super) O ). Let's see how it works.
For example, ④, a2.show (B), a2 is A reference variable, type is A, this is a2, B is an instance of B, so it finds the show (B obj) method in Class A and does not find it, so it searches for A's super (superclass), and A does not have A superclass, so it goes to the third priority this. show (super) O), this is still a2, Here O is B, (super) O is (super) B is, therefore, it finds the show (A obj) method in Class A. Class A has this method, but because a2 references an object of Class B, B overrides the show (A obj) method of A, so it is eventually locked to show (A obj) of Class B, and the output is B and ".
For example, accept, B. show (c), B is a reference variable, type is B, this is B, c is an instance of C, so it goes to class B to find the show (C obj) method, not found. I switched to super class A of B and found it in class A, so I also switched to the third priority this. show (super) O), this is B, O is C, (super) O is (super) C is B, so it finds show (B obj) in B) as B References an object of Class B, it is directly locked to show (B obj) of Class B and output to B and B ".
According to the above method, other results can be obtained correctly.
The problem persists. Now let's take a look at how the above analysis process shows the meaning of the blue font sentence. It said: When a super-Class Object references a variable to reference a subclass object, the type of the referenced object rather than the type of the referenced variable determines who calls the member method, however, the called method must have been defined in the superclass, that is, the method covered by the quilt class. Take a2.show (B) for example.
A2 is A reference variable of type A, which references an object of B. Therefore, B determines which method to call. Therefore, you should call show (B obj) of B to output B and B. But why is the result of the preceding analysis inconsistent ?! The problem is that we should not ignore the second half of the blue font, which specifically states that the called method must be defined in the superclass, that is, the method of quilt coverage. Is show (B obj) in B defined in superclass? No! That's not to mention being covered. In fact, this sentence hides a piece of information: it is still determined based on the priority of the method call. It finds show (A obj) in Class A. If subclass B does not overwrite the show (A obj) method, it calls show (A obj) of Class) (Because B inherits A, although it does not cover this method, it inherits this method from super class A. In A sense, it is determined by B to call the method, only the method is implemented in A); now subclass B overwrites show (A obj), so it is eventually locked to show (A obj) of B ). This is the meaning of the sentence. Here, we can clearly understand the Java polymorphism.