-1

Case 1

public static void main(String[] args) {
    Dog aDog = new Dog()
    Dog oldDog = new Dog()
if(aDog== oldDog) {
  System.out.println("Same");
} else {
  System.out.println("Different");
}

}

Output: Different

Case 2

public static void main(String[] args) {
    Dog aDog = new Dog();
    Dog oldDog = aDog;

if(aDog== oldDog) {
  System.out.println("Same");
} else {
  System.out.println("Different");
}

}

Output: Same

Can someone explain to me the result of these programs, please?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
toommy
  • 9
  • 1
  • This question is very vague. Please include more detail and ask a **specific question**. You may wish to revise this guide: https://stackoverflow.com/help/how-to-ask Also, please introduce your question before posting any code. – Captain Hat Jan 24 '21 at 02:00
  • 2
    Can you attempt to explain in your own words what the line `oldDog = aDog` does? – chrylis -cautiouslyoptimistic- Jan 24 '21 at 02:19

1 Answers1

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

aran
  • 10,978
  • 5
  • 39
  • 69
  • 1
    "Memory address" is usually a misleading concept to introduce when discussing the JVM; the Java documentation generally simply sticks with "the same/identical object". – chrylis -cautiouslyoptimistic- Jan 24 '21 at 02:21
  • @chrylis-cautiouslyoptimistic- agreed, coming from c world this is somehow misleading. I updated the answer, hope it's cleaner now. Thanks for the comment! – aran Jan 24 '21 at 02:25