Difference: 1. Value transfer creates a copy, while reference transfer does not create a copy; 2. The original object cannot be changed in the function during value transfer, but the original object can be changed in the function during reference transfer. Passing by value means that a copy of the actual parameters is passed to the function when calling the function, so that if the parameters are modified in the function, the actual parameters will not be affected; passing by reference means that the actual parameters are copied when calling the function. The address is passed directly to the function, so modifications to the parameters in the function will affect the actual parameters.
The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.
actual and formal parameters
We all know that parameters can be defined when defining a method in Java. For example, the main method in Java, public static void main(String[ ] args), the args here are parameters. Parameters are divided into formal parameters and actual parameters in programming languages.
Formal parameters: are the parameters used when defining the function name and function body. The purpose is to receive the parameters passed in when calling the function.
Actual parameters: When calling a parameterized function, there is a data transfer relationship between the calling function and the called function. When calling a function in the calling function, the parameters in parentheses after the function name are called "actual parameters"
A simple example:
public static void main( String[ ] args) {
ParamTest pt = new ParamTest();
pt.sout( "Hollis");//實際參數為Hollis
}
public void sout( String name) {/!形式參數為name
system.out.println(name);
}
The actual parameters are The content that is actually passed when calling a method with parameters, and the formal parameters are the parameters used to receive the content of the actual parameters.
Value passing and reference passing
As mentioned above, when we call a parameterized function, the actual parameters will be passed to the formal parameters. However, in programming languages, there are two cases of transfer in this transfer process, namely transfer by value and transfer by reference. Let's take a look at how passing by value and passing by reference are defined and distinguished in programming languages.
Value passing refers to copying a copy of the actual parameters to the function when calling the function, so that if the parameters are modified in the function, the actual parameters will not be affected. Passing by reference refers to passing the address of the actual parameters directly to the function when calling the function. Then the modification of the parameters in the function will affect the actual parameters.
With the above concepts, you can then write code and practice it. Let’s see whether it is value passing or reference passing in Java. So, the simplest piece of code came out:
public static void main( String[] args) {
ParamTest pt = new ParamTest();
int i = 10;
pt.pass(i);
System.out.println( "print in main , i is " +i);
}
public void pass(int j){
j = 20;
system.out.println( "print in pass , j is " + j);
}
In the above code, we modify the value of parameter j in the pass method, and then print the value of the parameter in the pass method and main method respectively. The output result is as follows:
print in pass , j is 20
print in main , i is 10
It can be seen that the modification of the value of i inside the pass method does not change the value of the actual parameter i. So, according to the above definition, someone came to the conclusion: Java's method passing is value passing. However, some people soon raised questions (haha, so don’t jump to conclusions easily.). Then, they will move out the following code:
public static void main(String[ ] args) {
ParamTest pt = new ParamTest();
User hollis = new User();
hollis.setName( "Hollis");
hollis.setGender("Male");
pt.pass(hollis);
system.out.println( "print in main , user is " + hollis);}public void pass(User user) {
user.setName( "hollischuang");
System.out.println( "print in pass , user is " + user);}
is also a pass method, and the value of the parameter is also modified within the pass method. The output result is as follows:
print in pass , user is User{name='hollischuang', gender='Male '}
print in main , user is User{name='hollischuang' , gender='Male '}
After the pass method is executed, the value of the actual parameter is changed. According to the definition of passing by reference above, the value of the actual parameter is changed. Isn’t this called passing by reference? . Therefore, based on the above two pieces of code, someone came to a new conclusion: in Java methods, when passing ordinary types, it is passed by value, and when passing object types, it is passed by reference. However, this statement is still wrong. If you don’t believe me, take a look at the following parameter transfer where the parameter type is an object:
public static void main( string[] args) {
ParamTest pt = new ParamTest();
string name = "Hollis";
pt.pass(name ) ;
System.out.println( "print in main , name is " + name);
}
public void pass(string name) {
name = "hollischuang";
system.out.println( "print in pass , name is " + name);
}
The output result of the above code is
print in pass , name is hollischuangprint in main , name is Hollis
What’s the explanation? An object is also passed, but the original parameter is The value has not been modified. Could it be that the transferred object has become a value transfer again?
Value transfer in Java
Above, we gave three examples to show the The results are different, which is why many beginners and even many advanced programmers are confused about Java's transfer types. In fact, what I want to tell you is that the above concept is not wrong, but there is a problem with the code example. Come on, let me outline the key points of the concept for you, and then give you a few truly appropriate examples.
Value passing refers to copying a copy of the actual parameters to the function when calling the function, so that if the parameters are modified in the function, the actual parameters will not be affected. Passing by reference refers to passing the address of the actual parameters directly to the function when calling the function. Then the modification of the parameters in the function will affect the actual parameters.
So, let me summarize for you the key points of the difference between value passing and reference passing.
##Pass by value
Pass by reference
Fundamental difference
Will create a copy
Does not create a copy
All
The original object cannot be changed in the function
The original object can be changed in the function
public static void main(String[ ] args){
ParamTest pt = new ParamTest();
User hollis = new User();
hollis.setName( "Hollis");
hollis.setGender("Male" );
pt.pass(hollis);
system.out.println("print in main , user is " + hollis);
public void pass(User user) {
user = new User();
user.setName( "hollischuang");
user.setGender( "Male");
system.out.println( "print in pass , user is " + user);
上面的代碼中,我們在pass方法中,改變了user對象,輸出結果如下:
print in pass , user is User{name='hollischuang ' , gender='Male '}
print in main , user is User{name='Hollis', gender= 'Male '}
Passing by sharing means that when a function is called, a copy of the address of the actual parameter is passed to the function (if the actual parameter is on the stack, the value is copied directly). When operating parameters inside a function, you need to copy the address to find the specific value before operating. If the value is on the stack, then because it is a direct copy of the value, operations on the parameters within the function will not affect external variables. If the original copy is the address of the original value in the heap, then you need to find the corresponding location in the heap based on the address before performing the operation. Because a copy of the address is passed, the operation on the value within the function is visible to the external variable.
To put it simply, transfer in Java is by value, and this value is actually a reference to the object. Passing by sharing is actually just a special case of passing by value. So we can say that passing in Java is passing by sharing, or that passing in Java is passing by value.
So operating parameters inside the function will not affect external variables. If the original copy is the address of the original value in the heap, then you need to find the corresponding location in the heap based on the address before performing the operation. Because a copy of the address is passed, the operation on the value within the function is visible to the external variable.
To put it simply, transfer in Java is by value, and this value is actually a reference to the object.
Passing by sharing is actually just a special case of passing by value. So we can say that passing in Java is passing by sharing, or that passing in Java is passing by value.
The above is the detailed content of What is the difference between pass by value and pass by reference in java. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Singleton design pattern in Java ensures that a class has only one instance and provides a global access point through private constructors and static methods, which is suitable for controlling access to shared resources. Implementation methods include: 1. Lazy loading, that is, the instance is created only when the first request is requested, which is suitable for situations where resource consumption is high and not necessarily required; 2. Thread-safe processing, ensuring that only one instance is created in a multi-threaded environment through synchronization methods or double check locking, and reducing performance impact; 3. Hungry loading, which directly initializes the instance during class loading, is suitable for lightweight objects or scenarios that can be initialized in advance; 4. Enumeration implementation, using Java enumeration to naturally support serialization, thread safety and prevent reflective attacks, is a recommended concise and reliable method. Different implementation methods can be selected according to specific needs
Analyzing Java heap dumps is a key means to troubleshoot memory problems, especially for identifying memory leaks and performance bottlenecks. 1. Use EclipseMAT or VisualVM to open the .hprof file. MAT provides Histogram and DominatorTree views to display the object distribution from different angles; 2. sort in Histogram by number of instances or space occupied to find classes with abnormally large or large size, such as byte[], char[] or business classes; 3. View the reference chain through "ListObjects>withincoming/outgoingreferences" to determine whether it is accidentally held; 4. Use "Pathto
ThreadLocal is used in Java to create thread-private variables, each thread has an independent copy to avoid concurrency problems. It stores values ??through ThreadLocalMap inside the thread. Pay attention to timely cleaning when using it to prevent memory leakage. Common uses include user session management, database connections, transaction context, and log tracking. Best practices include: 1. Call remove() to clean up after use; 2. Avoid overuse; 3. InheritableThreadLocal is required for child thread inheritance; 4. Do not store large objects. The initial value can be set through initialValue() or withInitial(), and the initialization is delayed until the first get() call.
Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.
The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying
There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)->
Dynamic web crawling can be achieved through an analysis interface or a simulated browser. 1. Use browser developer tools to view XHR/Fetch requests in the Network, find the interface that returns JSON data, and use requests to get it; 2. If the page is rendered by the front-end framework and has no independent interface, you can start the browser with Selenium and wait for the elements to be loaded and extracted; 3. In the face of the anti-crawling mechanism, headers should be added, frequency control, proxy IP should be used, and verification codes or JS rendering detection should be carried out according to the situation. Mastering these methods can effectively deal with most dynamic web crawling scenarios.
In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar