Assignment in if is OK for Java, because Java does not allow you write something like this by mistake (code updated, thanks nicckk):
String str = "not test";
if (str = null) { // oops, = instead of ==, but compiler will show you error, because it only accepts boolean value here
// process
}
but you still can write this:
boolean condition = false;
if (condition = true) { // oops, = instead of ==, but compiler can't help you
System.out.println("Oops");
}
but typically above code will look like this:
boolean condition = false;
if (condition) {
//
}
So your first code is OK for Java, but still can be problem in rare situations. Other languages that does not have strong type checking use some tricks to avoid this problem, for example PHP:
$condition = true;
if (true = $condition) { // note reverse order, you can't assign to true, so interpreter will show error
// process
}
But in Java there is no need for it.
Edited by Vladimir, 07 November 2010 - 12:09 PM.