Java Basics-Stack and heap, static, final modifier, inner class, and Java memory allocation

Source: Internet
Author: User
Tags format definition modifiers variable scope

Java Basics-Stack and heap, static, final modifier, inner class, and Java memory allocation (RPM)
Java Stack and heap
Heap: Random in order

Stack: LIFO (last-in/first-out).

The Java heap is a run-time data area in which the objects of the class 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 variables (int, short, long, byte, float, double, Boolean, char) and object handle.

1. Stacks and heaps (heap) are places that Java uses to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set up stacks or heaps.

2. The advantage of the stack is that the access speed is faster than the heap, second only to the registers directly in the CPU. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. In addition, the stack data can be shared, see 3rd. The advantage of the heap is that the memory size can be allocated dynamically, and the lifetime does not have to tell the compiler beforehand that the Java garbage collector automatically collects the data that is no longer in use. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time.

3. There are two kinds of data types in Java.

One is the basic type (primitive types), a total of 8 kinds, namely int, short, long, byte, float, double, Boolean, char (note, and no basic type of string). The definition of this type is through such as int a = 3; Long B = 255L; the form to be defined, called an automatic variable. It is worth noting that the automatic variable is a literal value, not an instance of a class, that is not a reference to a class, there is no class here. such as int a = 3; Here A is a reference to the int type, pointing to the literal value of 3. The data of these literals, due to the size of the known, the lifetime of the known (these values are fixed in a program block, the program block exits, the field value disappears), for the sake of speed, it exists in the stack.

In addition, the stack has a very important particularity, is that there is data in the stack can be shared. Let's say we define both:
Copy content to Clipboard 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 looks for an address with a literal value of 3, finds an address that holds the literal value of 3, and then points A to the address of 3. then the int b = 3 is processed, and after the reference variable of B is created, B is pointed directly to the address of 3 because there are already 3 literals in the stack. In this case, A and B both point to 3.

It is particularly important to note that the reference to this literal is different from the reference to the class object. Assuming that a reference to two class objects points to an object at the same time, if an object reference variable modifies the internal state of the object, then another object reference variable will immediately reflect that change. Conversely, modifying its value by a reference to a literal value does not result in another case where a reference to that literal is changed. As in the example above, we define the value of a and B and then make a=4; then B will not be equal to 4 or equal to 3. Inside the compiler, when it encounters A=4, it will re-search the stack for a literal value of 4, and if not, re-open the value of the address 4, and if so, point a directly at the address. Therefore the change of a value does not affect the value of B.

