This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

preface

  • Have you ever come across a scene like this? When you initialize a variable and pass it downstream after the business process is done, the variable gets contaminated. What does contamination mean that variables are changed

Problem specification

  • We often call other methods in our methods to assist in processing, which is good for coupling the code. However, sometimes we pass values to subfunctions just to facilitate their internal business, and do not want to be affected by their internal influence and pollute their own business
  • Amethod calls Bmethod with a value parameter. The value argument should remain the same after the call

Problem resolution

  • Why did it change? Those of you who have this kind of knowledge probably know that some things change and some things don’t change. This has something to do with the type of values we pass in Java; Value passing, reference passing
  • Passing in Java is exactly all value passing. Then why do we still have the term “pass-by”? The address of the object is passed when non-underlying type data is passed. Internal operations find objects by address. So we call this passing by reference

reference

  • Above is our case code. inlogMapMethod to print a map. Now we see that the outside is also unchanged

  • But if we were inlogMapIn the parameter structure changes. Then we have a change on the outside

  • Why does this happen? It also says that the value of the address is passed. The principle can be seen as follows

Value passed

	public static void main(String[] args) throws InterruptedException {
        int index = 0;
        add(index);
        System.out.println(index);
    }

    private static void add(int index) {

        index = index + 1;
    }
Copy the code
  • But when we pass the base type, it doesn’t change. Because we copied this lecture directly.

conclusion

  • Value passing is what we think of as copying in the computer. A copy of the past has no relation to the original data. It’s just the same initial content
  • Reference passing is what we understand as a desktop shortcut. I’m still operating on the same copy

Original is not easy, thank you for your praise