Two Ways to Pass Arguments to Methods:
Call by Value:
Call by Reference:
Primitive Type Passage:
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);
}
}
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);
}
}
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.

The above is the detailed content of How arguments are passed. For more information, please follow other related articles on the PHP Chinese website!
How to use filter function
What are the java flow control statements?
What is mobile HD
How to solve the problem that pycharm cannot find the module
SQL statement to backup database
What is function
What should I do if the matching result of the vlookup function is N/A?
Introduction to the usage of MySQL ELT function