5
public class Foo {

    public static void main(String[] args) {
        foo();
        bar();
    }

    public static void foo() {
        String s = "str4";
        String s1 = "str" + s.length();
        System.out.println("(s==s1)" + (s1 == s));
     }

    public static void bar() {
        String s = "str4";
        String s1 = "str" + "4";
        System.out.println("(s==s1)" + (s1 == s));
    }
}

OUTPUT

(s==s1)false

(s==s1)true

At String s1 = "str" + s.length(); the value of s1=str4 but it turns out to be false at next sysout statement during double equal (==) check

*/

Sirko
  • 72,589
  • 19
  • 149
  • 183
  • 1
    @delnan Not really, read through it again. – Anubian Noob May 02 '14 at 14:43
  • 3
    It's definitely a duplicate, but not of that. – Sotirios Delimanolis May 02 '14 at 14:43
  • 1
    @AnubianNoob and others: The question as asked is not literally the same, but the underlying problem is the same and the answers over there completely answer it. –  May 02 '14 at 14:44
  • 2
    We have 3 hasty answers, 2 comments, and 6 flags... This question isn't really a duplicate, nor is it about comparing strings using `.equals()`. It's more about Java's memory management. – Anubian Noob May 02 '14 at 14:46
  • I believe one of the answers in that post does explain this, though. I too voted too quickly as duplicate (of that particular question). – Reinstate Monica -- notmaynard May 02 '14 at 14:47
  • If nothing else: http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.5 – Reinstate Monica -- notmaynard May 02 '14 at 14:48
  • 6
    possible duplicate of [Java String literals concatenation](http://stackoverflow.com/questions/16771122/java-string-literals-concatenation) – Sotirios Delimanolis May 02 '14 at 14:48
  • @AnubianNoob Any question about == vs. equals necessarily touches on string interning (what I presume you mean by Java's memory management), and answers do answer that. In that case, the immediate cause is interning and constant folding of literal concatenation, but that is explained by the question I linked to and many others nominally about something different. What's now suggested as duplicate is closer, but I don't think the one I proposed would have been wrong or harmful as duplicate. –  May 02 '14 at 14:50
  • 1
    @SotiriosDelimanolis: Or [this one, which seems more similar](http://stackoverflow.com/questions/16729045/behavior-of-string-literals-are-confusing). – T.J. Crowder May 02 '14 at 14:50

1 Answers1

10

That's because "str" + "4" is compiled as "str4".

String s = "str4";
String s1 = "str" + "4";

For the compiler, it will be:

String s = "str4";
String s1 = "str4";

Note that "str4" is a literal String and it will be stored in String pool.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332