Expressions and Subexpressions

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

Answer:

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

Expressions and Subexpressions

a + bis an arithmetic expression
sum < a + bis a relational expression,
a type of boolean expression
d > 90is a relational expression,
a type of boolean expression
sum < a + b && d > 90is a boolean expression ... and so on ... There are many other subexpressions

The boolean expression of the question contained pieces, called sub-expressions, that are themselves expressions. It is common in Java (and other languages) to build up complicated expressions out of smaller expressions. The precedence rules and parentheses keep everything straight.

Arithmetic operators *, /, +, -, and % have higher precedence than && and || so they are done first. For example:

sum < a + b

means

sum < (a + b)

However, the not operator (!) has higher precedence than all the arithmetic operators except unary minus and has higher precedence than the other logical operators. Usually this means that you will need to use parentheses to apply it correctly.

QUESTION 17:

People may enter a contest UNLESS they are less than 21 years old, make more than $100,000, or live in Ohio. Use parentheses to group this boolean expression so that it is true when a person CAN enter the contest.

! age < 21 || pay > 100000 || home.equals("Ohio")