0

When I perform the == operator comparison, I'm seeing false though I'm expecting the value to be true.

Why does this happen?

public class String1 {
    public static void main(String[] args) {

        //case 1
        String s1="Hello";
        String s2=s1+"Java";
        String s3="HelloJava";
        System.out.println(s2.equals(s3));// true
        System.out.println(s2==s3);// expected True but getting output False  
        System.out.println(s2);
        System.out.println(s3);

        // case 2
        String x = "hello";
        String y = "he" + "llo";
        System.out.println(x == y);// TRUE as exepected
    }

}
anacron
  • 6,443
  • 2
  • 26
  • 31
  • The compiler hard-codes the concatenation result only if all Strings involved are constant. You need to make the variables `final` to get that. But I may be completely wrong there and don't really care, because there is no need to ever depend on that. Just use `equals` to compare Strings. – Thilo Sep 26 '16 at 06:38

2 Answers2

1

In Java the == operator tests reference equality -> same object

.equals() tests for value equality

in both of your cases you have different objects (s1, s2, x, y)

Lennart
  • 52
  • 3
  • But I am comparing S2 with S3 both have same values as "HelloJava" and when I am checking s2 and s3 with equal to (==) operator ,the result should be True as both are pointing to the same "HelloJava".Can you please explain why S2 and S3 shows false. –  Oct 03 '16 at 13:24
0

== compares references (i.e. pointer values) of objects.

In case 2 the compiler can shorten "he" + "llo" to "hello" as opposed to the first case where the concatination is performed at runtime.

Also string literals are cached in a pool. Thus two occurences of "hello" will normally refer to the same object. This is possible because strings are immutable.

Strings follow the same rule as every other object. If you want to compare pointers use ==, if you want to compare content use equals.

Erik Hofer
  • 2,296
  • 2
  • 18
  • 39