public static void main(String[] args) {
int A=5;
int B=2;
A *= B*= A *= B ;
System.out.println(A);
System.out.println(B);
}
When I calculated this problem on paper I found A=200 B=20
, but when I write it down to eclipse it shows A=100 B=20
Can you explain the solution like solving on the paper?
I tried to solve in Eclipse and by myself.
How do we solve it?
so. a -= b is equivalent to a = a - b. a *= b is equivalent to a = a * b. a /= b is equivalent to a = a / b.
In Java, the *= is called a multiplication compound assignment operator. It's a shortcut for density = density * invertedRatio; Same abbreviations are possible e.g. for: String x = "hello "; x += "world" // results in "hello world" int y = 100; y -= 42; // results in y == 58.
Thus in case of i+++j , we have original value of i when expression is evaluated, and i is incremented after the evaluation is completed. In case of ++j since its prefix value is incremented before evaluation. This i+++j is equal to (i++)+j and i+ ++j is equivalent to i + (++j) .
The difference between both the concatenation operators is that the + creates a new list and the += modifies an existing list in place.
Starting off with A=5
, B=2
A
becomes A * B * A * B
, which is 100, and
B
becomes B * A * B
, which is 20.
In more detail:
A *= B *= A *= B
is
A = A * (B = B * (A = A * B))
That resolves to
A = 5 * (B = 2 * (A = 5 * 2))
which means
A = 5 * (B = 2 * (A = 10)) // set A to 10
A = 5 * (B = 2 * 10)
A = 5 * (B = 20) // set B to 20
A = 5 * 20
A = 100 // set A to 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With