Table of Contents
Is java passed by value or reference?
Home Common Problem Is java passed by value or by reference?

Is java passed by value or by reference?

Sep 08, 2022 pm 02:47 PM
java

Java is value passing; value passing means that when calling a method, a copy of the actual parameters is passed to the method, so that if the parameters are modified in the method, it will not affect the actual parameters; when passing When a basic type is passed, a copy of the value is passed, and modifications to the copied variable do not affect the original variable; when a reference type is passed, a copy of the reference address is passed, but the copied address and the real address point to both The same real data, so the value in the original variable can be modified.

Is java passed by value or by reference?

The operating environment of this tutorial: Windows 10 system, DELL G3 computer.

Is java passed by value or reference?

Java is passed by value.

When a basic type is passed, a copy of the value is passed, and modifications to the copied variable do not affect the original variable; when a reference type is passed, a copy of the reference address is passed. However, the copied address and the real address both point to the same real data, so the value in the original variable can be modified; when the String type is passed, although the copied address is also a reference address and points to the same data, the String The value cannot be modified, so the value in the original variable cannot be modified.

First, let’s explain what is passing by reference and what is passing by value.

  • Pass by reference refers to passing the address of the actual parameters directly to the method when calling the method. Then the modification of the parameters in the method will affect actual parameters.

  • Pass by value means passing a copy of the actual parameters to the method when calling the method, so that if the parameters are modified in the method, it will not affect to the actual parameters.

So in Java, is it passed by reference or by value? In fact, this issue has been debated continuously, and the official has not given a definite answer. But as far as I understand it, Java is value transfer.

Let’s look at a simple example first:

1

2

3

4

5

6

7

8

9

10

public void test() {

    int a = 1;

    change(a);

    System.out.println("a的值:" + a);

}

private void change(int a) {

    a = a + 1;

}

// 输出

a的值:1

Copy after login

defines a basic type variable a in the test() method, then calls the change() method to try to change the variable, and finally outputs is still the original value.

First of all, we must be clear that local variables in a method are stored on the stack. If it is a basic type variable, the value of this variable is stored directly. If it is a reference type variable, the value is stored. The address points to a specific value in the heap.

In the above example, the a passed when calling the change() method is actually a copy of the a variable, not the real a. What is changed in the change() method is a copy, which has no effect on the real a. of.

Looking at it this way, Java is indeed passing by value, but if we look at the following example, you will be confused

1

2

3

4

5

6

7

8

9

10

11

public void test() {

   User user = new User();

   user.setAge(18);

   change(user);

   System.out.println("年龄:" + user.getAge());

}

private void change(User user) {

   user.setAge(19);

}

// 输出

年龄:19

Copy after login

Look, the properties in the object have been changed, isn’t it passed by value? , it should not change. At this time, someone concluded that when the value passed is a basic type, it is passed by value, and when the value passed is a reference type, it is passed by reference. Is it really?

To analyze this problem, we need to know how variables are stored in jvm.

First look at the basic type. This is very simple. The variable stores the value directly on the stack. What is passed to the change() method is a copy of the variable, so modifications to the copied variable will not affect the original variable. value.

Then look at the reference type. The variable stores the reference address in the stack. This address points to the specific value in the heap, as shown below:

Is java passed by value or by reference?

When calling When the change() method passes in a variable, it also copies the variable, but the copy here is only the reference address in the stack and does not copy the data in the heap, so it will become like the following picture:

Is java passed by value or by reference?

Although the variable is copied, the address it points to is the same. Therefore, when the data in the variable is modified, it will still affect the original real variable. However, if we modify the address of the variable on the stack , it will not affect the original variable, for example, the following code:

1

2

3

4

5

6

7

8

9

10

11

12

public void test() {

   User user = new User();

   user.setAge(18);

   change(user);

   System.out.println("年龄:" + user.getAge());

}

private void change(User user) {

   user = new User();

   user.setAge(19);

}

// 输出

年龄:18

Copy after login

This is to modify the address of the variable in the stack, but it will not affect the original variable.

At this point, everyone almost understands it, but looking back at the original question, a variable of type String is passed in. String is a reference type. It stands to reason that the original variable will be changed. What is the result? Is it unchanged?

String variable is special. We can see from the source code of String that the value of String is maintained through the internal char[] array, but this data is defined as final type. Therefore, the value of String is Immutable. When we usually modify the value of String, we actually create a new String object. For example, in the following code:

1

2

String a = "hello";

a = "world";

Copy after login

In this code, in fact, the a variable is not modified to world, but a new String is created. Object, the value of this object is world, and the reference address of this object is assigned to a. The original hello is still in the heap, but this value is not referenced and will be garbage collected by gc after a while.

The changes in the memory of the value passed by the String variable are as follows:

Is java passed by value or by reference?

String copies the variable address, but it cannot change the value of the original String. Because String is immutable, a new String object is created in the change() method. What is changed is the value of the new object, and the original variable has no effect.

For more related knowledge, please visit the FAQ column!

The above is the detailed content of Is java passed by value or by reference?. For more information, please follow other related articles on 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)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.