-3
class X
{
    public static void main(String...a)
    {
        String a = "meow";
        String ab = a + "deal";
        String abc = "meowdeal";
        System.out.println(ab == abc);
    }
}

Am getting an output as false... why. Am preparing for ocjp. I thin we have to get true. Beacuse ab contains "meowdeal". When am trying to assign "meowdeal" to abc this literal is already tehre in string pool. So ab and abc both are pointing to the same object. Then we have to get true.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Abdul
  • 1,130
  • 4
  • 29
  • 65
  • 1
    @PatrickCollins The question is not about the erroneous use of `==` for `equals`. It is about compiler interna, and the OP is aware of some inner workings. – Joop Eggen Aug 26 '14 at 06:22
  • 1
    @JoopEggen Is that why there have been 4 answers in 12 minutes telling the OP to use `equals` instead of `==`? – Patrick Collins Aug 26 '14 at 06:24
  • @PatrickCollins all misunderstood the question, see my answer below. Or I am getting senile, which I suspect sufficiently often. Nevertheless I also almost gave a sigh of despair about ==. – Joop Eggen Aug 26 '14 at 06:32

4 Answers4

2

The problem is that a not being final lets forfeit the compiler optimization.

If a is not final, data flow analysis is needed to see that the initialisation of ab is special.

    final String a = "meow";
    String ab = a + "deal";
    String abc = "meowdeal";
    System.out.println(ab == abc);
    System.out.println("meow" + "deal" == "meowdeal");

Will yield true + true.

I could imagine other java compilers dealing differently with this.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

Try equals() instead:

class X
{
    public static void main(String...a)
    {
        String a = "meow";
        String ab = a + "deal";
        String abc = "meowdeal";
        System.out.println(ab.equals(abc));
    }
}
0

The == operator checks whether two variables refer to the same object. You have two distinct string objects that contain the same text. The equals method will return true, but == returns false because they're different objects (regardless of their contents).

Wyzard
  • 33,849
  • 3
  • 67
  • 87
0

== checks the reference, not the object itself. If you write

String a = "meow";
String ab = a;

then

System.out.println(a == ab);

will give you true.

If you want to compare Strings you should use equals(). it will be:

String a = "meow";
String ab = a + "deal";
System.out.println(ab.equals(abc));