Home > 类库下载 > java类库 > body text

Two ways to pass java method parameters

little bottle
Release: 2019-04-08 14:56:18
forward
6259 people have browsed it

#There are two ways to pass method parameters in Java, pass by value and pass by reference.

1. Pass by value

The parameter type is int, long and other basic data types (eight basic data types), the process of parameter passing Using the value copy method

Code snippet 1:

public class Test {

    public static void main(String[] args) {
        int a = 5;
        fun(a);
        System.out.println(a);// 输出结果为5
    }

    private static void fun(int a) {
        a += 1;
    }
}
Copy after login

2. Pass by reference

The parameter type is a reference type, and the parameter transfer process adopts the copy reference method


Code snippet 2:

public class Test {

    public static void main(String[] args) {
        A a = new A(5);
        fun(a);
        System.out.println(a.a);// 输出结果为6
    }

    private static void fun(A a) {
        a.a += 1;
    }

    static class A {
        public int a;

        public A(int a) {
            this.a = a;
        }
    }
}
Copy after login

Conclusion: Passing by value will not change the original value, passing by reference will change the value of the referenced object

Look at the following This situation:

Code snippet 3:

public class Test {

    public static void main(String[] args) {
        Integer a = 5;
        fun(a);
        System.out.println(a);// 输出结果为5
    }

    private static void fun(Integer a) {
        a += 1;
    }

}
Copy after login

This is obviously a reference transfer, why is the value of the object not changed?

The auto-boxing function of the basic data type encapsulation class is actually used here.

Integer a = 5, after compilation it is actually Integer a = Integer.valueOf(5). Looking at the source code of Integer, it does not change the value of the original object, but just points its reference to another object.


#The process in code snippet 3 can be represented by the following figure:

directly changes the stack frame The address points to another object, so the original value is not changed.

【Recommended Course:

Java Video Tutorial

The above is the detailed content of Two ways to pass java method parameters. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template