Home  >  Article  >  类库下载  >  Two ways to pass java method parameters

Two ways to pass java method parameters

little bottle
little bottleforward
2019-04-08 13:43:206250browse

#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;
    }
}

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

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

}

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete