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.
int x = 5; int y = ++x; int z = x--; System.out.println(x + "," + y + "," + z);
| Step | Expression | Variable x | Variable y | Variable z | Action | Output |
|---|---|---|---|---|---|---|
| 1 | int x = 5; | 5 | - | - | Initialize x to 5 | - |
| 2 | int y = ++x; | 6 | 6 | - | Prefix ++ increments x to 6, then y = 6 | - |
| 3 | int z = x--; | 5 | 6 | 6 | Postfix -- assigns z = 6, then decrements x to 5 | - |
| 4 | System.out.println(x + "," + y + "," + z); | 5 | 6 | 6 | Print values of x, y, z | 5,6,6 |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| x | - | 5 | 6 | 5 | 5 |
| y | - | - | 6 | 6 | 6 |
| z | - | - | - | 6 | 6 |
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.
What does the unary operator ++ do in Java?
++++ operator adds 1 to the current value of a variable.-- subtracts 1, ! flips boolean, and negation changes sign.++ means add one [OK]Which of the following is the correct **postfix** syntax to decrement a variable x by 1 using a unary operator?
int x = 5;
// Your code here
x-- and --x decrement by 1, but x-1 is an expression, not an operator.x--; correctly decreases x by 1 after its current use.x-- to subtract one [OK]What is the output of the following Java code?
int a = 3;
System.out.println(++a);
System.out.println(a++);
System.out.println(a);++a++a increases a before printing, so prints 4 and a becomes 4.a++a++ prints current a (4) then increases it to 5.aa is 5, so prints 5.Find the error in the following code snippet:
boolean flag = true;
flag = !flag++;
System.out.println(flag);flag is boolean; ++ operator works only on numeric types, not boolean.flag++ causes a compile-time error because booleans cannot be incremented.Given the code below, what will be the final value of count after execution?
int count = 0;
for (int i = 0; i < 3; i++) {
count = count++ + ++count;
}
System.out.println(count);count = count++ + ++count; behavior+ evaluates left operand first (count++: old value then increment), then right (++count: increment then new value).count++ value=0 (count=1), ++count value=2, sum=2 -> count=2.count++=2 (count=3), ++count=4, sum=6 -> count=6.count++=6 (count=7), ++count=8, sum=14 -> count=14.Pass the test and this pattern moves unknown