-2

I wrote the following JAVA code in eclipse,

String s1 = "a";
String s2 = s1 + "b";
String s3 = "a" + "b";
System.out.println(s2 == "ab");
System.out.println(s3 == "ab");

The output is

false 
true

why the result is like that, can some explain it to me? as I understand, both of them should be true.

Coinnigh
  • 611
  • 10
  • 18
  • 2
    `String s3 = "a"+"b";` is compiled to `String s3 = "ab";` so it uses the same literal string `"ab"` that you are comparing it to. – khelwood Dec 02 '15 at 15:20
  • 1
    The second example prints `true` because both are pointing to the same string in the [Java String Pool](http://stackoverflow.com/questions/2486191/what-is-the-java-string-pool-and-how-is-s-different-from-new-strings) – GriffeyDog Dec 02 '15 at 15:22

1 Answers1

-1

We do not use == to compare Strings in java. It will compare the object references to system memory.

You have several options:

  • equals
  • equalsIgnoreCase
  • matches (Regex)

In your example you defined two Strings. Both will live in different memory locations. == compares only the reference to that location and will find that it is not the same, since you are calling it on two different Strings.

The second comparison is true because java only added one "ab" to memory, hence it will point to the same location. See: java string pool

showp1984
  • 378
  • 1
  • 2
  • 13
  • I know we can use equals method, but I want to understand why the result is like what I wrote in my question. – Coinnigh Dec 02 '15 at 15:16