We have already seen conditional operators (<, >, !=) etc. Logical operators are work on boolean logic and allow us to link together boolean expressions through negation, conjunction and disjunction.

In English we try and put more than one condition in a SINGLE if statement. Consider this example -

Give a special offer to people whose age is between 20 and 30.

This is an example of conjunction or AND. Our true value will be when age is in between 20 and 30. That is age >= 20 AND age =< 30. We could write this as a nested if or as a conjunction. Here is the code for conjunction -

  1. if (age >= 20 && age <=30){
  2. System.out.println("Gief special offer ");
  3. }

The && is known as a logical operator. Logical operators can ONLY apply to expressions which evaluate to true or false. For example the following code snippets are value

  1. boolean a = true;
  2. boolean b = age < 20;
  3. a = a && b;

Line 2 will evaluate age < 20. As it can only have a boolean response it is known as a boolean expression. As such the result can be stored in a boolean variable. We can then do a logical operator on both a and b as both are boolean. The result again is a boolean.

We can chain as many logical operators as we want together.

next AND truth table >>

 
Basics
Menu
Search