Unary operators
Increment variable by 1: | Shorthand version: |
---|---|
int a = 4;
a = a + 1;
System.out.println("Value:" + a); |
int a = 4;
a++;
System.out.println("Value:" + a); |
Value:5 |
Increment variable by 1: | Shorthand version: |
---|---|
byte value = 127; // Max possible value
value = value + 1; // Error: Required type: byte
// Provided:int
System.out.println(value); |
byte value = 127; // Max possible value
value++; // o.K., will cycle through range
System.out.println(value); |
Does not compile | Value:-128 |
Increment variable by 1: | Shorthand version: |
---|---|
byte value = 127; // Max possible value
value = (byte)(value + 1); // cast required,
// possible overflow
System.out.println(value); |
byte value = 127; // Max possible value
value++; // cycle through range,
// no cast required.
System.out.println(value); |
Value:-128 |
pre-increment | post-increment | ||
---|---|---|---|
int a = 4;
int b = ++a;
System.out.println(b); |
int a = 4;
int b = a++;
System.out.println(b); |
||
Output: | 5 |
Output: | 4 |
No. 52
Three ways expressing the same
Q: |
Write the statement TipUse different operators. |
A: |
|
Shorthand | Operation | Explicit |
---|---|---|
//Integer operations i--; i += k; i %= 3; // boolean - nothing appropriate - |
|
//Integer operations i = i - 1; i = i + k; i = i % 3; // boolean b = !b; |
No. 53
Guessing results
Q: |
Consider the following code segment: int a = 3; a++; // Incrementing a by 1 --> a==4 int b = a; // TODO b--; // TODO --b; // TODO int c = b; // TODO b = ++a; // TODO int e = a++; // TODO a *= b; // TODO System.out.println("a=" + a); System.out.println("b=" + b); System.out.println("c=" + c); System.out.println("e=" + e); Guess the expected result without executing the above code. Replace the TODO sections by explanations among with expected variable values. Then copy/paste the above code into a main() method body and control your findings (possibly wailing about your success rate). TipBoth |
A: |
As inferred by the hint the biggest problem is about
understanding postfix and infix notation of the operators
The remaining task is just obeying the “due diligence” rule set:
|
No. 54
Cleaning up the mess
Q: |
Some developers follow the rule “It was hard to write, it should be hard to understand as well”. One such proponent codes:
Execution results in: a = 7, b = 7, c = 1 Decompose this cryptic assignment into a series of
multiple elementary ones like e.g. TipRead about evaluation of expressions and operator precedence. |
A: |
We start by modifying the line in question:
The expression on the right hand side will be decomposed by the Java™ compiler into a sum of four subexpressions to be evaluated from left to right:
We introduce a helper variable
|