The other is the wrapper class data, such as Integer, String, double, and so on, the corresponding basic data types are wrapped up class. These classes of data all exist in the heap, and Java uses the new () statement to tell the compiler that it is dynamically created as needed at run time, so it is more flexible, but the disadvantage is that it takes more time. 4. String is a special wrapper class data. That is, it can be created in the form of string str = new String ("abc"), or in the form of string str = "abc" (In contrast, before JDK 5.0, you have never seen an expression of integer i = 3; because class and literal literals are not can be generic except for string. In JDK 5.0, this expression is possible! Because the compiler is converting the integer i = new Integer (3) in the background. The former is the process of creating a canonical class, that is, in Java, everything is an object, and the object is an instance of the class, all created in the form of new (). Some classes in Java, such as the DateFormat class, can return a newly created class through the class's getinstance () method, which seems to violate this principle. actually otherwise The class uses a singleton pattern to return an instance of the class, except that the instance is created inside the class through new (), and getinstance () hides this detail from the outside. So why is the case in string str = "abc", not created by new (), a violation of the above principle? Not really.

5. About the internal work of string str = "abc". Inside Java, this statement is translated into the following steps:

(1) First define an object reference variable named str to the String class: String str;

(2) in the stack to find whether there is a value of "ABC" address, if not, then open a store with a literal "ABC" address, then create a new String Class object O, and the string value of O point to the address, and in the stack next to this address note the referenced object o. If you already have an address with a value of "ABC", look for the object o and return the address of O.

(3) Point Str to the address of the object o.

It is important to note that the string values in the generic string class are directly stored values. But like string str = "abc"; In this case, the string value is a reference to the data in the existing stack!

To better illustrate this problem, we can verify it by following several code.
Copy content to Clipboard code:
String str1 = "abc";
String str2 = "abc";
System.out.println (STR1==STR2); True
Note that we do not use Str1.equals (STR2) in this way, as this will compare the values of two strings for equality. = = number, as described in the JDK, returns true only if two references point to the same object. And what we're looking at here is whether str1 and str2 all point to the same object.
The result shows that the JVM created two references str1 and str2, but only one object was created, and two references pointed to the object.

Let's go further and change the above code to:
Copy content to Clipboard code:
String str1 = "abc";
String str2 = "abc";
str1 = "BCD";
System.out.println (str1 + "," + str2); BCD, ABC
System.out.println (STR1==STR2); False
This means that the change in the assignment has led to a change in the class object reference, and str1 points to another new object! And str2 still points to the original object. In the example above, when we change the value of str1 to "BCD", the JVM discovers that there is no address for that value in the stack, opens up this address and creates a new object whose string value points to the address.

In fact, the string class is designed to be immutable (immutable) classes. If you want to change its value, yes, but the JVM silently creates a new object at run time based on the new value, and then returns the address of the object to the reference of the original class. This creation process is entirely automatic, but it takes up more time. In the environment that is more sensitive to time requirements, it will have some adverse effects.

Then modify the original code:
Copy content to Clipboard code:
String str1 = "abc";
String str2 = "abc";

str1 = "BCD";

String STR3 = str1;
System.out.println (STR3); Bcd

String STR4 = "BCD";
System.out.println (str1 = = STR4); True
STR3 a reference to this object points directly to the object that str1 points to (note that STR3 does not create a new object). When str1 changes its value, it creates a reference str4 of string and points to the new object created by str1 modifying the value. It can be found that this time STR4 also did not create a new object, thereby re-sharing the data in the stack.

Let's look at the following code again.
Copy content to Clipboard code:
String str1 = new String ("abc");
String str2 = "abc";
System.out.println (STR1==STR2); False creates two references. Two objects were created. Two references point to a different two objects, respectively.

String str1 = "abc";
String str2 = new String ("abc");
System.out.println (STR1==STR2); False
Two references were created. Two objects were created. Two references point to a different two objects, respectively.

The above two code shows that as long as new () is used to create the object, it is created in the heap, and its string is stored separately, even if the data in the stack is the same, it is not shared with the data in the stack.

6. The value of the data type wrapper class cannot be modified. Not only the value of the string class cannot be modified, but all data type wrapper classes cannot change their internal values.


(1) When we use a format definition class such as String str = "ABC", we always want to think of course that we created the object str of the String class. Worry about traps! The object may not have been created! The only certainty is that a reference to the string class was created. As to whether the reference is pointing to a new object, it must be considered in terms of context, unless you create a new object with a prominent way through the new () method. Therefore, it is more accurate to say that we have created a reference variable to the object of the String class str, which refers to a variable that points to a string class with the value "ABC". Being aware of this is helpful in troubleshooting bugs that are difficult to find in a program.

(2) The use of string str = "abc", in a way that can improve the speed of the program to a certain extent, because the JVM will automatically based on the actual data in the stack to determine whether it is necessary to create a new object. 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. This idea should be the idea of the meta-mode, but it is not known whether the internal JDK implements this pattern.

(3) Use the Equals () method when comparing the values in the wrapper class, and use the = = when testing whether the references to the two wrapper classes point to the same object.

(4) Because of the immutable nature of the string class, you should consider using the StringBuffer class when the string variable needs to change its value frequently to improve program efficiency.

Stacks (stack) and heap (heap) "Go-to-pick" in Java
Stacks (stack) and heaps (heap)

(1) Strategies for memory allocation

According to the compiling principle, there are three kinds of strategies for memory allocation when the program runs, which are static, stacked, and stacked.

Static storage allocation is the ability to determine at compile time the storage space requirements for each data target at run time, so that they can be allocated a fixed amount of memory at compile time. This allocation policy requires that the existence of mutable data structures (such as variable groups) not be allowed in the program code, and that nested or recursive structures are not allowed to appear. Because they all cause the compiler to not be able to calculate the exact storage space requirements.

A stack storage allocation can also be called dynamic storage allocation, which is implemented by a stack-like run stack. In contrast to static storage allocation, in a stack storage scenario, the requirements for the data area are completely unknown at compile time, only to be known when running, but when the rules are entered into a program module You must know the size of the data area required by the program module to allocate memory for it. As with the stack we are familiar with in the data structure, the stack storage allocation is distributed according to the principle of advanced post-out.

Static storage allocation requires that the storage requirements of all variables be known at compile time, and that the stack storage allocation requires that all storage requirements be known at the entrance of the process, while the heap storage allocation is specifically responsible for the memory allocation of the data structures that the storage requirements cannot be determined at compile-time or at runtime module entrances. such as variable-length strings and object instances. The heap consists of large chunks of available or free blocks, and the memory in the heap can be allocated and freed in any order.

(2) Comparison of Heap and stack

The above definition is summarized from the compiling principle of the textbook, in addition to static storage allocation, it is very inflexible and difficult to understand, the following aside static storage allocation, centralized comparison heap and stack:

From the heap and the function of the stack and the role of the popular comparison, the heap is mainly used to store objects, the stack is mainly used to execute the program. And this difference is mainly due to the characteristics of the heap and stack:

In programming, for example, C + +, all method calls are made through stacks, all local variables, and formal parameters that allocate memory space from the stack. It's actually not an assignment, just up the top of the stack, like a conveyor belt in the factory (conveyor belt), stack pointer will automatically guide you to where you put things, All you have to do is put things down. When you exit a function, you can destroy the contents of the stack by modifying the stack pointer. This mode is the fastest, of course, to run the program. It is important to note that when allocating a data area for a program module that is about to be called, The size of this data area should be known in advance, but it is said that although the allocation is carried out at the time of the program running, the size of the allocation is determined, unchanged, and the "size of how much" is determined at compile time, not at runtime.

Heap is when the application is running to request the operating system to allocate its own memory, because of the memory allocation from the operating system management, so the allocation and destruction of time, so the efficiency of the heap is very low. But the advantage of the heap is that the compiler does not have to know how much storage space to allocate from the heap. It is also not necessary to know how long the stored data will stay in the heap, so there is greater flexibility in storing the data with the heap. In fact, object-oriented polymorphism, heap memory allocation is essential, because the required storage space for polymorphic variables can only be determined after the object is created at run time. In C + +, when you require an object to be created, you only need to compile the relevant code with the new command. When you execute the code, the data is saved automatically in the heap. Of course, to achieve this flexibility, there is a certain price to pay: it will take longer to allocate storage space in the heap! This is the reason we have just said that the inefficiency of the reasons, it seems that comrade Lenin said good, people's advantages are often also human shortcomings, human shortcomings are often also the advantages of people (halo ~).

(3) Stacks and stacks in the JVM

The JVM is a stack-based virtual machine. The JVM allocates a stack for each newly created thread. In other words, for a Java program, it runs through the operation of the stack. The stack holds the state of the thread in frames. The JVM operates on the stack in only two ways: stack and stack operations in frames.

We know that the method that a thread is executing is called the current method of this thread. We may not know that the frame used by the current method is called the current frame. When a thread activates a Java method, the JVM presses a new frame into the Java stack of threads. This frame naturally becomes the current frame. During the execution of this method, this frame is used to hold parameters, local variables, intermediate calculation procedures, and other data. This frame is similar to the concept of the activity record in the compilation principle.

From this allocation mechanism in Java, the stack can be understood as a stack is a storage area that the operating system establishes for a process, or a thread (a thread in a multithreaded operating system) for this thread, which has an advanced post-out feature.

Each Java application uniquely corresponds to a single JVM instance, and each instance uniquely corresponds to one heap. All instances or arrays of classes created by the application in the run are placed in this heap and shared by all threads of the application. Unlike C + +, allocating heap memory is automatically initialized in Java. The storage space for all objects in Java is allocated in the heap, but the reference to this object is allocated on the stack, that is, allocating memory from two places when an object is built, memory allocated in the heap actually establishes the object, and the memory allocated on the stack is just a pointer to the heap object (reference) Only.

Static, final modifier, inner class, and Java memory allocation

static modifier
The static modifier can be used with properties, methods, and inner classes to represent static. Static variables and static methods in a class can be used with the class name and do not need to create an object of a class to access the static members of the class, so the static modified variable is also called a "class variable."

Memory allocation of the static property

In a class, a static variable will have only one memory space, although there are multiple instances of the class, but this static variable in these class instances will share the same memory space.

Static variables are initialized when the class is loaded, that is, whenever a class is loaded, whether or not a static variable is used.
Basic rules of Static
• Static methods for a class can only access static properties
• A static method of a class cannot call a non-static method directly
• Static properties and methods can use the class name plus "." If access control permission is allowed. , you can also use the instance plus "." The way to call
• The current object does not exist in the static method and therefore cannot be used or super
• Static methods cannot be overridden by non-static methods
• The construction method does not allow the declaration of static
Note that non-static variables are limited to instances and can only be accessed through instance references.
Static initializers-static blocks
A static initializer is a static block that exists outside of a method in a class and executes only once when the class is loaded, and is typically used to initialize static class properties.

Final modifier
When you declare classes, properties, and methods in Java, you can use the keyword final to decorate the final marked component with an end-state feature, which indicates the ultimate meaning.
The specific rules of final
final tagged classes cannot be inherited
final tagged methods cannot be overridden by a quilt class
Final tags (member or local variables) are constants and can only be assigned once
The member variable of the final tag must be assigned at the same time as the declaration, and if it is not assigned at the time of declaration, then there is only one chance to assign the value, and it can only be assigned explicitly in the constructor method before using the
Local variables of the final tag can only be declared without assignment, and then a one-time assignment
final is generally used to mark the functions, implementations or values that cannot be arbitrarily changed to avoid misuse.
If a variable of a reference type (that is, the type of any class) is marked as final, the variable cannot point to any other object, but it can change the contents of the object, because only the reference itself is final.

Inner class
  defines another class within one class (or method, statement block), which is called an inner class, sometimes called a nested class.
  Inner class features
the     inner class can represent a logical dependency, while for other classes you can control the internal classes from being invisible to the outside, and so on
    The member variable scope of the outer class is the entire outer class, including the inner class, but the outer class cannot access the private member of the inner class
    logically related classes can be together and can effectively implement information hiding
   The   inner class can access members of the external class directly, and with this implementation multiple inheritance
    is compiled, and the inner class is compiled into a separate class with the name Outclass$inclass the form

Inner classes can be divided into four types of
    class level: member, static modifier
    Object level: Member, normal, no static modifier
     local inner class: local
    anonymous level: Local
  Member-based inner class basic rules
    can have a variety of modifiers, you can use 4 kinds of permissions, Static, final, abstract define
    If there is a static qualification, it is class-level, or object-level. Class-level can be accessed directly through an external class, and object-level objects need to be outside the
    class cannot have the same name
    non-static inner classes cannot declare any static members
    Inner classes can be called to each other
  the access
    inner class of the member inner class accesses the members of the Outer class object, the syntax is:
       Outer class name. This. Property
    When an inner class is used, the outer class object is called by the ". New" operator to construct the inner class object.
  When using a method defined in a non-static inner class in another external class, create an object of the outer class, create an object of the inner class related to the outer class, and then invoke the method of the inner class. The
  static inner class is equivalent to the static component of its outer class, which does not have dependencies between its objects and external class objects, so it can be created directly.
  Because an inner class can directly access the components of its outer class, it also causes a naming conflict when an inner class has a property or method with the same name in its outer class. Therefore, it is necessary to specify when multiple layers are called.

Local classes are classes that are defined in a block of code and are visible only in the code block in which they are defined.
The local class has several important features:
• Visible only in blocks of code that define them
• You can use any local final variable in the code block in which they are defined (note: The local class (which can also be a local inner class/anonymous inner class, and so on) uses the variables of the outer class, which is intended to be consistent with the object in the local class and this variable object in the outer classes. However, if this variable is not a final definition, it may be modified externally, resulting in inconsistent variable object states of the internal and external classes, so that such variables must be defined in the outer class with the final prefix)
• Local classes are not static and static members cannot be defined inside
• Local classes cannot be decorated with public, private, protected, only using the default
• The local class can be abstract

An anonymous inner class is a special form of a native inner class, that is, an inner class without a class name, and a specific class implementation is written in this inner class.
Rules for anonymous classes
• Anonymous classes have no construction method
• Anonymous classes cannot define static members
• Anonymous classes cannot be modified with 4 permissions, static, final, abstract
• Only one anonymous class instance can be created

memory allocation in Java
Java Program runtime memory structure is divided into: Method area, stack memory, heap memory, the local method stack several.
The method area holds the loaded class data information, including:
• Basic information: The fully qualified name of each class, the fully qualified name of the direct superclass for each class, whether the class is a class or an interface, an access modifier of that type, an ordered list of fully qualified names for the direct hyper-interface.
• Details of each loaded class: Run a constant pool, field information, method information, static variables, references to class ClassLoader, and references to class classes.
Stack memory
The Java stack memory consists of a local variable area, an operand stack, a frame data area, and a frame that holds the call state of the local method (including the parameters of the method call, local variables, intermediate results ...). )。
Heap Memory
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.
Local Method Stack Memory
Java uses the Java local interface Jni (Java Native Interface) to invoke programs written in other languages, and in Java the Native modifier is used to describe a method as a local method.
memory allocation of string
String is a special wrapper class data, because the value of the string class is immutable, when a string variable needs to change its value frequently, consider using the StringBuffer or StringBuilder class to improve program efficiency.

