jQuery in Action, 2nd edition*
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "efficiency" Watch "efficiency" New topic


Mathew Kuruvilla
Ranch Hand

Joined: Nov 27, 2001
Posts: 135
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: 135
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: 24183

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: http://aspose.com/file-tools
subject: efficiency
Similar Threads
Swing - Content Pane vs. Panel - have I got this right?
Java Batch Program Design
Are 2 arrays more costly than 1 in 2D?
Look for a excellent script for Java
HTML page-tomcat servlet interaction