A coworker just ran into an interesting feature in Java that created a subtle bug. Most Java programmers know what the += operator does when used like this:

op1 += op2

Basically op2 is added to the value of op1 and then assigned to op1. So, for example:

        int bankAccount = 2000;
        bankAccount += 100;
        // bankAccount now contains 2100

Well, what happens in Java if you accidently type =+ instead of +=?

He didn’t know, I didn’t know, and another excellent Java programmer here had no idea either. So, off to look at the list of Java operators to make sense of it.

I’ll post the answer after the jump.

The answer is that Java also uses + as a unary operator like so:

+op1

And, it doesn’t do what you think, at least, not what I thought it should do. Basically, the + promotes a primitive short, byte, or char to an int. Because Java requires no spaces, the = sign becomes an assignment operator just like we all normally use. And, you get a very nasty bug. Using the same code snippet above, here’s the example:

        int bankAccount = 2000;
        bankAccount =+ 100;
        // bankAccount now contains 100
        // and someone is pissed ☺

I learned something new today and just wanted to make note of it so I didn’t forget.