Java memory allocation, management summary

Transferred from:

First, there are several issues at the conceptual level:

What kinds of memory structures are run in Java?
Why do you design stack separation in Java?
How is data sharing implemented in Java Multi-threading?
What is the basis of Java reflection?
Then the application level:

What is the difference between a reference type variable and an object?
What is the case with a local variable, and under what circumstances is a member variable?
How do arrays initialize? How do I allocate memory during the process of declaring an array?

Declares an array of primitive types and declarations of reference types, and when initialized, what are the extents of the memory allocation mechanism?

Under what circumstances is our approach designed to be static, and why

Run-time memory structure in Java

1.1 Method Area:

A method area is a memory logical area allocated by the system that is used by the JVM to store type information (the description of the class) when it loads the class file.

The information stored in the method area includes:

Basic information about the 1.1.1 class:

Fully qualified name of each class
Fully qualified name of the direct superclass for each class (constrained type conversions)
Whether the class is a class or an interface
Access modifiers of this type
Ordered list of fully qualified names for direct hyper-interfaces

1.1.2 More information about the loaded class:

To run a constant-rate pool:

In the method area, each type corresponds to a constant pool that holds all the constants used for that type, and the constant pool stores such as literal strings, final variable values, class names, and method name constants. They are accessed in an array form through an index, which is a bridge between external calls and classes and types of objects. (It may be a normal string, then parsed by a constant pool, it becomes a reference to a class)

