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("Equal");
else
    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 5 Years Ago by anand01: n/a

Try using the

.equals()

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

==

is not used for Strings.

Edited 5 Years Ago 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.