Home > Java > javaTutorial > How arguments are passed

How arguments are passed

PHPz
Release: 2024-08-24 06:34:08
Original
887 people have browsed it

Two Ways to Pass Arguments to Methods:

Call by Value:

  • Copies the value of the argument in the formal parameter of the subroutine.
  • Changes made to the parameter within the method do not affect the original argument.

Call by Reference:

  • Passes a reference to the argument, not the value.
  • Changes made to the parameter affect the original argument in the call.

Primitive Type Passage:

  • When a primitive type (such as int or double) is passed, call by value is used.
  • The method receives a copy of the argument, so changes made within the method do not affect the original value.

Example:

class Test {
    void noChange(int i, int j) {
        i = i + j;
        j = -j;
    }
}

class CallByValue {
    public static void main(String[] args) {
        Test ob = new Test();
        int a = 15, b = 20;
        System.out.println("a and b before call: " + a + " " + b);
        ob.noChange(a, b);
        System.out.println("a and b after call: " + a + " " + b);
    }
}

Copy after login

Object Passage:
When an object is passed to a method, Java uses call by reference.
The method receives a reference to the object, which means that changes made within the method affect the original object.

Example:

class Test {
    int a, b;
    Test(int i, int j) {
        a = i;
        b = j;
    }
    void change(Test ob) {
        ob.a = ob.a + ob.b;
        ob.b = -ob.b;
    }
}

class PassObRef {
    public static void main(String[] args) {
        Test ob = new Test(15, 20);
        System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
        ob.change(ob);
        System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
    }
}

Copy after login

Changes within the change() method affect the ob object passed as an argument.

Difference Between Primitive Types and Objects:
Primitive Types: Passed by value, changes to the method do not affect the original values.
Objects: Passed by reference, changes to the method affect the original object.

Final Summary:
Passing arguments in Java can be by value or by reference. Primitive types are passed by value, while objects are passed by reference, resulting in different effects on the original arguments.

Como os argumentos são passados

The above is the detailed content of How arguments are passed. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template