0

I can not understand why code below returns "false"

String x="Hello World";
String z=" Hello World".trim();
System.out.println(x==z); //false

I have read that "Strings are immutable and literals are pooled".After executing trim(), z will be z="Hello World" and then why output is not true?

Gunel
  • 23
  • 1
  • 8
  • This(http://stackoverflow.com/questions/3689952/using-instead-of-equals-for-java-strings) can help you!! – Imran Jul 21 '16 at 06:59

2 Answers2

2

You're comparing the pointers to the objects, which will be different. For strings you should use:

x.equals(z)
Binary Nerd
  • 13,872
  • 4
  • 42
  • 44
  • Why different ? "Hello World" is in String Pool and x and z point to the same String – Gunel Jul 21 '16 at 07:00
  • `x` and `y` are different `String` objects, its only the contents that are the same. To compare the contents for equality you have to use `equals()`. – Binary Nerd Jul 21 '16 at 07:04
2

It's because Strings are immutable! Because of that the trim() method returns a new instance of String which has a different reference. You can see it by watching the source code.

public String trim() {
    int len = value.length;
    int st = 0;
    char[] val = value;

    while ((st < len) && (val[st] <= ' ')) {
        st++;
    }
    while ((st < len) && (val[len - 1] <= ' ')) {
        len--;
    }
    return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}

public String substring(int beginIndex, int endIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    if (endIndex > value.length) {
        throw new StringIndexOutOfBoundsException(endIndex);
    }
    int subLen = endIndex - beginIndex;
    if (subLen < 0) {
        throw new StringIndexOutOfBoundsException(subLen);
    }
    return ((beginIndex == 0) && (endIndex == value.length)) ? this
            : new String(value, beginIndex, subLen); // new instance!
}
kai
  • 6,702
  • 22
  • 38