0
0
Javaprogramming~10 mins

Unary operators in Java - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Unary operators
Start
Apply unary operator
Evaluate expression
Update variable if needed
Use result
End
Unary operators take one value, change or use it, then produce a result or update the variable.
Execution Sample
Java
int x = 5;
int y = ++x;
int z = x--;
System.out.println(x + "," + y + "," + z);
This code shows how prefix ++ and postfix -- unary operators change and use variable values.
Execution Table
StepExpressionVariable xVariable yVariable zActionOutput
1int x = 5;5--Initialize x to 5-
2int y = ++x;66-Prefix ++ increments x to 6, then y = 6-
3int z = x--;566Postfix -- assigns z = 6, then decrements x to 5-
4System.out.println(x + "," + y + "," + z);566Print values of x, y, z5,6,6
💡 All statements executed, program ends.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
x-5655
y--666
z---66
Key Moments - 3 Insights
Why does x become 6 before y gets its value in ++x?
Because ++x is prefix increment, it increases x first (step 2), then assigns that new value to y.
Why does z get 6 but x becomes 5 after x--?
Because x-- is postfix decrement, it assigns the current x (6) to z first (step 3), then decreases x to 5.
What is the difference between prefix ++ and postfix -- in this example?
Prefix ++ changes the variable before using it, postfix -- uses the variable first then changes it, as shown in steps 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x after step 3?
A7
B6
C5
D4
💡 Hint
Check the 'Variable x' column after step 3 in the execution_table.
At which step does y get its value assigned?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column for when y is assigned in the execution_table.
If we change ++x to x++, what would be the value of y after step 2?
A6
B5
C7
D4
💡 Hint
Remember postfix ++ uses the original value before incrementing, check variable_tracker for x changes.
Concept Snapshot
Unary operators use one operand.
Prefix ++ or -- changes value before use.
Postfix ++ or -- uses value then changes it.
Common unary operators: ++, --, +, -, !
They can update variables or produce new values.
Full Transcript
This example shows unary operators in Java. We start with x = 5. Then ++x increases x to 6 before assigning to y, so y becomes 6. Next, x-- assigns current x (6) to z, then decreases x to 5. Finally, printing x, y, z shows 5,6,6. Prefix operators change the variable before use; postfix operators use the variable then change it. This helps understand how unary operators affect variables step-by-step.