1 + 1 ≠ 2

When Mood Music
2012-04-20 16:05:00 annoyed, puzzled In The City – Razorlight

Following on from here, take a look at this code:

package _06Swampless_JUnitTests;

public class testString {

public static void main(String[] args) {
String piece1 = “donkeyOGREsnake”;
String piece2 = “donkeysnake”;
String piece3 = piece1.replace(“OGRE”, “”);
if (piece3 == piece2) {
System.out.println(“piece1: ” + piece1);
System.out.println(“piece2: ” + piece2);
System.out.println(“piece3: ” + piece3);
} //end main

} //end class

This sets up pieces of text which are identical except the first one has some extra characters, namely “OGRE” . A third piece is created as the first one minus “OGRE”. So the third piece should be the same as the second. The if block will print ‘yeehah’ if this is true and ‘boo hiss’ if they’re not.

The actual output is:
piece1: donkeyOGREsnake
piece2: donkeysnake
piece3: donkeysnake

So two identical-looking pieces of text are in fact not identical. Bah!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.