0

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?

J28
  • 1,080
  • 3
  • 15
  • 25

1 Answers1

1

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.
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • Well, i know equals() is the right way to compare, however when the below is evaluating to true why isn't the above? String s1 = "abc"; String s2="abc"; s1==s2 - evaluates to true – J28 Nov 28 '14 at 10:04
  • 2
    Strings are immutable objects any modification create a new instance (like your toString() methods). – Fabien Thouraud Nov 28 '14 at 10:05
  • 2
    @Jsm - by default, at *object* level both `==` and `equals()` compare references. So, they will return `false` c1 is not c2. You will have to *override* `equals()` and then change its *default* mplementation and then use `c1.equals(c2)`. For Strings, `equals()` has already been implemented (overidden), So, `.equals()` compares *contents* of 2 *different* string instances. – TheLostMind Nov 28 '14 at 10:07
  • 1
    > String s1 = "abc"; String s2="abc"; s1==s2 Because "" does not create a new string, instead it uses string pooling. – Michael Lloyd Lee mlk Nov 28 '14 at 12:07