Hi all,
I know " String ".trim is used to remove the blank spaces but when i use the following string compare its shows some strange result

if(" String ".trim() == "String")
    System.out.println("Not Equal");

It produces the result of not equal. How it produces the result like this can any one explain me.
thanks in advance

Edited by anand01: n/a

6 Years
Discussion Span
Last Post by anand01

Try using the


method on the first String. It would be good for you to investigate why


is not used for Strings.

Edited by adarshcu: n/a


more complete explanation:
"String" will refer to a String constant on the String constant pool.
" String " refers to another String constant on the String constant pool.
" String ".trim() refers to a String instance on the heap.

The left and right operand of your comparison then are two different String instances. The == operator compares whether two object instances refer to the same instance, not whether they have a content identity (iow, whether two object instances are identical on a field comparison).
the equals() member method (as indicated in the previous answer) does that.

== will work for low Number instances referring to Integers and Longs because it has been specifically overridden for that purpose, but that's an exception to a very strict rule.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.