Sub topic 1
Values, Operators, and Expressions
Values, Operators, and Expressions
An expression is a piece of Java code that produces a value. An operator is a symbol that performs an action. An operand is a value used by an operator.
For example, in 2 + 3, the operator is +, the operands are 2 and 3, and the result is 5. Expressions help programs calculate and build values.
Grouping Expressions with Precedence and Parentheses
Precedence is the rule that decides how operators are grouped. Multiplication comes before addition, so 2 + 3 * 4 is grouped as 2 + (3 * 4) and gives 14.
Parentheses can change the grouping: (2 + 3) * 4 gives 20. Use them when they make an expression easier to read. Operators such as * and / have the same precedence and group from left to right.
Arithmetic, Remainder, and String Concatenation
Java uses +, -, *, and / for addition, subtraction, multiplication, and division. The remainder operator % gives what is left after division: 7 % 2 is 1.
A String is a value that holds text. String concatenation means joining text with another value using +. For example, "Total: " + 5 produces "Total: 5".
Numeric Types, Promotion, Division, and Overflow
An int holds a whole number. A double holds a number that can have a decimal part.
When both operands of / are integers, Java drops the fractional part. Thus, 7 / 2 gives 3. In 7.0 / 2, Java converts the 2 to a double, so the result is 3.5. This conversion to a wider numeric type is called promotion.
Overflow happens when a result is outside a type’s range. For int, adding 1 to the largest value wraps around to the smallest value.
Assignment and Compound Assignment
Assignment stores a value in a variable. For example, score = 5 stores 5 in score.
Compound assignment combines an operation with assignment. If score is an int, score += 3 adds 3 to it and stores the result.
Worked Example
Save this program as Expressions.java and run it. The comments show its output.
public class Expressions {
public static void main(String[] args) {
System.out.println(2 + 3 * 4); // 14
System.out.println((2 + 3) * 4); // 20
System.out.println(7 % 2); // 1
System.out.println("Total: " + 5); // Total: 5
System.out.println(7 / 2); // 3
System.out.println(7.0 / 2); // 3.5
System.out.println(Integer.MAX_VALUE + 1); // -2147483648
int score = 5;
score += 3;
System.out.println(score); // 8
}
}Exercise
If int n = 10; is followed by n += 3 * 2;, what are the values of n and n / 4?
Show answer
n is 16, because multiplication is grouped first. n / 4 is 4, using integer division.