0

Why this code doesn't compile on line 7?

public class HelloWorld
{
  public static void main(String[] args)
  {

    String s1 = "java";
    StringBuilder s2 = new StringBuilder();
    if (s1 == s2)
    System.out.print("1");
  }
}

and why this is accepted?

public class HelloWorld
{
  public static void main(String[] args)
  {

    String s1 = "java";
    Object s2 = new Object();
    if (s1 == s2)
    System.out.print("1");
  }
}

Should not be accepted even StringBuilder? Isn't an Object?

frank86ba
  • 23
  • 6
  • 3
    Because `String` and `StringBuilder` are unrelated, i.e. they do not stand in a inheritance-relationship, whereas `String` and `Object` do stand in an inheritance-relationship. Even if your syntax were correct (i.e. compare the two strings, holded by the `String` and the `StringBuffer`), [you never want to use `==` to compare `Strings` on equality](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – Turing85 May 19 '16 at 16:06
  • 2
    `String` is an `Object`. Every object is an `Object`. However, a `String` is not a `StringBuilder` and a `StringBuilder` is not a `String`, so you cannot compare those. – RaminS May 19 '16 at 16:06
  • 1
    I'd be interested to know why you think this is an equality check you want to make. They can't possibly be equal (which is why the compiler complains), so what are you hoping to accomplish? (This sort of thing is often a sign of a deeper misunderstanding, which is why I ask.) – dcsohl May 19 '16 at 16:09
  • @dcsohl In a language allowing operator-overloading, it would be possible to write such things and the intended semantics of OP should be clear. It is "just" the syntax and the actual semantics, that is messed up. – Turing85 May 19 '16 at 16:11
  • @Turing85 Your explanation is a plausible one but not guaranteed to be what's actually going on here. I'm not looking for a conversation; I want to know what *the OP* is trying to do. – dcsohl May 19 '16 at 16:13
  • @dcsohl I'm just testing operator overloading and casting it does. If I can use == on reference, I thought I can expect that s1 == s2 doesn't give me a compiler error, at least an error in semantics. I thought either s1 and s2 auto-casting to Object was legal, but it isn't that the way javac works. It try to cast s1 to s2 or viceversa, as I see in JLS (http://stackoverflow.com/questions/29820004/checking-object-reference-equality-using-in-java), so if it fails casting I get compiler error. Thank for all – frank86ba May 20 '16 at 07:49

0 Answers0