Parameter passing in Java is pass by value? Or pass by reference?

Is parameter passing in Java by value? Or pass by reference?

First there are two concepts:

1. There are no pointers in Java.

2. The program runs on the stack, so when passing parameters, there is only the problem of passing basic data types and object references. The object itself is not passed directly.

From the above - when Java passes parameters in a method call, because there is no pointer, it is a pass-by-value call .

But why does it feel like a pass-by-reference?

In the runtime stack, the processing of basic types and references is the same, and both are passed by value , so if it is a method call, it can also be understood as a "pass by reference" call by value, that is, the processing of references is the same as the basic type. of. But when entering the called method, the value of the reference passed is interpreted (or searched) by the program to the object in the heap, which corresponds to the real object. If the modification is made at this time, the modification is to refer to the corresponding object, not the reference itself, that is, the data in the heap is modified. So this modification can be maintained.

Objects, in a sense, are composed of primitive types. If the object is regarded as a tree, if the attributes of the object are still objects, it is still a tree (ie, non-leaf node), and the basic type is the leaf node of the tree. When the program parameter is passed, the passed value itself cannot be modified, but if the value is a non-leaf node (ie, an object reference), all the content under this node can be modified.

A program can have no heap, but not a stack. The heap is a data storage service for the stack, and the heap is actually a shared memory. It is precisely because of the idea of ​​separation of heap and stack that Java's garbage collection is possible.


Why separate the heap and stack?

First, from the perspective of software design, the stack represents processing logic and the heap represents data. This separation makes logical processing clearer. The idea of ​​divide and conquer.
Second, the separation of the heap and the stack allows the contents of the heap to be shared by multiple stacks.
Third, the stack can only grow upwards, which limits the storage capacity of the stack. Unlike the heap, objects in the heap can grow dynamically as needed, so the splitting of the stack and the heap makes dynamic growth possible, and only one address in the heap needs to be recorded in the corresponding stack.
Fourth, object-oriented is the combination of stack and heap. The attributes of the object are data, which are stored in the heap; and the methods of the object are the operation logic, which are placed in the stack. When writing an object, both the data structure and the logic for processing the data are written.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325769529&siteId=291194637