Logical Operators

NOT operator

We've already used the 'Not' operator in the If statement tutorial, but to recap - we simply place an exclamation mark ! in front of the boolean value we are checking, to reverse its value. Consider the following example:

if (!over20DegreesC) {
    //turn heating on
}
If over20DegreesC is true, then the application of ! evaluates to false (i.e. NOT true), and the heating is not turned on.

Conversley, if over20DegreesC is false, the application of ! evaluates to true (i.e. NOT false), and the heating is switched on

AND and OR operators

Logical operators allow use to check if one condition and another condition are met. Alteratively they can be used to see if one condition or another condition is met. It's also possible to see if a conditon is not met

Lets say we are tring to offer someone an alcoholic drink, we've already looked at checking if they are over 18, but it's increasing likely that they may choose not to drink alcohol, one way to do that would be to nest if statements as follows:

if (over18) {
    if (!teetotal) {
        System.out.println("Have a beer");
    } else {
        System.out.println("Have a Lemonade");
    }
} else {
    System.out.println("Have a lemonade");
}
This is less than ideal because we have repeated code.

AND operator

It would be better to check that they are over 18, and not teetotal, and we can do that using the and operator: &&. The code would instead look like this:

if (over18 && !teetotal){
    System.out.println("Have a beer");
}
else {
    System.out.println("Have a lemonade");
}

OR operator

This is not the only way we could have programmed it however - we could also say that if someone is under 18, or teetotal then they should be offered lemonade, and we could write the code that way instead this time using the or operator: ||. In this case the code would appear as follows:

if (!over18 || teetotal) {
    System.out.println("Have a lemonade");
}
else{
    System.out.println("Have a beer");
}