Java – objects referenced by reference – references by value

I read this comment here: passing a string by reference in Java?

Someone can explain that a new programmer can grasp what is the difference?

"In Java, primitives are passed by value and objects by reference

And:

Nothing in Java is passed by reference. References are passed by value

Are these statements true in a sense? I don't want to invite a parade, but it sounds like a very important concept, and I still don't fully understand it

Solution

I think the misunderstanding is that a variable cannot contain a starting object If you are sure, it is obvious that variables can only contain references to objects (or original values) The step from there to the implementation reference is passed through value (like the original value) is quite small

You can do a very simple test to determine whether the language supports by reference Ask yourself if you can write an exchange function in this language, that is, something that can do so

x == A,y == B

swap(x,y);

x == B,y == A

As a java programmer, you quickly realize that you can't implement it in Java, so you (correctly) conclude that Java is not passed by reference

Go back to your sentence:

>In Java, objects are passed by reference

This is false. I think you can only pass something contained in a variable. As I said above, a variable cannot contain an object, so you can't pass an object in Java

>Nothing in Java is passed by reference. References are passed by value

It's true.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>