Tag Archives: java

Floating point precision

float

A floating point. Well, a floating doughnut.

How do you compare two numbers for equality? Use the equality operator of your language-of-choice, right? Well, not exactly. For example, consider the following code (in Java):

int i = 2 * 5;
if (i == 10) {
...do something
} else {
...do something else
}

and this one:

float f = 2 * 5;
if (f == 10) {
...do something
} else {
...do something else
}

What would be the end result? The correct answer is that the first if block always returns true, while we cannot be so sure about the second one. But why?

Continue reading

String interning

javaMany beginners of Java are taught never to use == operator for string equality, but to use .equals() method instead. :

if (strMyString == "ok") {
... do something
}

The reason is that when comparing primitives, == operator checks if their value is the same. But when comparing objects (like Strings), it checks if two are actually the same object. If not, comparison returns false even if the two objects have exactly the same content.

After reading the above explanation, you may be amazed that the following code returns true:

String s1 := "foobar";
String s2 := "foo" + "bar";
return (s1 == s2);

How can the == operator think that s1 and s2 are the same object when they are clearly not?

Continue reading