Skip to content

Logical Operators

Logical operators are used to create and combine multiple expressions to create a set of values to compare against.

As an example we are given a task to evaluate if a temperature is within a range that is considered warm.

int temperature = 22;
boolean isWarm = temperature > 20 && temperature <30;
System.out.println("Is it warm? " + isWarm);

Java evaluates the above statements from left to right here we are using the && (and) operator to evaluate our value against two conditions providing an upper and lower limit.

boolean hasHighIncome = true;
boolean hasGoodCredit = true;
boolean isEligibleForLoan = hasHighIncome || hasGoodCredit;
System.out.println("Are you eligible for credit? " isEligibleForLoan);

Here we are using the || (OR) Logical Operator to evaluate our conditions from left to right returning loan eligibility, should hasHighIncome be set to false and hasGoodCredit true, the program would return true as it would continue evaluating and return the last statement accordingly.

boolean hasHighIncome = true;
boolean hasGoodCredit = true;
boolean hasExternalRisks = false;
boolean isEligibleForLoan = (hasHighIncome || hasGoodCredit) && !hasExternalRisks;
System.out.println("Are you eligible for credit? " + isEligibleForLoan);

We have now added another condition to check for loan eligibility by using the ! (NOT) operator. The ! (NOT) operator reverses the boolean value. If the original condition is true, ! will turn it into false, and vice versa..

Our final eligibility criteria to provide a loan now becomes:

  • Has a high income.
  • Has good credit
  • Does NOT have external risks

We have also wrapped our original two conditionals in brackets reverting to a single truthy being required as the first parameter of isEligibleForLoan