Task 7 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.5 Static and toString — comparing objects

Lesson

Одинаковые поля — ещё не один объект

You met this with strings: == asks whether two variables point at the same object, not whether their contents match. For your own classes the effect is the same, and more visible.


Worked example

Dog d1 = new Dog("Rex");
Dog d2 = new Dog("Rex");   // same name, built separately
Dog d3 = d1;               // the SAME object

System.out.println(d1 == d2);   // false — two different objects
System.out.println(d1 == d3);   // true  — one object, two names
System.out.println(d1.name.equals(d2.name));   // true — contents match

So == answers «is it literally the same object?». To compare by content, compare the fields yourself — or give the class its own equals method.


▶ Try it: run this, then change something and run it again.



Two objects with identical field values compared with == give...


When does == give true for two object variables?


Type exactly what this program prints.

class Dog {
    String name;

    Dog(String name) {
        this.name = name;
    }
}

public class Main {
    public static void main(String[] a){
        Dog x = new Dog("Bo");
        Dog y = new Dog("Bo");
        Dog z = x;
        System.out.println(x == y);
        System.out.println(x == z);
    }
}

To compare two dogs by name, you...


True or false?