#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.




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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment





