File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes efficiency Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "efficiency" Watch "efficiency" New topic


Mathew Kuruvilla
Ranch Hand

Joined: Nov 27, 2001
Posts: 141
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.
Mathew Kuruvilla
Ranch Hand

Joined: Nov 27, 2001
Posts: 141
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). . . .
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: efficiency
It's not a secret anymore!