This site requires JavaScript, please enable it in your browser!
Greenfoot back
danpost
danpost wrote ...

2012/2/7

'If' statement in the Java language

danpost danpost

2012/2/7

#
I had recently seen an example in one of the tutorials with the following statement
if ((s != null) && (s.length() > 0))
The coding leads me to believe that the first condition is checked first, and, only if it passes the test then the second condition is checked. Is this actually the case, or should they have used imbedded 'if's?
iau iau

2012/2/7

#
That's right. Both && and || in Java "short-circuit": they do not evaluate their right-hand-side if their left-hand-side makes it pointless. In (a && b), b will only be evaluated if a is true In (a || b), b will only be evaluated if a is false This is to allow precisely the code you quote, where evaluating b would be fatal if a is false. This idea goes back to the language BCPL in about 1970, one of the direct ancestors of C, C++ and Java.
danpost danpost

2012/2/7

#
Thanks for the clarification, iau. That will certainly eliminate some white-space in my code (and make it more readable)!
sp33dy sp33dy

2012/2/7

#
Dan, Also, the following code is often very useful:
c = (a < b) ? a : b;
i.e. The variable c will receive the contents of a if it is smaller than b; otherwise b. It's very useful for removing:
if (a<b) {
  c = a;
} else {
  c =b;
}
Duta Duta

2012/2/7

#
iau, surely in (a || b) b will be evaluated whatever a may be, as it is (in terms of a logic circuit) an OR gate, rather than an XOR - as in it will execute the if() statement if they are both true (as demonstrated by the following class):
public class AClass
{
    /*
     * Outputs:
     * 01, 10, 11
     * if it was an XOR, then it would output
     * 01, 10
     */
    public static void main(String[] args)
    {
        for(int a = 0; a < 2; a++)
            for(int b = 0; b < 2; b++)
                if(a == 1 || b == 1) System.out.println(a + "" + b);
    }
}
sp33dy sp33dy

2012/2/7

#
If a equates to true, Java will never try to evaluate b. What would the point be??? As soon as one is true, the condition is passed! In reference to your example. B will be evaluated when a!=1, however, as soon as a=1, b won't be evaluated during that iteration.
Duta Duta

2012/2/7

#
Oh my bad - I misunderstood what he was saying, thanks.
danpost danpost

2012/2/8

#
sp33dy wrote...
Also, the following code is often very useful:
c = (a < b) ? a : b;
I have seen that before, but I have yet to use it. I usually would code it as follows
c = b; if (a < b) c = a;
which does eliminate the else part (but does add another statement). I would put both statements on the same code-line to show the two statements belong together.
danpost danpost

2012/2/8

#
Can you use this format with objects also? like
Player player = (moveCount % 2 == 0) ? PlayerOne : PlayerTwo;
You need to login to post a reply.