Precedence of Logical Operators

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

An applicant must meet two conditions:

  • 4 or more years of college, AND
  • 2 years experience programming in Java OR a grade point average greater than 3.5.

Answer:

if (   college >= 4   &&   ( experience   >= 2   ||    gpa > 3.5  ) )

  System.out.println("Interview applicant");

else

  System.out.println("Send resume to circular file.");

Precedence of Logical Operators

Operatorprecedence
!High
&&Medium
||Low

You have seen that when expressions mix && and || that evaluation must be done in the correct order. Parentheses can be used to group operands with their correct operator, just like in arithmetic. Also like arithmetic operators, logical operators have precedence that determines how things are grouped in the absence of parentheses.

In an expression, the operator with the highest precedence is grouped with its operand(s) first, then the next highest operator will be grouped with its operands, and so on. If there are several logical operators of the same precedence, they will be examined left to right.


For example, say that A, B, C, and D stand for relational expressions (things like 23 > 90). Then,

A || B && CmeansA || (B && C)
A && B || C && Dmeans(A && B) || (C && D)
A && B && C || Dmeans((A && B) && C) || D
!A && B || Cmeans((!A) && B) || C

It is common for programmers to use parentheses to group operands together rather than rely on logical operator precedence rules.

QUESTION 16:

Add parentheses to the following to show how operator precedence groups operands:

a > b && 45 <= sum || sum < a + b && d > 90