亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Value passing and reference passing" >Value passing and reference passing
Value transfer in Java" > Value transfer in Java
Home Java Javagetting Started What is the difference between pass by value and pass by reference in java

What is the difference between pass by value and pass by reference in java

Jan 04, 2023 am 11:50 AM
java

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.

What is the difference between pass by value and pass by reference in java

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");//實(shí)際參數(shù)為Hollis
}
public void sout( String name) {/!形式參數(shù)為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 valuePass by referenceFundamental differenceWill create a copyDoes not create a copyAllThe original object cannot be changed in the functionThe original object can be changed in the function

我們上面看過的幾個(gè)pass的例子中,都只關(guān)注了實(shí)際參數(shù)內(nèi)容是否有改變。如傳遞的是User對(duì)象,我們?cè)囍淖兯膎ame屬性的值,然后檢查是否有改變。其實(shí),在實(shí)驗(yàn)方法上就錯(cuò)了,當(dāng)然得到的結(jié)論也就有問題了。

為什么說實(shí)驗(yàn)方法錯(cuò)了呢?這里我們來舉一個(gè)形象的例子。再來深入理解一下值傳遞和引用傳遞,然后你就知道為啥錯(cuò)了。

你有一把鑰匙,當(dāng)你的朋友想要去你家的時(shí)候,如果你直接把你的鑰匙給他了,這就是引用傳遞。這種情況下,如果他對(duì)這把鑰匙做了什么事情,比如他在鑰匙上刻下了自己名字,那么這把鑰匙還給你的時(shí)候,你自己的鑰匙上也會(huì)多出他刻的名字。

你有一把鑰匙,當(dāng)你的朋友想要去你家的時(shí)候,你復(fù)刻了一把新鑰匙給他,自己的還在自己手里,這就是值傳遞。這種情況下,他對(duì)這把鑰匙做什么都不會(huì)影響你手里的這把鑰匙。

但是,不管上面那種情況,你的朋友拿著你給他的鑰匙,進(jìn)到你的家里,把你家的電視砸了。那你說你會(huì)不會(huì)受到影響?而我們?cè)趐ass方法中,改變user對(duì)象的name屬性的值的時(shí)候,不就是在“砸電視”么。

還拿上面的一個(gè)例子來舉例,我們真正的改變參數(shù),看看會(huì)發(fā)生什么?

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);

上面的代碼中,我們?cè)趐ass方法中,改變了user對(duì)象,輸出結(jié)果如下:

print in pass , user is User{name='hollischuang ' , gender='Male '}
print in main , user is User{name='Hollis', gender= 'Male '}

我們來畫一張圖,看一下整個(gè)過程中發(fā)生了什么,然后我再告訴你,為啥Java中只有值傳遞。

What is the difference between pass by value and pass by reference in java

稍微解釋下這張圖,當(dāng)我們?cè)趍ain中創(chuàng)建一個(gè)User對(duì)象的時(shí)候,在堆中開辟一塊內(nèi)存,其中保存了name和gender等數(shù)據(jù)。然后hollis持有該內(nèi)存的地址ex123456(圖1)。當(dāng)嘗試調(diào)用pass方法,并且hollis作為實(shí)際參數(shù)傳遞給形式參數(shù)user的時(shí)候,會(huì)把這個(gè)地址ex123456交給user,這時(shí),user也指向了這個(gè)地址(圖2)。然后在pass方法內(nèi)對(duì)參數(shù)進(jìn)行修改的時(shí)候,即user = newUser();,會(huì)重新開辟一塊 eX456789的內(nèi)存,賦值給user。后面對(duì)user的任何修改都不會(huì)改變內(nèi)存eX123456的內(nèi)容(圖3)。

上面這種傳遞是什么傳遞?肯定不是引用傳遞,如果是引用傳遞的話,在user=new User()的時(shí)候,實(shí)際參數(shù)的引用也應(yīng)該改為指向eX456789,但是實(shí)際上并沒有。

通過概念我們也能知道,這里是把實(shí)際參數(shù)的引用的地址復(fù)制了一份,傳遞給了形式參數(shù)。所以,上面的參數(shù)其實(shí)是值傳遞,把實(shí)參對(duì)象引用的地址當(dāng)做值傳遞給了形式參數(shù)。

我們?cè)賮砘仡櫹轮暗哪莻€(gè)“砸電視”的例子,看那個(gè)例子中的傳遞過程發(fā)生了什么。

What is the difference between pass by value and pass by reference in java

同樣的,在參數(shù)傳遞的過程中,實(shí)際參數(shù)的地址eX1213456被拷貝給了形參,只是,在這個(gè)方法中,并沒有對(duì)形參本身進(jìn)行修改,而是修改的形參持有的地址中存儲(chǔ)的內(nèi)容。

所以,值傳遞和引用傳遞的區(qū)別并不是傳遞的內(nèi)容。而是實(shí)參到底有沒有被復(fù)制一份給形參。在判斷實(shí)參內(nèi)容有沒有受影響的時(shí)候,要看傳的的是什么,如果你傳遞的是個(gè)地址,那么就看這個(gè)地址的變化會(huì)不會(huì)有影響,而不是看地址指向的對(duì)象的變化。就像鑰匙和房子的關(guān)系。

那么,既然這樣,為啥上面同樣是傳遞對(duì)象,傳遞的String對(duì)象和User對(duì)象的表現(xiàn)結(jié)果不一樣呢?我們?cè)趐ass方法中使用name = “hollischuang”;試著去更改name的值,陰差陽錯(cuò)的直接改變了name的引用的地址。因?yàn)檫@段代碼,會(huì)new一個(gè)String,在把引用交給name,即等價(jià)于name =new String(“hollischuang”);。而原來的那個(gè)”Hollis”字符串還是由實(shí)參持有著的,所以,并沒有修改到實(shí)際參數(shù)的值。

What is the difference between pass by value and pass by reference in java

所以說,Java中其實(shí)還是值傳遞的,只不過對(duì)于對(duì)象參數(shù),值的內(nèi)容是對(duì)象的引用。

總結(jié)

無論是值傳遞還是引用傳遞,其實(shí)都是一種求值策略(Evaluation strategy)。在求值策略中,還有一種叫做按共享傳遞。其實(shí)Java中的參數(shù)傳遞嚴(yán)格意義上說應(yīng)該是按共享傳遞。

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.

For more programming-related knowledge, please visit: Programming Teaching! !

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

See all articles

    <tt id="82t1y"></tt>

      1. <var id="82t1y"><optgroup id="82t1y"></optgroup></var>

          <pre id="82t1y"></pre>