0

Can you explain me why do I have "false" output? If I understand correctly, references point to the same object!

public class mainC {
    String str1,str2;
    public static void main(String [] args){
        mainC m=new mainC();
        m.str1="a";
        m.str2="b";
        System.out.print("m.str1 == m.str2: "+m.str1 == m.str2);
    }
}

Thank you.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
George Revkov
  • 95
  • 3
  • 8

2 Answers2

5

m.str1 and m.str2 point to different String objects, which is why you get false. The == compares str1 and str2, not m.


Side note: Now, if you had:

m.str1="a";
m.str2="a"; // Same series of characters, e.g., "a"

...you'd be getting true, but it would be misleading. == compares object references. So you can have two different String objects that have the same characters in them, but they would not be == to each other (in fact, that's quite common). To compare strings, you use equals. The reason my example above returns true is that both strings are initialized pointing to literals, and String literals in Java are intern'd by default, so that literals with the same characters are mapped to the same object.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • So, they're both in String Literal Pool, but they have different objects because of different values? And if I create one new object of mainC class, then assign str2 as "a" and then try to compare them (==), I'll have true result. Correct? – George Revkov Jun 09 '13 at 22:39
  • @GeorgeRevkov: *"So, they're both in String Literal Pool, but they have different objects because of different values?"* Right. Literals with different sequences of characters will be different objects. *"And if I create one new object of mainC class, then assign str2 as "a" and then try to compare them (==), I'll have true result."* It doesn't matter how many objects you create. If you assign a **literal** `"a"` to them, you'll get the same `"a"` object each time (and similarly for the `"b"` object, which is different from the `"a"` object). Because literals are interned. – T.J. Crowder Jun 09 '13 at 22:44
  • Also note that there is a difference between `"a"` and `new String("a")` - play around with equals to find out what it is. – selig Jun 09 '13 at 23:16
0

A string in Java is implemented as a reference type and not a value type. Since this is the case, their pointers in memory aren't equal. To get around this, you can use their equals function to compare them.

Community
  • 1
  • 1
Vaughan Hilts
  • 2,839
  • 1
  • 20
  • 39