Oddities Explained

A number of people have been asking me about the strange bits of code in my previous blog post, so I felt I should explain a bit.

The Javascript

The reason why this…

'5' + 3

… gives you 53 is because javascript’s concatentation operator is the plus sign, and when it sees a string on the left operand, it forces the right operand to be promoted to a string, and then performs concatenation.

The precise opposite occurs when the operator is the minus sign.

'5' - 3

The operator minus is the mathematical subtraction operator, and so when it looks at the operands, it promotes both sides to a numeric type, and performs the subtraction.

The Java

So why on earth does Java think this is OK ?

Integer foo = 1000;
Integer bar = 1000;
 
foo <= bar; // true
foo >= bar; // true
foo == bar; // false

This is because the act of doing the assignments at the top sets the underlying primitive int to be of value 1000, but the actual variables themselves are of type Integer, which is an object to wrap the int. Therefor, when you do a numeric comparison with either >= or <= it will use the primitive type underneath, whereas when you use the == operator, it tries to compare the objects, which are 2 different instantiations of Integer objects, and are therefor not equal.

Hope this helps.

Posted: December 15th, 2010 | Author: | Filed under: Uncategorized | Tags: , | No Comments »

Leave a Reply