search
HomeJavajavaTutorialLet's talk about parameter passing of strings and arrays in JAVA

This article brings you relevant knowledge about java, which mainly introduces issues related to parameter passing of java strings and arrays. Let’s take a look at why java only Passing by value, hope it helps everyone.

Let's talk about parameter passing of strings and arrays in JAVA

Recommended study: "java Learning Tutorial"

The first thing to make clear is that there is only value passing in java! Only value is passed! The theoretical basis comes from "think in java". The next step is to explain in detail why java only passes by value.
Because there are two data types in Java: basic type and reference type, plus the special type String, it can be explained mainly from three aspects.

1. Basic data types

Look at the code first

public class Demo01 {
    
    public void change(int a) {
        System.out.println("副本a 的初始值" + a);
        a = 20;
        System.out.println("副本a 的新值值" + a);
    }

    public static void main(String[] args) {
        int a = 10;
        Demo01 d = new Demo01();
        d.change(a);
        System.out.println("change方法执行后的值" + a);
    }
}

Analysis:

In java, basic data types follow value transfer, so object d is called In the change() method, a copy of the original data a is simply passed to the parameter in the method. The value of the original data a and the copy a are both 10 at the first time. After a=20 is executed, the value of the copy a becomes 20.

So the running result is:

For the principle, please refer to the figure below

2. Reference data type

Look at the code first

public class Demo02 {

    char[] ch = {'a', 'b', 'c'};

    public void change(char ch[]) {
        System.out.println("方法中ch[0]的初始值:" + ch[0]);
        ch[0] = 'g';
        System.out.println("方法中ch[0]执行后的新值:" + ch[0]);
    }

    public static void main(String[] args) {
        Demo02 d = new Demo02();
        System.out.println("对象d中数组的初始值是:"+d.ch);
        d.change(d.ch);
        System.out.println("对象d中数组的最终值是:"+d.ch);
    }
}

Analysis:

When the reference type is passed as a parameter, it is also a value transfer. At this time, a copy of the address value is passed, but these two addresses point to the same place. When the copy address is not changed, operations on the data pointed to by the copy address will affect the value of the original data. The ch[] array in the method and the original ch[] array point to the same data, so in the initial stage ch[0] points to 'a'; then a new value is assigned to ch[0] in the copy to become 'g'.
So the running result is:

For the principle, please refer to the figure below

3. String parameter transfer

Look at the code first

public class Demo03 {
    public void change(String str2) {
        System.out.println("方法中str2初始值" + str2);
        System.out.println("方法中str2初始hashcode值" + str2.hashCode());
        str2 = "bbb";
        System.out.println("方法中str2赋值后:" + str2);
        System.out.println("方法中str2赋值后hashcode值:" + str2.hashCode());
    }

    public static void main(String[] args) {
        String str1 = new String("aaa");
        System.out.println("原始字符串str1的hashcode值:" + str1.hashCode());
        Demo03 d = new Demo03();
        d.change(str1);
        System.out.println("方法调用后str1的值" + str1);
    }
}

Analysis:

String is a special data type. Its bottom layer is a final char[] array, which cannot be changed, so When a string is passed as a parameter, it can be operated as a special array. In the same way, a copy of the original object reference is given to the copy. At this time, the reference of the copy object and the reference of the original object both point to the original string. The location, that is, when str2 is first initialized, the address it points to is consistent with the location pointed by the original object str1, that is, the initial hashcode value of str2 is the same as the hashcode value of the original object str1. After str2 is operated by str2="bbb", Due to the immutability of strings, str2 will point to a new object reference at this time, that is, str2 will point to the location of "bbb" at this time. The hashcode value of str2 will change, but the original object reference of str1 has not changed, and "aaa" has not changed, so str1 still points to "aaa". The running results are as follows:

Let’s look at a more specific string example:

public class Demo04 {

