Thursday, November 27, 2008

silly string problem!

Today is no different in office. We are nearing the release and test team is chucking out bugs tirelessly. Every day we have more bugs to fix :( As usual i started to work on with a high severity bug. I found the cause without any problem.

But then came a surprise to me. We have a function which takes an array and returns the index of any object you are looking for. So we have an array with few entries and search for an string which is there in the array. But the returned -1 (not found).

I am surprised and puzzled. One things i did was to replace the == with equals method and it worked well. But what I am not clear is why == didn't work. Since string is immutable any string object which has same data will be interned to the same reference in the string pool.

Then I searched on google and found that if any one of the string is read from file, then it is not interned.

consider the following code:
public class Test {

/**
* @param args
*/
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("c:\\test.txt"));

String str = reader.readLine();
str = str.trim();
String str2 = "A";
System.out.println(str==str2);

reader.close();
}

public final static int indexOf(T[] array, T t) {
for(int i = 0;i
if(array[i]==(t)) {
return i;
}
}
return -1;
}

}

content of the file is just "A", what do you expect the program to print? true? you are wrong.. answer is false. This is where we have to use the intern function in the string class.

Hope somebody will find it useful!!

1 comment:

Unknown said...

ithu blogaa illa java discussion forumaaa!!!!! over scene odumbukku aagathu thambi...