Archive for August, 2008
Debugging – Story of String Pools
String pools our friends can at times become out worst enemies. The nightmare story goes like this.
Ramu is a C programmer and he was one fine day asked to write a java program which was never his interest or expertise. Ramu read all the docs he could get on java programming and gave his best to write that java code. It got build and after regression testing, it was approved to be integrated with the mainstream application.
After adding this piece of logic/code to the application, it got tested in one particular application server. Everything went well and the code got released successfully. But the evil bug inside was waiting for it’s chance.
Ramu left the job and somu replaced him. One day suddenly the bug exploded. Somu our hero of the story is pretty good in debugging and tried to trace. He managed to find where the code fails and it was a condition check. This was of course not a logical mistake and much worse no system exception was thrown to stop the program execution.
The problem was that ramu tried to compare two string references rather than the value. But since it’s a String type, the string pool made it chaotic that both the references referred to the same object in spite of immutability. String pool nullifies the mutability issue till the data/value remains unchanged. Because of this String pool, this problem never rose.
The condition was:
ordered = “coffee”
orderServed= “coffee”
Ramu’s Code:
if ( ordered == orderServed)
In this case since both the strings are same, the reference matching worked(string pools to the rescue). But what happens when string pools are disabled. There are two instances (immutable of course).
The right code (non C-style comparison) would be to compare the actual values and not the addresses.
Somu’s code correction:
if ( ordered.equalsIgnoreCase(orderServed) ) // or equals()
Finally it was a happy ending. Even though this was a blunder, the program logically did well as it was intended.
1 comment August 8, 2008