Sub topic 1
Values, Operators, and Expressions
Java programs work with values, such as numbers and text. An expression is a piece of code that Java can evaluate, or work out. In this chapter, each expression produces a value called its result.
For example, 3 * 4 is an expression. Java works it out to get the result 12.
An operator is a symbol that tells Java what action to perform. In 3 * 4, the operator * tells Java to multiply. An operand is an expression that an operator uses. Here, 3 and 4 are the operands.
Values can come from variables
A literal is a value written directly in code, such as 4. A variable is a named place to store a value. A variable name can also be an expression: Java reads the value stored in that variable.
Try this complete program. Save it in a file named ExpressionsDemo.java, then run it as you normally run a Java program.
public class ExpressionsDemo {
public static void main(String[] args) {
int price = 8;
int items = 3;
int total = price * items;
boolean expensive = total > 20;
System.out.println(price);
System.out.println(total);
System.out.println(expensive);
}
}System.out.println displays a value on the screen. The program displays these results, in order:
824true
Follow the expressions
The program first stores 8 in price and 3 in items. It then evaluates price * items. The operands are price and items, so Java uses their stored values, 8 and 3. The result is 24, which is stored in total.
A statement is a complete instruction in a Java program. The line int total = price * items; is a statement. It contains the expression price * items.
Next, Java evaluates total > 20. The operator > asks whether its left operand is greater than its right operand. Since total holds 24, the result is true.
| Expression | Operands | Result |
|---|---|---|
| `8` | None; it is a literal | `8` |
| `price` | None; it is a variable name | `8` |
| `price * items` | `price` and `items` | `24` |
| `total > 20` | `total` and `20` | `true` |
Results have types
A type describes what kind of value Java is working with. The expression price * items produces an int, a type for whole numbers. The expression total > 20 produces a boolean, a type with two possible values: true and false.
The expression matters, not just the symbols it contains. For example, 20 is a number, but total > 20 answers a question and produces a boolean value.
Exercise
If price is 5 and items is 4, what are the operands and result of price * items?
Show answer
The operands are price and items. Their values are 5 and 4, so the result is 20.
Exercise
If total is 20, what is the result of total > 20?
Show answer
false, because 20 is not greater than 20.