Expressions and Operators

So far in this chapter, we’ve learned about the primitive types that Java programs can manipulate and seen how to include primitive values as literals in a Java program. We’ve also used variables as symbolic names that represent, or hold, values. These literals and variables are the tokens out of which Java programs are built.

An expression is the next higher level of structure in a Java program. The Java interpreter evaluates an expression to compute its value. The very simplest expressions are called primary expressions and consist of literals and variables. So, for example, the following are all expressions:

1.7         // A floating-point literal
true        // A boolean literal
sum         // A variable

When the Java interpreter evaluates a literal expression, the resulting value is the literal itself. When the interpreter evaluates a variable expression, the resulting value is the value stored in the variable.

Primary expressions are not very interesting. More complex expressions are made by using operators to combine primary expressions. For example, the following expression uses the assignment operator to combine two primary expressions—a variable and a floating-point literal—into an assignment expression:

sum = 1.7

But operators are used not only with primary expressions; they can also be used with expressions at any level of complexity. The following are all legal expressions:

sum = 1 + 2 + 3*1.2 + (4 + 8)/3.0
sum/Math.sqrt(3.0 * 1.234)
(int)(sum + 33)

Operator Summary ...

Get Java in a Nutshell, 5th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.