Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

About assignment by reference and value in JAVA


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • The first case creates two different Objects, each one with its own reference/entity in memory. Instances from the same Class, but different Objects anyway.
  • In the second case, you assign the same Object reference to the new Dog instance: they both refer to the same Object.

The == operator compares the references of objects. In your second case, they both reference the same Dog.

This is for Objects, not primitives; Regarding primitives, the value itself is compared.


Java Specification Equality Operators:

If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality. A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5). The run-time values of the two operands would necessarily be unequal.

At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...