Sub topic 2
Unary Operators and Prefix versus Postfix
An operator is a symbol that performs an action. A unary operator acts on one value or variable, called its operand. For example, -count produces the negative of count without changing count.
The operators ++ and -- increase or decrease a variable by one. Their position matters when their result is used:
- Prefix, as in
++count, changes the variable first and produces the new value. - Postfix, as in
count++, produces the old value and then changes the variable.
Save and run this program as Operators.java:
public class Operators {
public static void main(String[] args) {
int count = 3;
int before = count++;
int after = ++count;
System.out.println(before); // 3
System.out.println(after); // 5
int n = 2;
int total = n++ + ++n;
System.out.println(total); // 6
System.out.println(n); // 4
boolean inRange = count >= 1 && count <= 5;
System.out.println(inRange); // true
int divisor = 0;
boolean safe = divisor != 0 && 10 / divisor > 1;
System.out.println(safe); // false
}
}An expression is code that produces a value. In count++, the expression produces 3, then count becomes 4. Next, ++count makes count become 5 and produces 5.
Evaluation Order and Side Effects
A side effect is a change made while an expression is being evaluated. Both ++ and -- change a variable.
Java evaluates operands from left to right. In n++ + ++n, the left operand produces 2 and changes n to 3. The right operand then changes n to 4 and produces 4. The sum is 6.
Avoid changing the same variable several times in one expression. Separate steps are easier to read.
Comparing Primitive Values
Primitive values are simple values such as numbers and true or false. Comparisons produce a boolean, a value that is either true or false.
==and!=mean equal and not equal.<,<=,>, and>=compare numeric values.
For example, count >= 1 is true when count is 5.
Combining Boolean Expressions
Use && for “and” and || for “or.” The unary operator ! means “not”: it changes true to false, or the reverse.
In the program, inRange is true because both comparisons are true.
Short-Circuit Evaluation
Short-circuit evaluation means Java can skip the right operand when the left one already determines the result. With &&, Java skips the right side if the left side is false. With ||, it skips the right side if the left side is true.
In the program, divisor != 0 is false, so Java skips the division. This prevents a division-by-zero error.
Exercise
If x starts at 2, what are the result of x++ + x and the final value of x?
Show answer
The result is 5, and x ends at 3. The left operand produces 2 and changes x to 3 before the right operand is read.