Shetty's
Shetty's

Reputation: 617

Confused with output while working with Strings

    String sb1 = new String("Soft");
    String sb2 = new String("Soft");

    System.out.println("ANS1->" +sb1 == sb2);
    System.out.println(sb1 == sb2 + " After result");
    System.out.println("ANS2->" +sb1.equals(sb2));

This leads to output as below, but i dont understand why "ANS1" and "After result" texts are not displayed. Kindly help on this.

false

ANS2->true

Upvotes: 1

Views: 53

Answers (2)

TheLostMind
TheLostMind

Reputation: 36304

Because : "ANS1->" +sb1 == sb2 ==> ("ANS1->" +sb1) == sb2. Now, the compiler does this and prints false because ("ANS1->" +sb1) !=sb2.

Even : System.out.println("ANS1->" +sb1 == sb1); prints false :P

Upvotes: 5

Christian St.
Christian St.

Reputation: 1911

In addition to TheLostMinds´ answer:

System.out.println("ANS1->" + (sb1 == sb2));
System.out.println((sb1 == sb2) + " After result");

Now you see the "lost" strings.

Upvotes: 1

Related Questions