0

why the result is false? could someone please explain?

public class StringTest1 {
    public static void main(String[] args) {
    String a="a";
    String b=a+"b";
    String c="ab";
    System.out.println(b==c);
    }
}
Monika
  • 325
  • 1
  • 2
  • 9
  • `String a` is a reference to a String so when you do `b == c` you are comparing references to Strings and those references are not the same, even if the objects referenced contain the same data. – Peter Lawrey Jan 20 '16 at 10:56
  • Thanks for the response. – Monika Jan 20 '16 at 10:58
  • Here is a related common gotcha of using Java I recommend you read http://stackoverflow.com/questions/1700081/why-does-128-128-return-false-but-127-127-return-true-in-this-code – Peter Lawrey Jan 20 '16 at 10:59
  • Note that the result might not be false if you declared `a` `final`. – Andy Turner Jan 20 '16 at 11:02

2 Answers2

1

Because they don't point to the same object in the memory.

== is used for comparison of either primitive types, or object references.

What you want to do, is to compare their values, for which you 'll need to use the equals(Object o) or equalsIgnoreCase(Object o) method(s)

Stultuske
  • 9,296
  • 1
  • 25
  • 37
0

Output of this comparison is FALSE because you have created two objects which have different location in heap so == compare their reference or address location and return false.

Read more: http://java67.blogspot.com/2012/11/difference-between-operator-and-equals-method-in.html#ixzz3xmRzfSkP

Lucky
  • 16,787
  • 19
  • 117
  • 151