Home Java javaTutorial Detailed explanation of Java value passing and reference passing

Detailed explanation of Java value passing and reference passing

Jan 24, 2017 pm 04:54 PM

When an object is passed as a parameter to a method, this method can change the properties of the object and return the changed results. So is it passed by value or by reference?
Answer: It is value transfer. The Java programming language has only value-passed parameters. When an object instance is passed as a parameter to a method, the parameter's value is a copy of the object's reference. Pointing to the same object, the contents of the object can be changed within the called method, but the reference to the object (not a copy of the reference) will never change.

Java parameters, whether they are primitive types or reference types, are passed by copies (there is another way of saying it is by value, but it is easier to understand by saying that it is by value. Passing by value is usually relative to passing by address) ).

If the parameter type is a primitive type, then what is passed is a copy of the parameter, which is the value of the original parameter. This is the same as the value passing discussed before. Changing the value of the copy within the function does not change the original value.

If the parameter type is a reference type, then what is passed is a copy of the reference parameter, and this copy stores the address of the parameter. If the address of this copy is not changed in the function, but the value in the address is changed, then the change within the function will affect the parameters passed in. If the address of the copy is changed in the function, such as new, then the copy points to a new address. At this time, the parameter passed in still points to the original address, so the value of the parameter will not be changed.

Example:

public class ParamTest {
  public static void main(String[] args){
   /**
    * Test 1: Methods can't modify numeric parameters
    */
   System.out.println("Testing tripleValue:");
   double percent = 10;
   System.out.println("Before: percent=" + percent);
   tripleValue(percent);
   System.out.println("After: percent=" + percent);
  
   /**
   * Test 2: Methods can change the state of object parameters
   */
   System.out.println("\nTesting tripleSalary:");
   Employee harry = new Employee("Harry", 50000);
   System.out.println("Before: salary=" + harry.getSalary());
   tripleSalary(harry);
   System.out.println("After: salary=" + harry.getSalary());
  
   /**
   * Test 3: Methods can't attach new objects to object parameters
   */
   System.out.println("\nTesting swap:");
   Employee a = new Employee("Alice", 70000);
   Employee b = new Employee("Bob", 60000);
   System.out.println("Before: a=" + a.getName());
   System.out.println("Before: b=" + b.getName());
   swap(a, b);
   System.out.println("After: a=" + a.getName());
   System.out.println("After: b=" + b.getName());
  }
  
  private static void swap(Employee x, Employee y) {
   Employee temp = x;
   x=y;
   y=temp;
   System.out.println("End of method: x=" + x.getName());
   System.out.println("End of method: y=" + y.getName());
  }
  
  private static void tripleSalary(Employee x) {
   x.raiseSalary(200);
   System.out.println("End of method: salary=" + x.getSalary());
  }
  
  private static void tripleValue(double x) {
   x=3*x;
   System.out.println("End of Method X= "+x);
  }
 }
Copy after login

Display result:

Testing tripleValue:
Before: percent=10.0
End of Method X= 30.0
After: percent=10.0
 
Testing tripleSalary:
Before: salary=50000.0
End of method: salary=150000.0
After: salary=150000.0
 
Testing swap:
Before: a=Alice
Before: b=Bob
End of method: x=Bob //可见引用的副本进行了交换
End of method: y=Alice
After: a=Alice //引用本身没有交换
After: b=Bob
Copy after login

The above is the entire content of this article, I hope it will be useful for everyone’s learning Thank you for your help, and I hope everyone will visit the PHP Chinese website.

For more detailed articles on Java value passing and reference passing, please pay attention to the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles