This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
What are efficiency implications of int a = 5; if (3 == a)......vs if (a == 3) Why is the former preferred?
I was told the answer to this when I was learning Java, but I forgot.
Joined: Nov 27, 2001
Sorry, the reason is not efficiency. It has to do with good coding standards. Suppose we wrote "if (a = 3)" by mistake instead of "if (a == 3)", the code will still compile assuming it as an assignment. But the results will not be as expected.
BUT if we wrote "if (3 = a)" it will get caught in the compilation time itself and we'd know that it should have been "if (3== a)"
Believe me, this happens to even experienced programmers (not me, no). . . .
This is true for C and C++, but not for Java except in one very limited case. "if (a=3)" won't compile because "a=3" is not a boolean expression. In C/C++, the expression in the parentheses is an integer, so this problem is quite real in those languages.
Now, in Java, you can make this mistake with boolean variables; you can write "if (a=true)" by mistake. The correct way to deal with this, though, is to enforce the rule that one must never compare to a boolean literal. There's never a reason to write "if (a==true)", because "if (a)" suffices. Similarly, "if (a!=true)" is equivalent to "if (!a)".
A related issue is "if ("hello".equals(s))", with s being a String variable. If you write things the way I've shown, the code works if s is null. If you write it the other way around -- "if (s.equals("hello"))" -- then when s is null, you'll get an exception at runtime.