var = expr; |
Effect:
|
int a = 3; int b = 4; Arithmetic expression: a + b Returns the result: 7 |
var = expr |
Result returned by an assignment expression:
Result of var = expr is equal to the value of expr |
Note:
|
public class AssignExpr01 { public static void main(String[] args) { int a; a = 0; System.out.println(a); System.out.println(a = 2); // Prints 2 System.out.println(a); // Prints 2 } } |
Explanation:
|
How to run the program:
|
|
Operator | Example | Returned value |
---|---|---|
= | a = 2 | 2 |
+= | a += 2 | a + 2 |
-= | a -= 2 | a - 2 |
*= | a *= 2 | a * 2 |
/= | a /= 2 | a / 2 |
%= | a %= 2 | a % 2 |
public class AssignExpr02 { public static void main(String[] args) { int a; a = 5; System.out.println(a = 2); a = 5; System.out.println(a += 2); a = 5; System.out.println(a -= 2); a = 5; System.out.println(a *= 2); a = 5; System.out.println(a /= 2); a = 5; System.out.println(a %= 2); } } |
Output:
2 7 3 10 2 1 |
How to run the program:
|
|
|
public class AssignExpr03 { public static void main(String[] args) { int a, b, c; c = b = a = 4 + 2; // Cascade assignment System.out.println(a); // Prints 6 System.out.println(b); // Prints 6 System.out.println(c); // Prints 6 } } |
Explanation:
c = b = a = 4 + 2; is evaluated as follows: c = b = a = 4 + 2; higher priority ^^^^^ Reduces to: c = b = a = 6; from right to left ^^^^^ assigns 6 to variable a and returns 6 Reduces to: c = b = 6; from right to left ^^^^^ assigns 6 to variable b and returns 6 Reduces to: c = 6; assigns 6 to variable c (and returns 6) ^^^^^ |
How to run the program:
|
public class AssignExpr04 { public static void main(String[] args) { int a, b, c; a = 1; b = 1; c = 2; c *= b -= a += 1 + 2; System.out.println(a); System.out.println(b); System.out.println(c); } } |
Answer:
4 -3 -6 |
How to run the program:
|