Home >Java >javaTutorial >Let's talk about parameter passing of strings and arrays in JAVA

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

WBOY
WBOYforward
2022-03-28 12:05:192465browse

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.net. If there is any infringement, please contact admin@php.cn delete