Assignment operators
Increment variable by right hand value:
int a = 4;
a = a + 2;
System.out.println("Value:" + a); |
int a = 4;
a += 2;
System.out.println("Value:" + a); |
Value:6 |
No. 45
Strange addition
Q: |
Execute the following snippet and explain its result:
|
A: |
In binary representation starting from Byte.MAX_VALUE we'd see: 01111111 127 + 1 + 1 -------- ---- 10000000 128 But a byte variable is being represented as 1-byte 2 complement: 01111111 127 + 1 + 1 Overflow! -------- ---- 10000000 -128 Note that assigning b = b + 1 yields a compile time error instead: Required type: byte Provided: int Conclusion: the |
Logical and
operation:
boolean examSuccess = true,
registered = false;
examSuccess = examSuccess & registered;
System.out.println(
"Exam success:" + examSuccess); |
boolean examSuccess = true,
registered = false;
examSuccess &= registered;
System.out.println(
"Exam success:" + examSuccess); |
Exam success:false |
= |
Assign right to left operand | Example using %= |
+= |
Assign sum of operands to left operand |
|
-= |
Assign difference of operands to left operand | |
*= |
Assign product of operands to left operand | |
/= |
Assign quotient of operands to left operand | |
%= |
Assign remainder of operands to left operand | Result=3 |
&= |
Assign logical “and” of operands to left operand |
|= |
Assign logical “or” of operands to left operand |
No. 46
Understanding +=
Q: |
Consider the following snippet:
This will compile and execute thereby incrementing the
On the other hand the
So why is |
||||
A: |
The Java® Language Specification SE 19 Edition offers a definition in its Compound Assignment Operators section:
We provide an example illustrating this rather condensed statement: double d = 4.5; byte i = 3; i += d ; // E1 op= E2 We thus link:
Our variable
Back to our original example: According to Figure 120, “No binary + operator yielding
NoteSince
On contrary regarding the
Notice 24 being equal to |