Wednesday, March 19, 2008

Groovy is kinda really groovy

public class StringTester { 
    public static void main(String[] args) {
        System.out.println(new String("foo") == "foo"); 
    }
}

Now the above code will evaluate to false. However if I changed it to:
"foo" == "foo"
it will be true. Reason: Java interns String literals. This is precisely why using == on String isn't advised. However groovy converts all == instances to .equals() so we basically get the same result as if we interned the String in java. This makes sense, since in groovy there are no primitive data types; it uses the wrapper classes from java. Integer, Double, Byte, etc. More information about the wrapper classes can be found here.
class StringTester { 
    static void main(args) {
        println new String("foo") == new String("foo") 
        println new String("foo") == "foo"
        println "foo" == "foo" 
    }
}

All three cases will evaluate to true. Now we can modify the java code so that it behaves the same way groovy did:

public class StringTester { 
    public static void main(String[] args) {
        System.out.println(new String("foo").intern() == "foo");
        System.out.println(new String("foo").intern() == new String("foo").intern()); 
    }
}

Now both will evaluate to true! Interesting thing =)

For more information about interned Strings check out this

2 comments:

Indy said...

Interesting.

BTW, I normally use "assert" rather than "prinln". I find that it is a much nicer way test.

Robby O'Connor said...

Yeh I know; i didn't care here =)