This little beauty was spotted in my struts code by a colleague of mine, clearly the result of too little coffee in the morning:
ActionErrors errors = errors = new ActionErrors();
Whilst I say this is a mistake, it actually complies and works. Here I’m assigning an object reference twice. It also works with multiple references:
Long p;
Long l = p = new Long(10);
Which results in both p
and l
are referencing the same object. It has to be said that I can’t think of a single legitimate reason why you’d want to do this – I blame the lack of coffee this afternoon for me spending even this much time on it…
3 Responses to “Brain hurting mistakes of our time”
Yeah, it’s an interesting little known feature of Java assignment operators. In terms of ‘operator overloading’, it is essentially ‘returning’ the value of the assignment after performing the assignment on the variable.
That’s why:
boolean c = true;
boolean b = false;
if(b=c) {
System.out.println(“text”);
}
compiles and prints out text; unlike:
if(b==c) {
…
}
which doesn’t.
wheee!
For that matter, you’ll also get the behavior that
boolean c = true;
boolean b = false;
if(b=c) {
System.out.println(“text”);
}
will always print, but
if (c=b) {
System.out.println(“text”);
}
will never print. Probably caused more than one VB developer to give up… Once I spent an hour trying to figure out why
if (somemethodcall(c));
{
System.out.println(“text”);
}
would always print even as I stepped again and again through the method observing that I hadn’t botched the logic and that it really should be returning false…
Making ActionErrors final (which I do by habit) would’ve spotted the first case.