sábado, 13 de setembro de 2008

String Interning and Equality

I was studying about Strings at Deitel book, and the String static method, internal, raised up my attention about the Java String pool mechanism.
When we create a literal String in Java, this string is placed at the String pool. So if we create other String with the same content, it will not be placed at the String pool because it already exists on memory. So the reference will point to the same object. In this case, these 2 references should be compared using the == operator. Comparing strings that are the same object with == will return true!

So, if we create 2 strings with different contents like follows:


String a = "foo";
String b = "bar";


Comparing both with == will return true? Of course not! But isn't because the difference in contents. If the contents are different theses strings will be differente objects in String pool.

Now, lets take a look in other example:


String a = "foo";
String b = new String("foo");


( a == b ) will return false!!!! both references have Strings with the same content, but they point to different objects.

The better way to compare Strings is to use equals method.

( a.equals(b) ) will return true, regardless if they are different or equal objects in memory.

But if you don't want to use equals, you can use

( a == b.intern() ), that will return true because 'a' points to String in the String pool, and b.intern returns the value that already exists in String pool. So you will be comparing the same object.

The following code shows an example of a function that compare strings using == regardless the strings are the same object or not, because if the content are the same, they will be placed at same object using intern method.


public class StringIntern {

public static void main(String[] args) {

String output;
String a = "teste";
String b = new String("teste");

// even comparing different objects this code will return true
if (StringIntern.comparaStrings(a, b)) {
output = "a and b are equal";
} else {
output = "a and b are NOT equal";
}

System.out.println(output);
}

private static boolean comparaStrings( String a, String b )
{
String c = a.intern();
String d = b.intern();
return c == d;
}
}

Nenhum comentário:

Postar um comentário