-2

Edited: I have tested this code in java and the printed output was "true", while the compiler compares the reference and not the value of Strings why this is "true"?

public class Main {    
    public static void main(String[] args) {        
        String s1 = "string";
        String s2 = "string";
        System.out.println(""+(s1==s2));
    }
}
Mansour
  • 445
  • 1
  • 4
  • 14

4 Answers4

3

The String equality rules have not changed in Java 8 and s1==s2 prints always true in this case since they both point to the same memory location in constant pool, which typically located on heap memory.

I just checked with Java6 and it's true.

nalply
  • 26,770
  • 15
  • 78
  • 101
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Ok, Thank you. I was wrong. I replaced the statement "System.out.println(""+(s1==s2));" with this two statements and the result was "false". Thanks. String s3 = "stringstring"; System.out.println(""+(s3==s1+s2)); – Mansour Sep 15 '15 at 10:24
  • @Mansur Answer after edit of question : because both point to the same memory location in constant pool. – RishiKesh Pathak Sep 15 '15 at 10:36
1

There has been no change, the == operator checks if two references point to the same object. String literals are placed in the string pool. So "string" is placed in the string pool, s1 and s2 both point to that, hence an output of true.

RamanSB
  • 1,162
  • 9
  • 26
1

In your edited question, you have defined two String literals. As per JLS § 3.10.5 these literals are interned:

a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Therefore reference equality using == will always return true for s1 == s2 where:

String s1 = "string";
String s2 = "string";

The JLS states (almost exactly) the same for Java 7 and Java 6

Note though that there are some subtle differences in the way string interning works between certain JDK versions. See, for instance "intern() behaving differently in Java 6 and Java 7"

Community
  • 1
  • 1
Andy Brown
  • 18,961
  • 3
  • 52
  • 62
0

It is up to the compiler to decide, in this case, whether s1 == s2. The condition is testing whether s1 and s2 are the same object. This is likely to be true, as a sensible compiler would have a constant pool, but not necessarily so.

However, your intent is comparing the strings, not the objects, so equals() is the correct method and the use of == is incorrect for that.

Limnic
  • 1,826
  • 1
  • 20
  • 45