#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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment