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. 47
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 - |
Decrement by one Raise by k's value assign modulus of 3 Switching true <--> false |
//Integer operations i = i - 1; i = i + k; i = i % 3; // boolean b = !b; |
No. 48
Guessing results
Q: |
Consider the following code segment:
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. 49
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
|