    public static void main(String[] args) {
        StringBuffer s = new StringBuffer("hello");
        StringBuffer s2 = new StringBuffer("hi");
        test(s, s2);
        System.out.println("方法調用后s的值:" + s);
        System.out.println("方法調用后s2的值:" + s2);
    }

    static void test(StringBuffer s3, StringBuffer s4) {
        System.out.println("方法初始化時s3的值" + s3);
        System.out.println("方法初始化時s4的值" + s4);
        s4 = s3;
        s3 = new StringBuffer("new");
        System.out.println("第一步变化后s3的值" + s3);
        System.out.println("第一步变化后s4的值" + s4);
        s3.append("boy");
        s4.append("gril");
        System.out.println("第二步变化后s3的值" + s3);
        System.out.println("第二步变化后s4的值" + s4);

    }
}

Let’s look at the results first this time:

Then analyze:

Before the method is executed, the locations pointed to by strings s1 and s2 are "hello" and "hi" respectively. This is beyond doubt,

(1) Then enter the method. The parameters s3 and s4 in the method are initialized the same as the above example. At this time, they point to the same position as s1s2, or s1s2 gives a copy of the object reference to s3s4. At this time, the value of s3s4 For "hello" and "hi"

(2) Then execute s4=s3. This operation is to reference the object of s3 to s4. At this time, s4 is "hello"; s3=new StringBuffer("new "); Please note that this operation is equivalent to giving s3 a new object reference. s3 points to a location where the string is "new", so at this time s3 = "new", s4 = "hello"

(3) Then s3.append("boy");s4.append("gril"); Please note that the append method in StringBuffer does not point to a new object reference for s3s4. It is The operation is performed on the original basis, so after the operation is completed, s3 = "newboy", s4 = "hellogril"

(4) At this point, the method is called. Let’s go back and review the impact of s3s4 on s1s2 in the process.
——- A. First, s3 starts to point to "hello" like s1, and then creates a new object reference "new" for s3. At this time, s3 and s1 no longer have a half-cent relationship, and s3 performs append ( boy), s3 = "newboy";
——– B. s4 and s2 both point to "hi" at the beginning, and then s3 gives its initial value (that is, a copy of s1) to s4. At this time, s4 points to "hello" (this will create a relationship between s4 and s1), s4 performs the append (grill) operation, because it and s1 point to the same location, so the objects they jointly point to will change, s4=s1="hellogrill".
——- C. Then it becomes clear that the object "hi" pointed to by s2 has not changed, and the "hello" pointed by s1 has become "hellogril" under the append ("grill") operation.

4. Summary

  • When using basic data types as formal parameters of a method, modifications to the formal parameters in the method body will not affect the values ​​of the actual parameters.

  • When using a reference data type as the formal parameter of a method, if the data content pointed to by the formal parameter is modified in the method body, it will affect the value of the actual parameter variable, because the formal parameter Variables and actual parameter variables share the same heap area;

  • When using reference data types as formal parameters of a method, if the pointer of the formal parameter variable is changed in the method body, then It will not affect the value of the actual parameter variable, so the formal parameter variable and the actual parameter variable point to different heap areas respectively; the last example is the most vivid explanation.

  • Regarding string parameters, it also depends on whether its parameter variable pointing has changed, because the bottom layer of String is a final type char[]. When you use String s = " aaa" or String s = new String("aaa"), a new object reference will be created for s. However, when the append() method is called, it will not point to a new object, but will change the original pointed object, and the object reference shared with it will also change.

  • The last thing repeated is that there is no reference transfer in Java, only value transfer. The reference type is a special value transfer (a copy of its address is given to the parameter, but it is different from the basic data type , if the object pointed to by the address changes, the original object will also change due to sharing reasons).

Recommended study: "java tutorial"

The above is the detailed content of Let's talk about parameter passing of strings and arrays in JAVA. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
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 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 to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

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

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

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 set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

MinGW - Minimalist GNU for Windows

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.