Behavior of &&

public class BusinessRulesTrab212 {

public int Save(int newcod, String obs)

throws ClassNotFoundException, SQLException {

// DataAccessTrab212 t = new DataAccessTrab212();

return 1 // t.Insert(newcod, obs);

}

}

--

and ...

BusinessRulesTrab212 t = new BusinessRulesTrab212();

boolean r = false;

r &&= (t.Save(newcod, obs) == 1);

--

Java dont call the function Save from Object t, and allways r gets a value of false. Why this code doesnt work?.

[537 byte] By [gescobara] at [2007-10-2 6:25:05]
# 1

r &&= (t.Save(newcod, obs) == 1);

I never knew you could do &&= but if it compiles, I guess it's equivalent to r = r && whatever;

Now, since you initialize r to false, it's equivalent to r = false && whatever;

false && anything is always false.

targaryena at 2007-7-16 13:26:55 > top of Java-index,Java Essentials,Java Programming...
# 2

&& is the logical AND operator. Java will stop evaluating results as soon as it encounters a single false value. Because your r value is false and it is on the left hand side, it is evaluated first, and that will always cause the && to fail, so it doesn't even bother with the right hand side of the operation.

carr_onstotta at 2007-7-16 13:26:55 > top of Java-index,Java Essentials,Java Programming...
# 3
doh, too slow
carr_onstotta at 2007-7-16 13:26:55 > top of Java-index,Java Essentials,Java Programming...
# 4

> doh, too slow

But you did add the important point that t.Save() will never get called due to th short-circuit boolean.

@OP: If you wanted t.Save() to be called even if the LHS of the AND was false, you could use & instead of &&. && short-circuits, but & always evaluates both sides.

Note that r = false & whatever will still leave r false though.

targaryena at 2007-7-16 13:26:55 > top of Java-index,Java Essentials,Java Programming...
# 5
> && is the logical AND operator. Be careful with the terminology; the & operator is also a logical operator when the operands are boolean. The JLS refers to && as "Conditional-And".
yawmarka at 2007-7-16 13:26:55 > top of Java-index,Java Essentials,Java Programming...
# 6
Thanks !!!
gescobara at 2007-7-16 13:26:55 > top of Java-index,Java Essentials,Java Programming...