Issue
int[] A = {1000000007,1000000007,1000000007};
This overflows
System.out.println("Bracket mul: "+(long) (A[0]*A[0]));
Output:
Bracket mul: -371520463
This doesnt - multiplication without brackets
System.out.println("Integer Multiplication: "+ (long) A[0]*A[0]);
Output:
Integer Multiplication: 1000000014000000049
I know how to make use of these now, but want to understand if typecasting is applied to first value and then operation is performed if brackets are not there ?
and if brackets are there, it is treated as integer literal operation, correct me if I am wrong
Solution
Here
(long) (A[0]*A[0])
you're doing a multiplication between integers and then casting the (already overflowed) result to long
.
Here
(long) A[0]*A[0]
which is read as
((long)A[0]) * A[0]
you're casting the first operand to long
, so the operation will be between long
s (because the second operand will be promoted to long
as well) and the result will be a long
and won't overflow.
Answered By - Federico klez Culloca
Answer Checked By - Candace Johnson (JavaFixing Volunteer)