Field information:
Field information holds information about each field declared in a class, including the name, type, and modifier of the field.

A field name refers to an instance variable or class variable of a class or interface, and a field descriptor is a string that indicates the type of field, such as private a a=null; A is a field name, A is a descriptor and private is a modifier

Method information:
The information for each method declared in the class, including the method name, the return value type, the parameter type, the modifier, the exception, and the method's bytecode.

(at compile time, the method's local variables, operand stack size and so on are determined and stored in the bytecode, when loaded, along with the class loaded into the method area.) )

At run time, the JVM obtains a symbolic reference from a constant pool, then resolves the actual address of the referenced item at run time, and finally links the code in the current class or interface with the code in the other class or interface through the fully qualified name, method, and field descriptor in the constant pool.

Static variables:
This is nothing to say, is the class variable, all instances of the class are shared, we just need to know that there is a static zone in the method area, static zone dedicated to static variables and static blocks.

A reference to the class ClassLoader: a reference to the class loader for the class.
References to class classes: The virtual machine creates a class instance for each loaded type to represent the loaded class.

Thus we can know the basis of reflection:

When the class is loaded, all the information in the method area is added, and then an instance of class is formed, representing the loaded class. All the information in the method area can be reflected by this class object. We know that an object is an instance of a class, and a class is an abstraction of an object of the same structure. Each object in the same class has the same structure (attributes) and has the same function (method), and the individual objects differ only in the value of the property.
Similarly, all of our classes are actually instances of class, and they all have the same structure-----field array, method array. The properties in each class are a specific property value of the field property, and the method is a specific property value for the methods property.

At run time, the JVM obtains a symbolic reference from a constant pool, then resolves the actual address of the referenced item at run time, and finally links the code in the current class or interface with the code in the other class or interface through the fully qualified name, method, and field descriptor in the constant pool.

1.2 Java Stack

The JVM stack is a program runtime unit that determines how the program executes, or how the data is handled.

In Java, a thread will have a thread's JVM stack corresponding to it, because the thread execution logic is obviously different, so a separate JVM stack is required to hold the thread's execution logic.

Invocation of the method:

Java stack memory, as a frame of the local method of the call state, including the method call parameters, local variables, intermediate results, etc. (methods are stored in the form of method frames in the method area), each call to a method will be the method of the method frame into the Java stack, as the current method frame. When the call finishes (returns), the frame pops up.

This means that:

Some of the basic types of variables and reference variables that are defined in the method are allocated in the stack memory of the method. When a variable is defined in a block of code, Java allocates a memory space for the variable in the stack, and when the scope of the variable is exceeded (after the execution of the method is completed), Java automatically frees the memory space allocated for that variable, which can be used immediately by another. --------also, because the variable is freed, the object that corresponds to the variable loses its reference and becomes garbage that can be recycled by the GC object.

So we can know the difference between the member variable and the local variable:

Local variables, declared inside the method, when the method runs out, memory is freed.
Member variable, as long as the object is still there, even if a method has run out.
From a system perspective, declaring local variables facilitates more efficient use of memory space (the method runs out of recycle).
Member variables can be used to share data across methods.

The composition of the Java stack memory:
The local variable area, the operand stack, the frame data area compose.
(1): The local variable area is an array in words, and each array element corresponds to the value of a local variable. When a method is called, the local variables of the method are made into an array, accessed through an index. In the case of a non-static method, add an implied reference to the This parameter, which points to the object that called the method. The static method does not have this parameter. Therefore, the object cannot invoke a static method.

Thus, we can know when the method is designed to be static, when is non-static?

As mentioned earlier, an object is an instance of a class, with the same structure for each object, but with different properties.
A static method is an object that cannot be called.
Therefore, static methods are suitable for tool methods in the tool class, which are used only to implement some functions, and do not need to produce objects, by setting the properties of the object to get different individuals.

(2): The operand stack is also an array, but is accessed through a stack operation. The so-called operands are those that are instructed to manipulate the data. When a parameter operation is required, such as A=B+C, the parameters to be manipulated will be stacked, such as the B and C stacks, which are then ejected by the action instruction, and the operation is performed. The virtual machine takes the operand stack as the workspace.
(3): Frame data area processing constant pool resolution, exception handling, etc.

1.3 Java Heap

The Java heap is a run-time data area that stores the cells of the data, and stores the new objects and arrays created by the New keyword, from which the object allocates memory.
Objects declared in the heap are not directly accessible and must be called by a variable that is declared in the stack to the reference. 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.

From this we can see the difference between a reference type variable and an object:

Declared objects are initialized in heap memory and are really used to store data. cannot be accessed directly.

Reference-type variables are stored in the stack, a symbol that refers to objects in the heap (pointers).

Heap vs. Stack comparison:
The Java heap and stack are all used to store data, so what is the difference between them? Since stacks can also store data, why design heaps?

1. From the point of view of storing data:

We have explained earlier:

A variable of the underlying type or reference type that is stored in the stack

The object or array object is stored in the heap.

In the stack, the reference variable has a size of 32 bits and a base type of 1-8 bytes.
However, the size of the object and the size of the array is dynamic, which also determines the dynamic nature of the data in the heap, because it is dynamically allocated memory at run time, the lifetime does not have to be determined at compile time, Java garbage collector will automatically take away the data that is no longer used.

2. From the perspective of data sharing:

1). In a single thread class, the data in the stack can be shared

