String Equality and Interning
by, 04-26-2012 at 07:29 PM (484 Views)
In Java Strings are the objects however they resemble primitives like charS or intS. In that java source, code may be having the String literals and + operator might be used to concatenate the Strings. These features are quite convenient, however similarity present b/w Strings & primitives may cause certain confusions, when comparison is done of the Strings.
Two mechanisms are provided by Java to do the test for equality. Use “==” operator for testing of the primitive values equality. It might also be used to find out whether 2 object references are being pointed at the similar underlying objects. The equal(Object) method return to be true for java objects when argument is equivalent to that object at which method gets invoked. This happened when class semantics of object are used to define the equality.
Strings are the objects. To return the equals(Object) method true, two strings shall be having similar content which means similar characters shall be there in similar order. The == operator is considered to be true only when 2 string references will be pointing at similar, underlying String object. Therefore, same content is presented by 2 strings that would be equal when test is done by the equal(Object)method.