next up previous contents
Next: 3 Iteration Up: 2 Input, mathematical functions Previous: Else and else if   Contents

Logical operators

It is also possible to test whether more than one condition is satisfied at the same time. E.g.

    if ((w < z) && (a == b))
    {
        x = y;
    }
This uses what is known as the AND logical operator, which is represented in the code above by the symbol &&. It does exactly what the name suggests -- the code will set x equal to y only if both w is less than z and a is equal to b. Look carefully at the use of round brackets in the example above. These are important as the conditions within the innermost brackets are evaluated first. When these are found to be either true or false, the && operator asks whether both sets of brackets are true.

There are also other logical operators, including OR and NOT which again do rather what their names suggest.

&&
AND operator
E.g. (boo1 && boo2) returns true only if both boo1 and boo2 are true. Returns false otherwise.
||
OR operator
E.g. (boo1 || boo2) returns true if either boo1, boo2, or both are true. Returns false otherwise.
!
NOT operator
E.g. !boo returns false if boo is true and vice versa.

Exercise 2.3


(4 marks)



Look at the code given below. What is the output from this program when:

(i)
a = 1, b = 2, c = 3, and d = 4?
(ii)
a = 2, b = 4, c = 2, and d = 1?
(iii)
a = 7, b = 4, c = 2, and d = 1?
(iv)
a = 3, b = 1, c = 3, and d = 1?
Work it out by hand, then write a program to check your answers if you wish.



if ((a>b) && (c!=d))
{
    System.out.println("First if block of code executed");
}
else
{
    System.out.println("First else block of code executed");
}

if ((a==c) || (b<=d))
{
    System.out.println("Second if block of code executed");
}
else
{
    System.out.println("Second else block of code executed");
}


next up previous contents
Next: 3 Iteration Up: 2 Input, mathematical functions Previous: Else and else if   Contents
RHUL Dept. of Physics