For example we define:

Java code
int a=3;
int b=3;
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.

And if we define:

Java code
Integer a=new integer (3);//(1)
Integer b=new integer (3);//(2)
Integer a=new integer (3);//(1) Integer b=new integer (3);//(2)

At this point the execution process is: at Execution (1), a variable A is first created in the stack, then an object is instantiated in the heap memory, and the variable A is pointed to the instantiated object. At Execution (2), the procedure is similar, at which time, in heap memory, there will be two integer types of objects.

2). The sharing of data between the threads of the process is implemented through the heap

So, how is our data sharing implemented in multithreaded development?

, the data in the heap is shared by all line stacks, and we can pass the data from one heap to the working memory of each stack through parameter passing, thus realizing data sharing among multiple threads.

(data sharing across multiple processes needs to be transmitted over the network.) )

3. From the perspective of the program design:

From the point of view of software design, the JVM stack represents the processing logic, and the JVM heap represents the data. This separation makes the processing logic clearer. The idea of divide and conquer. This idea of isolation and modularity is reflected in every aspect of software design.

4. Value passing and reference passing the truth

With this understanding of stacks and heaps, it's easy to know the truth about value passing and referencing:

1. The program runs always in the JVM stack, so when parameters are passed, there is only a problem passing the base type and object references. The object itself is not passed directly.

