object1.toString() == object2.toString()

140 Views Asked by At

The below is my main method in which am comparing two object references. Having overridden the toString() method in Car class, my question is why are the below "if" conditions evaluating to false when they should evaluate to true. Could somebody explain? Thanks.

public static void main(String[] args){

        Car c1 = new Car(2829,"white");
        Car c2 = new Car(2829,"white");

        if(c1 == c2)
            System.out.println(true);
        else
            System.out.println(false);

        String sc1 = c1.toString();
        String sc2 = c2.toString();

        if(sc1 == sc2)
            System.out.println("it's equal");
        else
            System.out.println("it's not!");
    }


public class Car {
    private int regNo;
    private String color;

    protected void start(){
        System.out.println("Car Started!");
    }

    public Car(int regNo, String color){
        this.regNo = regNo;
        this.color = color;
    }

    @Override
    public String toString() {
        return "Car-"+regNo;
    }
}

Say, i have two strings s1="abc" and s2 = "abc". Now, s1 == s2 evaluating to true then why is that in the above code c1.toString() == c2.toString() evaluating to false is my question?

1

There are 1 best solutions below

4
On

Well, because == compares references and

  1. The reference c1 is not same as c2
  2. c1.toString().equals(c2.toString()) is the right way to compare Strings.