Saturday, October 9, 2010

What is String Internization

HI,

What is String Interization.
Strings can be COmpared by ways.
1) using operator " =="
2) using the method equals of Object class.

1) The Operator "==" compares two strings objects and returns true if and only the
 Two References point to same Object .
Example :
String firstReference = new String("Sekhar");
String secondReference = new String("Sekhar");
now :
if(firstReference == secondReference){
Syso("Equal");
}
else{
Syso("Not equal");
}

the Above Example Returns "Not Equal" because the here the two references ('firstReference' & 'second Reference') points two Different Instances.

then how to get Result as "EQUAL"
Here is the Technique "String INternization"

String firstReference = new String("Sekhar").inter();
String secondRefernce = new String("Sekhar").intern();
if(firstReference == secondReference)
{
Syso("Equal");
}
else
{
Syso("Not Equal");
}
In this It Returns the EQUAL.

To save memory (and speed up testing for equality), Java supports “interning” of Strings.
When theintern() method is invoked on a String, a lookup is performed on a table of interned Strings. If a String object with the same content is already in the table, a reference to the String in the table is returned. Otherwise, the String is added to the table and a reference to it is returned. The result is that after interning, all Strings with the same content will point to the same object. This saves space, and also allows the Strings to be compared using the == operator, which is much faster than comparison with the equals(Object) method.
Confusion can arise because Java automatically interns String literals. This means that in many cases, the == operator appears to work for Strings in the same way that it does for ints or other primitive values. Code written based on this assumption will fail in a potentially non-obvious way when the == operator is used to compare Strings with equal content but contained in different String instances.

Check out this Example. :
package newPackage;
import myPackage.*;

public class Another {

public static void main(String[] args) {
// TODO Auto-generated method stub

String s1 = new String("sekhar");
String s2 = new String("sekhar");
if(s1.equals(s2)){
System.out.println(" Two Strings are Equal ");
}
else{
System.out.println("Two Strings are not Equal using equals method.");
}
if(s1 == s2){
System.out.println(" String are Equal using the == Operator");
}else{
System.out.println(" Strings are not Equal using the == Operator.");
 }
}
}
The Output of the Above Program.:
Two Strings are Equal using the equal method.
Strings are not Equal using the == Operator.

Important Note: It follows that for any two strings s and t,
 s.intern() == t.intern() is true if and only if s.equals(t) is true.






No comments:

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...