But how is the illusion of citation caused?

In running the JVM stack, the basic type and the reference are treated the same, all of which are pass values, so if it is a reference to a method call, it can also be understood as a "pass-through value" invocation, that is, the reference processing is exactly the same as the base type.

However, when the called method is entered, the value of the reference being passed is interpreted (or found) by the program to the object in the JVM heap, which corresponds to the actual object.

If you modify at this point, you modify the reference object instead of the reference itself, which is: the data in the JVM heap is modified. So this is a change that can be maintained.

At last:

In a sense, objects are made up of basic types.

You can look at an object as a tree, the object's properties, if it is an object, is still a tree (that is, a non-leaf node), and the base type is the leaf node of the tree. When a program parameter is passed, the passed value itself cannot be modified, but if the value is a non-leaf node (that is, an object reference), you can modify all the content underneath the node.

In fact, the object-oriented approach to the implementation of the previous structured program is not any different.

The introduction of object-oriented is only changing the way we think about problems, and closer to thinking in the natural way.

When we take the object apart, the object's properties are data, stored in the JVM heap, and the object's behavior (method) is run logic, placed in the JVM stack. When we write the object, we write the data structure, and also write the logic of the processing.

Java Basics-Stack and heap, static, final modifier, inner class, and Java memory allocation

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: 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.