Expressions
Goals
- Understand and work with expressions.
Concepts
- conditional operator
- equality
- exclusive OR (XOR)
- expression
- identity
- inclusive OR
- operator
- post-increment
- pre-increment
- short-circuiting
- truth table
Lesson
An expression represents the result of some comparison or mathematical operation, such as adding two things (e.g. x + 2
) or seeing if one number or variable is greater than another (e.g. x > y
). Expressions can be made up of variables, literals, and/or symbols called operators. The result of an expression is a value of some type—normally the type of the values in the expression, but not always. Here are some examples of expressions:
5
x
x + 5
y = x + 5
true
3 == 4
Mathematical Operators
In your expressions most of the operators you'll use are those you are already familiar with in arithmetic, including +
, -
, *
, and /
. These operators for the most part have the precedence you are used to (e.g. multiplication takes precedence over addition), and you can override precedence by using parentheses (
and )
. See the References section if you have a doubt. Of special note is the %
operator, which is the remainder or modulus operator of division. You can also compare numbers using <
, <=
, ==
, !=
, >=
, and >
.
Equality Operators
You've already seen that Java uses =
to indicate a variable assignment. Two equals signs together make up an expression to determine if two primitive values are identical, such as 4 + 5 == 9
. The result of this expression is the boolean
value true
.
Logical Operators
When part or all of an expression evaluates to a boolean
type, you can use &&
(logical AND), ||
(logical OR), and !
(logical NOT). The operator &&
takes precedence over ||
, but in your own code use parentheses to keep from confusing others.
You may notice that there are certain rules that the logical operators always follow used in expressions. For example, for expressions involving ||
if either side is true
then the outcome will be true
. In an expression involving &&
both sides of the expression must evaluate to true
or the the result will be false
.
The rules of Boolean expressions allow us to create a truth table containing all possible outcomes involving each logical operator.
Input Values | AND | OR | XOR | NOT | |
---|---|---|---|---|---|
boolean foo | boolean bar | foo && bar | foo || bar | foo ^ bar | !foo |
false | false | false | false | false | true |
false | true | false | true | true | true |
true | false | false | true | true | false |
true | true | true | true | false | false |
Assignment
You've already used the assignment operator =
, but there are some other operators that do assignment and a little bit more. These were inherited from C/C++, and while cool if you're trying to be clever, most of the time you should not be clever but smart. Don't overuse these. One exception is within loops, where it's expected to see an increment operator (i++
). Here are some examples of assignment operators. See the References section for a complete list.
Example | Same As |
---|---|
a += b | a = a + b |
i++ | i = i + 1 |
Ternary Operator
One last operator is especially cool, acting like a test. The expression (a ? b : c)
(parentheses added for clarity) means: “If a
is true
, then yield the value b
; otherwise, yield the value c
.”
Review
Summary
Operators | Precedence |
---|---|
additive | + - |
assignment | = += -= *= /= %= &= ^= <<= >>= >>>= |
bitwise exclusive OR | ^ |
equality | == != |
logical AND | && |
logical OR | || |
multiplicative | * / % |
postfix | expr++ expr-- |
relational | < > <= >= instanceof |
shift | << >> >>> |
ternary | ? : |
unary | ++expr --expr +expr -expr ~ ! |
Gotchas
- Be careful not to use
=
(assignment) when you mean==
(equals). This trips up the best programmers! Thankfully the compiler will warn you if you use=
in an expression that is expected to yield a value. This is another reason to usefinal
whenever possible.
In the Real World
- When you create a complex expression, don't rely on order-of-precedence—use parentheses to remove all doubt and help your fellow developers understand the code.
- The ternary operator is neat and useful. Just don't overuse it, and please don't nest them unless you can make it completely clear what you're doing. The compiler will understand, but your teammates may not.
Think About It
- Is this expression so long that it needs to be split out into an extra variable so it can be understood more easily?
Self Evaluation
- What is the difference between a variable and an operator?
- What is the difference between
=
and==
? - What is the type of the value produced by the expression
5 == 3
? - What does it mean for an expression to "short-circuit"? Provide an example.
- How would you negate a Boolean expression?
- Explain how the ternary operator works.
- What is the difference between
++i
andi++
?
Task
Create a program that makes the following determinations using expressions:
- Create a variable that holds the result of an assignment of another variable.
- What is the floating point value of
(5 + 2) / 3
? - What is the floating point value of
0.1 + 0.2
? - If
17
people are in a room and5
of them leave, what percentage of the original group is still in the room? - Create a
boolean
variable holding the result of an expression evaluating whether Pluto is farther from the sun than Earth is from the sun. - After calculating the the slope of a line with a rise of
456
and a run of789
, print either"steep"
or"gradual"
, based upon whether the slope you calculated is greater than1
, using the ternary operator.
Create a compressed archive of your entire project directory and send it to your teacher as you have in previous lessons.
See Also
- Database Search Tips: Boolean operators (MIT Libraries)
- Comparing Floating Point Numbers, 2012 Edition (Random ASCII)
References
- Summary of Operators (Oracle - The Java™ Tutorials)
- Operator Precedence (Oracle - The Java™ Tutorials)
Acknowledgments
- Operator precedence table modified from the table in The Java™ Tutorials (Oracle).