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?

1

2 Answers 2

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!
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

x.equals(z)

2 Comments

Why different ? "Hello World" is in String Pool and x and z point to the same String
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().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.